repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
yvorobey/adversarialMI
[ "8950623c3946ee917ecf21262c52c98a8689b1a1" ]
[ "l2_attack.py" ]
[ "# modified by Huahong Zhang <huahong.zhang@vanderbilt.edu> to fit the L2 algorithm mentioned in the paper\n# original copyright license follows.\n\n# Copyright (c) 2016 Nicholas Carlini\n#\n# LICENSE\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport tensorflow as tf\nimport numpy as np\nfrom feature import RawImage, ImageWithMas\nfrom brainage import BrainAgeModel1, BrainAgeModel2\n\nBINARY_SEARCH_STEPS = 10 # number of times to adjust the constant with binary search\nMAX_ITERATIONS = 1000 # number of iterations to perform gradient descent\nABORT_EARLY = True # if we stop improving, abort gradient descent early\nLEARNING_RATE = 1e-2 # larger values converge faster to less accurate results\nCONFIDENCE = 0 # how strong the adversarial example should be\nINITIAL_CONST = 1e1 # the initial constant c to pick as a first guess\nTHRESHOLD = 1\n\n\nclass CarliniL2:\n def __init__(self, sess, model, batch_size=1, confidence = CONFIDENCE,\n learning_rate = LEARNING_RATE,\n binary_search_steps = BINARY_SEARCH_STEPS, max_iterations = MAX_ITERATIONS,\n abort_early = ABORT_EARLY, \n initial_const = INITIAL_CONST,\n direction='max'):\n \"\"\"\n The L_2 optimized attack. \n\n This attack is the most efficient and should be used as the primary \n attack to evaluate potential defenses.\n\n Returns adversarial examples for the supplied model.\n\n confidence: Confidence of adversarial examples: higher produces examples\n that are farther away, but more strongly classified as adversarial.\n batch_size: Number of attacks to run simultaneously.\n targeted: True if we should perform a targetted attack, False otherwise.\n learning_rate: The learning rate for the attack algorithm. Smaller values\n produce better results but are slower to converge.\n binary_search_steps: The number of times we perform binary search to\n find the optimal tradeoff-constant between distance and confidence. \n max_iterations: The maximum number of iterations. Larger values are more\n accurate; setting too small will require a large learning rate and will\n produce poor results.\n abort_early: If true, allows early aborts if gradient descent gets stuck.\n initial_const: The initial tradeoff-constant to use to tune the relative\n importance of distance and confidence. If binary_search_steps is large,\n the initial constant is not important.\n boxmin: Minimum pixel value (default -0.5).\n boxmax: Maximum pixel value (default 0.5).\n \"\"\"\n\n # image_size, num_channels, num_labels = model.image_size, model.num_channels, model.num_labels\n self.sess = sess\n self.LEARNING_RATE = learning_rate\n self.MAX_ITERATIONS = max_iterations\n self.BINARY_SEARCH_STEPS = binary_search_steps\n self.ABORT_EARLY = abort_early\n self.CONFIDENCE = confidence\n self.initial_const = initial_const\n self.batch_size = batch_size\n self.repeat = binary_search_steps >= 10\n self.direction = direction\n\n shape = (batch_size, model.shape[0], model.shape[1], model.shape[2], model.shape[3])\n \n # the variable we're going to optimize over\n modifier = tf.Variable(np.zeros(shape,dtype=np.float32))\n\n # these are variables to be more efficient in sending data to tf\n self.timg = tf.Variable(np.zeros(shape), dtype=tf.float32)\n self.const = tf.Variable(np.zeros(batch_size), dtype=tf.float32)\n self.mas = tf.Variable(np.zeros([batch_size, 134]), dtype=tf.float32)\n\n self.boxmul = tf.Variable(np.zeros(batch_size), dtype=tf.float32)\n self.boxplus = tf.Variable(np.zeros(batch_size), dtype=tf.float32)\n\n # and here's what we use to assign them\n self.assign_timg = tf.placeholder(tf.float32, shape)\n self.assign_tlab = tf.placeholder(tf.float32, [batch_size])\n self.assign_const = tf.placeholder(tf.float32, [batch_size])\n self.assign_mas = tf.placeholder(tf.float32, [batch_size, 134])\n\n self.assign_boxmul = tf.placeholder(tf.float32, [batch_size])\n self.assign_boxplus = tf.placeholder(tf.float32, [batch_size])\n \n # the resulting image, tanh'd to keep bounded from boxmin to boxmax\n self.newimg = tf.tanh(modifier + self.timg) * self.boxmul + self.boxplus\n\n if isinstance(model, BrainAgeModel2):\n self.output = model.predict([self.newimg, self.mas])\n self.org_output = model.predict([tf.tanh(self.timg)* self.boxmul + self.boxplus, self.mas])\n else:\n self.output = model.predict(self.newimg)\n self.org_output = model.predict(tf.tanh(self.timg) * self.boxmul + self.boxplus)\n \n # distance to the input data\n self.l2dist = tf.reduce_sum(tf.square(self.newimg-(tf.tanh(self.timg) * self.boxmul + self.boxplus)),[1,2,3,4])\n\n # modified here\n if self.direction == 'max':\n loss1 = -self.output + self.org_output\n else:\n loss1 = self.output - self.org_output\n\n # sum up the losses\n self.loss2 = tf.reduce_sum(self.l2dist)\n self.loss1 = tf.reduce_sum(self.const*loss1)\n self.loss = self.loss1+self.loss2\n \n # Setup the adam optimizer and keep track of variables we're creating\n start_vars = set(x.name for x in tf.global_variables())\n optimizer = tf.train.AdamOptimizer(self.LEARNING_RATE)\n self.train = optimizer.minimize(self.loss, var_list=[modifier])\n end_vars = tf.global_variables()\n new_vars = [x for x in end_vars if x.name not in start_vars]\n\n # these are the variables to initialize when we run\n self.setup = []\n self.setup.append(self.timg.assign(self.assign_timg))\n self.setup.append(self.const.assign(self.assign_const))\n self.setup.append(self.boxmul.assign(self.assign_boxmul))\n self.setup.append(self.boxplus.assign(self.assign_boxplus))\n\n if isinstance(model, BrainAgeModel2):\n self.setup.append(self.mas.assign(self.assign_mas))\n \n self.init = tf.variables_initializer(var_list=[modifier]+new_vars)\n\n def attack(self, imgs, eps, mas=None):\n \"\"\"\n Perform the L_2 attack on the given images for the given targets.\n\n If self.targeted is true, then the targets represents the target labels.\n If self.targeted is false, then targets are the original class labels.\n \"\"\"\n r = []\n print('go up to',len(imgs))\n for i in range(0,len(imgs),self.batch_size):\n print('tick', i)\n raw_images = np.array([x.raw_image for x in imgs[i:i + self.batch_size]])\n max_values = np.array([x.max_value for x in imgs[i:i + self.batch_size]])\n min_values = np.array([x.min_value for x in imgs[i:i + self.batch_size]])\n if isinstance(imgs[0], RawImage):\n res = self.attack_batch(raw_images, eps, max_values, min_values)\n r.extend([RawImage(res[i]) for i in range(self.batch_size)])\n elif isinstance(imgs[0], ImageWithMas):\n mas_feats = [x.mas for x in imgs[i:i+self.batch_size]]\n res = self.attack_batch(raw_images, eps, max_values, min_values, mas_feats)\n r.extend([ImageWithMas(res[i], mas_feats[i]) for i in range(self.batch_size)])\n else:\n raise Exception('Invalid data')\n\n # r.extend(self.attack_batch(imgs[i:i+self.batch_size], targets[i:i+self.batch_size]))\n\n return r\n\n def attack_batch(self, imgs, eps, max_values, min_values, mas_feats=None):\n \"\"\"\n Run the attack on a batch of images and labels.\n \"\"\"\n def compare(x, y):\n return (x>y and self.direction==\"max\") or (x<y and self.direction==\"min\")\n\n eps = [eps[0]*(max_values[0]-min_values[0])*(max_values[0]-min_values[0])]\n\n batch_size = self.batch_size\n\n # convert to tanh-space\n boxmul = (max_values - min_values)/2\n boxplus = (max_values + min_values)/2\n imgs = np.arctanh((imgs - boxplus) / boxmul * 0.999999)\n\n # set the lower and upper bounds accordingly\n lower_bound = np.zeros(batch_size)\n CONST = np.ones(batch_size) * self.initial_const\n upper_bound = np.ones(batch_size) * 1e10\n\n # the best l2, score, and image attack\n # o_bestl2 = [1e10]*batch_size\n o_bestscore = [-1]*batch_size if self.direction == \"max\" else [1e10]*batch_size\n o_bestattack = [np.zeros(imgs[0].shape)]*batch_size\n\n for outer_step in range(self.BINARY_SEARCH_STEPS):\n print('STEP: %d, EPS: %f, CONST: %f, o_bestscore: %f' % (outer_step, eps[0], CONST[0], o_bestscore[0]))\n # completely reset adam's internal state.\n self.sess.run(self.init)\n batch = imgs[:batch_size]\n\n # The last iteration (if we run many steps) repeat the search once.\n if self.repeat == True and outer_step == self.BINARY_SEARCH_STEPS - 1:\n CONST = upper_bound\n\n # set the variables so that we don't have to send them over again\n if not mas_feats:\n self.sess.run(self.setup, {self.assign_timg: batch,\n self.assign_const: CONST,\n self.assign_boxmul: boxmul,\n self.assign_boxplus: boxplus})\n else:\n batchmas = mas_feats[:batch_size]\n self.sess.run(self.setup, {self.assign_timg: batch,\n self.assign_mas: batchmas,\n self.assign_const: CONST,\n self.assign_boxmul: boxmul,\n self.assign_boxplus: boxplus})\n\n # bestl2 = [1e10] * batch_size\n org_score = self.sess.run(self.org_output)[0][0]\n print(\"org_score\", org_score)\n bestscore = [org_score+0.01] * batch_size if self.direction == \"max\" else [org_score-0.01] * batch_size\n\n prev = 1e6\n found = False\n for iteration in range(self.MAX_ITERATIONS):\n # perform the attack\n _, l, l2s, scores, nimg = self.sess.run([self.train, self.loss,\n self.l2dist, self.output,\n self.newimg])\n\n # print out the losses every 10%\n if iteration % (self.MAX_ITERATIONS // 10) == 0:\n print(iteration, \"loss: %f\" % l, 'l1: %f' % (l - l2s), 'l2: %f' % l2s, 'score %f' % scores)\n # print(iteration, self.sess.run((self.loss,self.loss1,self.loss2)), )\n\n # check if we should abort search if we're getting nowhere.\n if self.ABORT_EARLY and iteration % (self.MAX_ITERATIONS // 10) == 0:\n if l > prev * .9999:\n break\n prev = l\n\n # adjust the best result found so far\n for e, (l2, sc, ii) in enumerate(zip(l2s, scores, nimg)):\n if l2 < eps and compare(sc[0], bestscore[e]):\n bestscore[e] = sc[0]\n found = True\n if l2 < eps and compare(sc, o_bestscore[e]):\n print(\"Found better result\", sc[0], o_bestscore[e])\n o_bestscore[e] = sc[0]\n o_bestattack[e] = ii\n\n # adjust the constant as needed\n # the updates are different from the original version\n for e in range(batch_size):\n if found:\n lower_bound[e] = max(lower_bound[e], CONST[e])\n if upper_bound[e] < 1e9:\n CONST[e] = (lower_bound[e] + upper_bound[e]) / 2\n else:\n CONST[e] *= 2\n else:\n upper_bound[e] = min(upper_bound[e], CONST[e])\n if upper_bound[e] < 1e9:\n CONST[e] = (lower_bound[e] + upper_bound[e]) / 2\n\n # return the best solution found\n return o_bestattack\n" ]
[ [ "numpy.arctanh", "tensorflow.reduce_sum", "tensorflow.global_variables", "tensorflow.variables_initializer", "tensorflow.placeholder", "numpy.ones", "tensorflow.tanh", "tensorflow.train.AdamOptimizer", "numpy.array", "numpy.zeros" ] ]
edges-collab/edges-analysis
[ "b5165c55b7ae4334f6ac0578ade76ad875612605" ]
[ "examples/mid_band_polychord.py" ]
[ "#!/usr/bin/python\n\"\"\"\nAn example of running polychord for mid-band data.\n\nHow to run::\n\n python mid_band_polychord.py 0 5\n\"\"\"\n\nimport sys\nfrom os import makedirs\nfrom os.path import exists\n\nimport numpy as np\nimport PyPolyChord\nfrom PyPolyChord.settings import PolyChordSettings\n\nfrom edges_analysis.estimate.tools import dumper\nfrom edges_analysis.simulation import data_models as dm\nfrom edges_analysis.config import config\n\n\ndef prior_list(N21, n_fg, model_type_signal, model_type_foreground):\n pl = np.zeros((Nparameters, 2))\n pl[:, 0] = -1e4\n pl[:, 1] = +1e4\n\n if model_type_signal in [\"exp\", \"tanh\"] and N21 >= 4:\n\n # Amplitude\n pl[0, 0] = -2\n pl[0, 1] = 2 # 0\n\n # Center\n pl[1, 0] = 58 # 61\n pl[1, 1] = 128 # 149 #119 #100\n\n # Width\n pl[2, 0] = 2\n pl[2, 1] = 70 # 60 #30\n\n # Tau\n pl[3, 0] = 0.01\n pl[3, 1] = 20\n\n if (model_type_signal == \"exp\") and (N21 == 5):\n # Tau\n pl[4, 0] = -10\n pl[4, 1] = 10\n\n if (model_type_signal == \"tanh\") and (N21 == 5):\n # Tau\n pl[4, 0] = 0.01\n pl[4, 1] = 20\n\n if model_type_foreground == \"linlog\":\n # Temperature at reference frequency\n pl[N21, 0] = 100 # lower limit of first parameter, temperature at 100 MHz\n pl[N21, 1] = 10000 # upper limit of first parameter, temperature at 100 MHz\n elif model_type_foreground == \"powerlog\":\n # Temperature at reference frequency\n pl[N21, 0] = 100 # lower limit of first parameter, temperature at 100 MHz\n pl[N21, 1] = 10000 # upper limit of first parameter, temperature at 100 MHz\n\n # Spectral index\n pl[N21 + 1, 0] = -2.0\n pl[N21 + 1, 1] = -3.0\n return pl\n\n\ndef loglikelihood(theta):\n N = len(v)\n\n # Evaluating model\n m = dm.full_model(\n theta,\n v,\n v0,\n model_type_signal=model_type_signal,\n model_type_foreground=model_type_foreground,\n n_21=N21,\n n_fgpar=n_fg,\n )\n\n # Log-likelihood\n DELTA = t - m\n lnL2 = -(1 / 2) * np.dot(np.dot(DELTA, inv_sigma), DELTA) - (N / 2) * np.log(\n 2 * np.pi\n ) # -(1/2)*np.log(det_sigma)\n # lnL2 = #-(1/2)*np.log(det_sigma)\n\n # This solves numerical errors\n if np.isnan(lnL2):\n print(\"True\")\n lnL2 = -np.infty\n\n return lnL2, 0\n\n\ndef prior(cube):\n \"\"\"\n\n A function defining the transform between the parameterisation in the unit hypercube to the\n true parameters.\n\n Args: cube (array, list): a list containing the parameters as drawn from a unit hypercube.\n\n Returns:\n list: the transformed parameters.\n\n \"\"\"\n\n theta = np.zeros(len(cube))\n\n pl = prior_list(N21, n_fg, model_type_signal, model_type_foreground)\n\n for i in range(len(cube)):\n theta[i] = cube[i] * (pl[i, 1] - pl[i, 0]) + pl[i, 0]\n\n return theta\n\n\ndef run():\n settings = PolyChordSettings(Nparameters, Nderived)\n settings.base_dir = save_folder\n settings.file_root = save_file_name\n settings.do_clustering = True\n settings.read_resume = False\n PyPolyChord.run_polychord(\n loglikelihood, Nparameters, Nderived, settings, prior, dumper\n )\n\n\nif __name__ == \"__main__\":\n # Input parameters\n # -----------------------\n save_folder = (\n config[\"edges_folder\"] + \"mid_band/polychord/20190910/case101_GHA_6-18hr\"\n \"/foreground_linlog_5par_signal_exp_4par/\"\n )\n\n data = \"real\" # it could be 'real' or 'simulated'\n case = 101 # 0=nominal\n f_low = 58 # 58\n f_high = 118 # 128\n v0 = 90\n\n n_fg = int(sys.argv[1])\n N21 = int(sys.argv[2])\n\n gap_f_low = 0 # nominal value: 0\n gap_f_high = 0 # nominal_value: 0\n\n model_type_foreground = \"linlog\" # , 'linlog', 'powerlog'\n model_type_signal = \"exp\" # 'exp' #, 'tanh'\n\n if not exists(save_folder):\n makedirs(save_folder)\n save_file_name = \"chain\" # sys.argv[3]\n\n # Constants\n # -----------------------\n Nparameters = N21 + n_fg\n Nderived = 0\n\n # Data\n # -------------------------------------------------\n # Choose to work either with simulated or real data\n if data == \"simulated\":\n v = np.arange(61, 159, 0.39)\n\n # t, sigma, inv_sigma, det_sigma = dm.simulated_data([-0.5, 78, 19, 7, 1000, -2.5, -0.1, 1,\n # 1], v, v0, 0.02, model_type_signal='exp', model_type_foreground='exp', n_21=4,\n # n_fgpar=5)\n t, sigma, inv_sigma, det_sigma = dm.simulated_data(\n [1000, -2.5, -0.1, 1, 1],\n v,\n v0,\n 0.01,\n model_type_signal=\"exp\",\n model_type_foreground=\"exp\",\n N21par=0,\n n_fgpar=5,\n )\n\n elif data == \"real\":\n v, t, w, sigma, inv_sigma, det_sigma = dm.real_data(\n case, f_low, f_high, gap_f_low=gap_f_low, gap_f_high=gap_f_high\n )\n\n run()\n" ]
[ [ "numpy.dot", "numpy.log", "numpy.isnan", "numpy.arange", "numpy.zeros" ] ]
Fieldhunter/2020-ZhanJiang-Underwater-Object-Detection-Algorithm-Contest
[ "b3d5e756766cff352acd2a0636e167f09f225514" ]
[ "data_augmention/getTransmissionMap.py" ]
[ "import numpy as np\r\ndef getMinChannel(img,AtomsphericLight):\r\n imgGrayNormalization = np.zeros((img.shape[0], img.shape[1]), dtype=np.float16)\r\n for i in range(0, img.shape[0]):\r\n for j in range(0, img.shape[1]):\r\n localMin = 1\r\n for k in range(0, 3):\r\n # print('AtomsphericLight[k]',AtomsphericLight[k])\r\n imgNormalization = img.item((i, j, k)) / AtomsphericLight[k]\r\n if imgNormalization < localMin:\r\n localMin = imgNormalization\r\n imgGrayNormalization[i, j] = localMin\r\n # print('imgGrayNormalization',imgGrayNormalization)\r\n # print('np.max(imgGrayNormalization)',np.max(imgGrayNormalization))\r\n return imgGrayNormalization\r\n\r\ndef getTransmission(img,AtomsphericLight ,blockSize):\r\n img = np.float16(img)\r\n img = getMinChannel(img,AtomsphericLight)\r\n AtomsphericLight = AtomsphericLight / 255.0\r\n addSize = int((blockSize - 1) / 2)\r\n newHeight = img.shape[0] + blockSize - 1\r\n newWidth = img.shape[1] + blockSize - 1\r\n # 中间结果\r\n imgMiddle = np.zeros((newHeight, newWidth))\r\n imgMiddle[:, :] = 1\r\n imgMiddle[addSize:newHeight - addSize, addSize:newWidth - addSize] = img\r\n # print('imgMiddle',imgMiddle)\r\n imgDark = np.zeros((img.shape[0], img.shape[1]))\r\n localMin = 1\r\n for i in range(addSize, newHeight - addSize):\r\n for j in range(addSize, newWidth - addSize):\r\n localMin = 1\r\n for k in range(i - addSize, i + addSize + 1):\r\n for l in range(j - addSize, j + addSize + 1):\r\n if imgMiddle.item((k, l)) < localMin:\r\n localMin = imgMiddle.item((k, l))\r\n imgDark[i - addSize, j - addSize] = localMin\r\n transmission = (1 - imgDark) / (1 - 0.1 / np.max(AtomsphericLight))\r\n transmission = np.clip(transmission, 0.1, 0.9)\r\n # for i in range(0, transmission.shape[0]):\r\n # for j in range(0, transmission.shape[1]):\r\n # if transmission[i, j] < 0.01:\r\n # transmission[i, j] = 0.01\r\n # if transmission[i, j] > 0.99:\r\n # transmission[i, j] = 0.99\r\n\r\n return transmission" ]
[ [ "numpy.max", "numpy.float16", "numpy.zeros", "numpy.clip" ] ]
AmanVirmani/LucasKanadeTracker
[ "c64c858d1cffe0957a0b35e0aede9414593eea4c" ]
[ "InverseCompositionAffine.py" ]
[ "#!/usr/bin/python3\n\n'''\n16-720B Computer Vision (Fall 2018)\nHomework 3 - Lucas-Kanade Tracking and Correlation Filters\n'''\n\n__author__ = \"Heethesh Vhavle\"\n__credits__ = [\"Simon Lucey\", \"16-720B TAs\"]\n__version__ = \"1.0.1\"\n__email__ = \"heethesh@cmu.edu\"\n\nimport numpy as np\nfrom scipy.ndimage import shift, affine_transform\nfrom scipy.interpolate import RectBivariateSpline\n\n\ndef InverseCompositionAffine(It, It1, threshold=0.005, iters=50):\n '''\n [input]\n * It - Template image\n * It1 - Current image\n * threshold - Threshold for error convergence (default: 0.005)\n * iters - Number of iterations for error convergence (default: 50)\n \n [output]\n * M - Affine warp matrix [2x3 numpy array]\n '''\n\n # Initial parameters\n #x1, y1, x2, y2 = rectangle[0], rectangle[1], rectangle[2], rectangle[3]\n M = np.asarray([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])\n I = M\n\n # Step 3 - Compute the gradient for template\n gradient = np.dstack(np.gradient(It)[::-1])\n gradient = gradient.reshape(gradient.shape[0] * gradient.shape[1], 2).T\n\n # Step 4 - Evaluate jacobian parameters\n H, W = It.shape\n Jx = np.tile(np.linspace(0, W-1, W), (H, 1)).flatten()\n Jy = np.tile(np.linspace(0, H-1, H), (W, 1)).T.flatten()\n #H, W = 50,50 # It.shape\n #Jx = np.tile(np.linspace(x1, x2, W), (H, 1)).flatten()\n #Jy = np.tile(np.linspace(y1, y2, H), (W, 1)).T.flatten()\n\n # Step 5 - Compute the steepest descent images\n steepest_descent = np.vstack([gradient[0] * Jx, gradient[0] * Jy,\n gradient[0], gradient[1] * Jx, gradient[1] * Jy, gradient[1]]).T\n \n # Step 6 - Compute the Hessian matrix\n hessian = np.matmul(steepest_descent.T, steepest_descent)\n\n # Iterate \n for i in range(iters):\n # Step 1 - Warp image\n warp_img = affine_transform(It1, np.flip(M)[..., [1, 2, 0]])\n\n # Step 2 - Compute error image with common pixels\n mask = affine_transform(np.ones(It1.shape), np.flip(M)[..., [1, 2, 0]])\n error_img = (mask * warp_img) - (mask * It)\n\n # Step 7/8 - Compute delta P\n delta_p = np.matmul(np.linalg.inv(hessian), np.matmul(steepest_descent.T, error_img.flatten()))\n \n # Step 9 - Update the parameters\n dM = np.vstack([delta_p.reshape(2, 3) + I, [0, 0, 1]])\n M = np.matmul(M, np.linalg.inv(dM))\n\n # Test for convergence\n if np.linalg.norm(delta_p) <= threshold: break\n\n return M\n\n" ]
[ [ "numpy.linspace", "numpy.gradient", "numpy.asarray", "numpy.linalg.inv", "numpy.matmul", "numpy.linalg.norm", "numpy.ones", "numpy.flip", "numpy.vstack" ] ]
liammagee/data-analytics
[ "ef7d47603427856030d85aedea0ffec7ffbf54e5" ]
[ "common.py" ]
[ "# Imports\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport savReaderWriter\nimport seaborn as sns\n\n\n\n\nclass DataSet:\n def __init__(self, filename = None):\n self.data = {}\n self.metadata = {}\n if filename != None:\n self.load_spss_files(filename)\n self.assign_columns()\n\n # Functions\n def load_spss_files(self, filename):\n with savReaderWriter.SavHeaderReader(filename) as header:\n self.metadata = header.all()\n with savReaderWriter.SavReader(filename) as reader:\n self.data = pd.DataFrame(list(reader))\n\n def assign_columns(self):\n self.data.columns = [x.decode('utf-8') for x in self.metadata.varNames]\n\n def get_var_label(self, var):\n key = bytes(var, encoding='utf-8')\n if key in self.metadata.varLabels:\n return self.metadata.varLabels[bytes(var, encoding='utf-8')].decode('windows-1252')\n else:\n return None\n\n def get_value_labels(self, var):\n key = bytes(var, encoding='windows-1252')\n if key in self.metadata.valueLabels:\n return dict([(k, v.decode('windows-1252')) for k, v in self.metadata.valueLabels[key].items()])\n else:\n return None\n\n def freq_table(self, var, weights = True, weight_col = 'WEIGHT'):\n value_labels = self.get_value_labels(var)\n var_label = self.get_var_label(var)\n if value_labels != None:\n return pd.DataFrame(list(self.get_value_labels(var).items()), columns=['index', self.get_var_label(var)]) \\\n .set_index('index', drop=True) \\\n .merge(pd.DataFrame({ 'Freq.': self.data[var].value_counts().sort_index(),\n 'Freq. Rel.': np.round(100. * self.data[var].value_counts().sort_index() / np.size(self.data[var]), 1),\n 'Freq. Weighted': self.data.groupby(var).apply(lambda x: np.sum(x[weight_col])),\n 'Freq. Weighted Rel.': np.round(100. * self.data.groupby(var).apply(lambda x: np.sum(x[weight_col])) / np.sum(self.data[weight_col]), 1),\n }), \\\n left_index = True, right_index = True)\n else:\n return pd.DataFrame(self.data[var].value_counts().sort_index())\n\n\n def gen_histogram(self, cols, stacked = True, legend_labels = None, normalise = False, use_weights = True):\n import tabulate\n from IPython.display import HTML, display\n \n # For cases where weights are included, get the first column along\n col = cols[0]\n \n # Print the variable name\n display(HTML(\"<strong>\"+self.get_var_label(col)+\"<strong>\"))\n display(HTML(\"<br/>\"))\n\n # Set up the plot\n fig, ax = plt.subplots()\n labels = self.get_value_labels(col).values()\n bin_length = len(labels)\n \n # If legend labels exist, split the data by the first index value (assumes len(legend_labels) == len(self.data.index.levels))\n if legend_labels != None and hasattr(self.data.index, 'levels') and len(legend_labels) == len(self.data.index.levels):\n d = pd.DataFrame(self.data[cols].dropna(), index = self.data.index).unstack(level=0).as_matrix().T\n d = np.array([x[~np.isnan(x)] for x in d])\n else:\n d = self.data[cols].dropna()\n \n values, weights = np.split(d, 2)\n \n if use_weights == False:\n weights = [np.ones(len(x)) for x in weights]\n if stacked == False and normalise == True:\n hists = [np.histogram(x, np.arange(1, bin_length + 2) - 0.5, weights = weights[i]) for i, x in enumerate(values)]\n hists_norm = [(100. * x / np.sum(x), y) for (x, y) in hists]\n offset = 1. / (len(hists_norm) + 1)\n [ax.bar(x[1][:-1] + offset * i, x[0], width = 0.3, label = legend_labels[i]) for i, x in enumerate(hists_norm)];\n bins = np.array(hists)[0, 1]\n n = [np.round(x[0], 1) for x in hists_norm] # np.array(hists)[:, 0]\n else:\n n, bins, patches = ax.hist(values, weights = weights, bins = np.arange(1, bin_length + 2) - 0.5, rwidth = 0.8, stacked=stacked, label = legend_labels)\n\n # Add grid\n ax.grid(True)\n \n # Legend\n if legend_labels != None:\n ax.legend(prop={'size': 10})\n\n # Apply colours\n cm = plt.get_cmap('Blues')\n #for c, patch in zip(bns, patches):\n # patch.set_facecolor(cm(c))\n\n bin_centers = 0.5 * (bins[:-1] + bins[1:])\n # scale values to interval [0,1]\n bns = bin_centers - min(bin_centers)\n bns /= max(bns)\n\n # rescale values to interval [0.2,0.8]\n scale_inc = 0.2\n bns *= (1.0 - scale_inc * 2.)\n bns += scale_inc\n\n # Add title and axes\n # plt.title(self.get_var_label(col), loc='left')\n ax.set_xticks(np.arange(1, bin_length + 1))\n ax.set_xticklabels(self.get_value_labels(col).values(), rotation=45, ha='right')\n plt.xlabel('Level')\n if normalise == True:\n plt.ylabel('% of responses')\n else:\n plt.ylabel('No. of responses')\n\n # Tweak spacing to prevent clipping of ylabel\n # fig.tight_layout()\n plt.show()\n \n # Generate the frequency table\n display(HTML(\"<br/>\"))\n display(HTML(\"Responses, in percentages\"))\n df = pd.DataFrame(np.asarray(n).T, index=labels)\n if legend_labels == None:\n legend_labels = ['Frequencies'] \n s = tabulate.tabulate(df, headers=legend_labels, tablefmt='html')\n display(HTML(s))\n\n display(HTML(\"<br/>\"))\n\n" ]
[ [ "numpy.split", "numpy.asarray", "numpy.arange", "numpy.isnan", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.subplots", "numpy.round", "numpy.size", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "numpy.sum", "matplotlib.pyplot.ylabel" ] ]
rsmith6559/workspace
[ "82a686dfe956fe2434b873af6b44a42108d93b55" ]
[ "testGUI.py" ]
[ "#!/usr/bin/python3\n\nimport tkinter as tk\nfrom tkinter import colorchooser, messagebox\n\nfrom matplotlib.backends.backend_tkagg import(\n FigureCanvasTkAgg, NavigationToolbar2Tk )\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.figure import Figure\n\nimport numpy as np\n\n\ndef newFile():\n print( colorchooser.askcolor( initialcolor=\"#ff0000\" ) )\n \ndef openFile():\n messagebox.showinfo( message=\"Have a sparkling day!\" )\n \ndef closeFile():\n if( messagebox.askyesno( message=\"Are you sure?\", icon=\"question\",\n title=\"Are you kidding me??\" ) ):\n mkMatPlotLibGrid()\n \ndef exitFile(): window.destroy()\n\ndef increase():\n val = int( lbl_value[ \"text\" ] )\n lbl_value[ \"text\" ] = f\"{ val + 1 }\"\n\ndef decrease():\n val = int( lbl_value[ \"text\" ] )\n lbl_value[ \"text\" ] = f\"{ val - 1 }\"\n\ndef mkMatPlotLibGrid():\n frame = tk.Frame( master=window )\n frame.grid( row=2, column=0, columnspan=3, sticky=\"nsew\" )\n\n fig = Figure( figsize=( 5, 4 ), dpi=100 )\n t = np.arange( 0, 3, .01 )\n fig.add_subplot( 111 ).plot( t, 2 * np.sin( 2 * np.pi * t ) )\n\n canvas = FigureCanvasTkAgg( fig, master=frame )\n canvas.draw()\n\n toolbar = NavigationToolbar2Tk( canvas, frame )\n toolbar.update()\n\n canvas.get_tk_widget().pack( fill=tk.BOTH, expand=True )\n\nwindow = tk.Tk()\nwindow.option_add( '*tearOff', False )\nwindow.title( \"Increase / Decrease\" )\nwindow.rowconfigure( [ 0, 2 ], minsize=50, weight=1 )\nwindow.columnconfigure( [ 0, 1, 2 ], minsize=50, weight=1 )\n\nmenubar = tk.Menu( window )\nmenu_file = tk.Menu( menubar )\nmenu_edit = tk.Menu( menubar )\nmenubar.add_cascade( menu=menu_file, label=\"File\" )\nmenubar.add_cascade( menu=menu_edit, label=\"Edit\" )\n\nmenu_file.add_command( label=\"Choose Color\", command=newFile )\nmenu_file.add_separator()\nmenu_file.add_command( label=\"Message\", command=openFile )\nmenu_file.add_separator()\nmenu_file.add_command( label=\"Grid\", command=closeFile )\nmenu_file.add_separator()\nmenu_file.add_command( label=\"Exit\", command=exitFile )\n\nmenu_edit.add_command( label=\"Grid\", command=closeFile )\n\nwindow[ \"menu\" ] = menubar\n\nbtn_decrease = tk.Button( window, text=\" - \", command=decrease )\nbtn_decrease.grid( row=0, column=0, sticky=\"nsew\" )\n\nlbl_value = tk.Label( window, text=\"0\" )\nlbl_value.grid( row=0, column=1 )\n\nbtn_increase = tk.Button( window, text=\" + \", command=increase )\nbtn_increase.grid( row=0, column=2, sticky=\"nsew\" )\n\nphoto = tk.PhotoImage( file=\"./KEYBOARD.gif\" )\nlbl_picture = tk.Label( window, text=\"\" )\nlbl_picture[ \"image\" ] = photo\nlbl_picture.grid( row=1, column=1 )\n\nwindow.mainloop()\n\n" ]
[ [ "matplotlib.figure.Figure", "numpy.arange", "numpy.sin", "matplotlib.backends.backend_tkagg.NavigationToolbar2Tk", "matplotlib.backends.backend_tkagg.FigureCanvasTkAgg" ] ]
st3107/19st_tio2b_notebooks
[ "ff1f87cbfebaef2fe298ea50e4f94de1e96e8ef6" ]
[ "utils.py" ]
[ "import math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pdffitx.modeling as md\nimport pdffitx.parsers as ps\nfrom diffpy.srfit.fitbase import FitResults\nfrom diffpy.srfit.fitbase.parameter import Parameter\nfrom diffpy.srfit.fitbase.fitresults import initializeRecipe\nfrom diffpy.srfit.fitbase.profile import Profile\nimport pdffitx.modeling.running as rn\nfrom pyobjcryst.crystal import Crystal\nfrom diffpy.srfit.fitbase.fithook import FitHook\nimport typing as tp\nimport xarray as xr\nimport scipy.optimize as opt\nimport pdfstream.visualization\nimport pathlib\nimport matplotlib.gridspec as gridspec\n\n\ndef load_data(filename: str, metadata: dict = None) -> Profile:\n profile = Profile()\n parser = md.MyParser()\n parser.parseFile(filename, metadata)\n profile.loadParsedData(parser)\n return profile\n\n\ndef get_symbol(name: str) -> str:\n \"\"\"A conventional rule to rename the parameter name to latex version.\"\"\"\n words = name.split(\"_\")\n if \"scale\" in words:\n return \"scale\"\n if \"delta2\" in words:\n return r\"$\\delta_2$\"\n if \"delta1\" in words:\n return r\"$\\delta_1$\"\n for word in (\"a\", \"b\", \"c\"):\n if word in words:\n return word\n for word in (\"alpha\", \"beta\", \"gamma\"):\n if word in words:\n return rf\"$\\{word}$\"\n for word in (\n 'Uiso', 'U11', 'U12', 'U13', 'U21', 'U22', 'U23', 'U31', 'U32', 'U33',\n 'Biso', 'B11', 'B12', 'B13', 'B21', 'B22', 'B23', 'B31', 'B32', 'B33',\n ):\n if word in words:\n return rf\"{word[0]}$_{{{word[1:]}}}$({words[1]})\"\n for word in (\"x\", \"y\", \"z\"):\n if word in words:\n return rf\"{word}({words[1]})\"\n for word in (\"psize\", \"psig\", \"sthick\", \"thickness\", \"radius\"):\n if word in words:\n return rf\"{word}\"\n return \" \".join(words[1:])\n\n\ndef get_unit(name: str) -> str:\n \"\"\"A conventional rule to get the unit.\"\"\"\n words = name.split(\"_\")\n if \"scale\" in words:\n return \"\"\n if \"delta2\" in words:\n return r\"Å$^2$\"\n if \"delta1\" in words:\n return r\"Å\"\n for word in (\"a\", \"b\", \"c\"):\n if word in words:\n return \"Å\"\n for word in (\"alpha\", \"beta\", \"gamma\"):\n if word in words:\n return \"deg\"\n for word in (\n 'Uiso', 'U11', 'U12', 'U13', 'U21', 'U22', 'U23', 'U31', 'U32', 'U33',\n 'Biso', 'B11', 'B12', 'B13', 'B21', 'B22', 'B23', 'B31', 'B32', 'B33',\n ):\n if word in words:\n return \"Å$^2$\"\n for word in (\"x\", \"y\", \"z\"):\n if word in words:\n return \"Å\"\n for word in (\"psize\", \"psig\", \"sthick\", \"thickness\", \"radius\"):\n if word in words:\n return \"Å\"\n return \"\"\n\n\nclass ModelBase:\n \"\"\"The template for the model class.\"\"\"\n\n def __init__(self, equation: str, structures: tp.Dict[str, Crystal], characteristics: tp.Dict[str, tp.Callable]):\n self._equation = equation\n self._structures = structures\n self._characteristics = characteristics\n self._recipe = self._create_recipe()\n self._fit_result = FitResults(self._recipe, update=False)\n self._verbose: int = 1\n self._order: tp.List[tp.Union[str, tp.Iterable[str]]] = []\n self._options: dict = {}\n\n def parallel(self, ncpu: int):\n fc = self.get_contribution()\n for g in fc.generators.values():\n g.parallel(ncpu)\n\n def set_xrange(self, xmin: float = None, xmax: float = None, xstep: float = None) -> None:\n profile = self.get_profile()\n profile.setCalculationRange(xmin=xmin, xmax=xmax, dx=xstep)\n\n def get_xrange(self) -> tp.List:\n return self._xrange\n\n def set_verbose(self, level: int) -> None:\n self._verbose = level\n\n def get_verbose(self) -> int:\n return self._verbose\n\n def set_options(self, **kwargs) -> None:\n self._options = kwargs\n\n def get_options(self) -> dict:\n return self._options\n\n def set_order(self, *order: tp.Union[str, tp.Iterable[str]]) -> None:\n order = list(order)\n self._check_order(order)\n self._order = order\n\n def _check_order(self, order: tp.Any) -> None:\n tags = set(self._recipe._tagmanager.alltags())\n if isinstance(order, str):\n if not hasattr(self._recipe, order) and order not in tags:\n raise ValueError(\"'{}' is not in the variable names.\".format(order))\n elif isinstance(order, tp.Iterable):\n for x in order:\n self._check_order(x)\n else:\n raise TypeError(\"'{}' is not allowed.\".format(type(order)))\n\n def get_order(self) -> tp.List[tp.Union[str, tp.Iterable[str]]]:\n return self._order\n\n def set_param(self, **kwargs) -> None:\n for name, value in kwargs.items():\n if not hasattr(self._recipe, name):\n raise ValueError(\"There is no parameter called '{}'\".format(name))\n for name, value in kwargs.items():\n var: Parameter = getattr(self._recipe, name)\n var.setValue(value)\n\n def _create_recipe(self) -> md.MyRecipe:\n raise NotImplemented\n\n def get_contribution(self) -> md.MyContribution:\n return next(iter(self._recipe.contributions.values()))\n\n def set_profile(self, profile: Profile) -> None:\n fc: md.MyContribution = self.get_contribution()\n fc.setProfile(profile)\n\n def optimize(self) -> None:\n md.optimize(self._recipe, self._order, validate=False, verbose=self._verbose, **self._options)\n\n def update_result(self) -> None:\n return self._fit_result.update()\n\n def show(self) -> None:\n self._recipe.show()\n\n def get_result(self) -> dict:\n fr = self._fit_result\n dct = dict()\n n = len(fr.varnames)\n for i in range(n):\n dct[fr.varnames[i]] = fr.varvals[i]\n n = len(fr.fixednames)\n for i in range(n):\n dct[fr.fixednames[i]] = fr.fixedvals[i]\n dct[\"rw\"] = self._fit_result.rw\n return dct\n\n def get_profile(self) -> Profile:\n fc = self.get_contribution()\n return fc.profile\n\n def save(self, filepath: str):\n self._fit_result.saveResults(filepath)\n\n def load(self, filepath: str):\n initializeRecipe(self._recipe, filepath)\n\n def export_result(self) -> xr.Dataset:\n dct = self.get_result()\n ds = xr.Dataset(dct)\n for name in ds.variables:\n ds[name].attrs[\"long_name\"] = get_symbol(name)\n ds[name].attrs[\"units\"] = get_unit(name)\n return ds\n\n def export_fits(self) -> xr.Dataset:\n profile = self.get_profile()\n ds = xr.Dataset(\n {\"y\": ([\"x\"], profile.y), \"ycalc\": ([\"x\"], profile.ycalc), \"yobs\": ([\"xobs\"], profile.yobs)},\n {\"x\": ([\"x\"], profile.x), \"xobs\": ([\"xobs\"], profile.xobs)}\n )\n ds[\"y\"].attrs[\"standard_name\"] = \"G\"\n ds[\"y\"].attrs[\"units\"] = r\"Å$^{-2}$\"\n ds[\"ycalc\"].attrs[\"standard_name\"] = \"G\"\n ds[\"ycalc\"].attrs[\"units\"] = r\"Å$^{-2}$\"\n ds[\"yobs\"].attrs[\"standard_name\"] = \"G\"\n ds[\"yobs\"].attrs[\"units\"] = r\"Å$^{-2}$\"\n ds[\"x\"].attrs[\"standard_name\"] = \"r\"\n ds[\"x\"].attrs[\"units\"] = \"Å\"\n ds[\"xobs\"].attrs[\"standard_name\"] = \"r\"\n ds[\"xobs\"].attrs[\"units\"] = \"Å\"\n return ds\n\n def get_structures(self):\n return self._structures\n\n def export_in_files(self, directory: str, file_prefix: str) -> None:\n directory = pathlib.Path(directory)\n result = self.export_result()\n path = directory.joinpath(\"{}_result.nc\".format(file_prefix))\n result.to_netcdf(path)\n fits = self.export_fits()\n path = directory.joinpath(\"{}_fits.nc\".format(file_prefix))\n fits.to_netcdf(path)\n structures = self.get_structures()\n for name, structure in structures.items():\n path = directory.joinpath(\"{}_{}.cif\".format(file_prefix, name))\n with path.open(\"w\") as f:\n structure.CIFOutput(f)\n\n def plot(self) -> None:\n md.view_fits(self._recipe)\n\n\nclass MultiPhaseModel(ModelBase):\n\n def _create_recipe(self) -> md.MyRecipe:\n n = len(self._structures)\n if n != 2:\n raise ValueError(\"The model needs exactly two structures. Currently, it has {}\".format(n))\n pgs = []\n for name, structure in self._structures.items():\n pg = md.PDFGenerator(name)\n pg.setStructure(structure, periodic=True)\n pgs.append(pg)\n fc = md.MyContribution(self.__class__.__name__)\n fc.xname = \"x\"\n for pg in pgs:\n fc.addProfileGenerator(pg)\n for name, sf in self._characteristics.items():\n fc.registerFunction(sf, name)\n fc.setEquation(self._equation)\n fr = md.MyRecipe()\n fr.clearFitHooks()\n fr.addContribution(fc)\n md.initialize(fr)\n return fr\n\n\ndef plot_fits(fits: xr.Dataset, offset: float = 0., ax: plt.Axes = None, **kwargs) -> None:\n if ax is None:\n ax = plt.gca()\n fits[\"yobs\"].plot.line(ax=ax, marker=\"o\", fillstyle=\"none\", ls=\"none\", **kwargs)\n fits[\"ycalc\"].plot.line(ax=ax, _labels=False, **kwargs)\n diff = fits[\"y\"] - fits[\"ycalc\"]\n shift = offset + fits[\"y\"].min() - diff.max()\n diff += shift\n ax.axhline(shift, ls='--', alpha=0.5, color=\"black\")\n diff.plot.line(ax=ax, _labels=False, **kwargs)\n ax.set_title(\"\")\n return\n\n\ndef plot_fits_along_dim(fits: xr.Dataset, dim: str, num_col: int = 4, offset: float = 0., figure_config: dict = None, grid_config: dict = None, plot_config: dict = None) -> tp.List[plt.Axes]:\n if grid_config is None:\n grid_config = {}\n if plot_config is None:\n plot_config = {}\n if figure_config is None:\n figure_config = {}\n fig: plt.Figure = plt.figure(**figure_config)\n n = len(fits[dim])\n num_row = math.ceil(n / num_col)\n grids = gridspec.GridSpec(num_row, num_col, figure=fig, **grid_config)\n axes = []\n for i, grid in zip(fits[dim], grids):\n fit = fits.isel({dim: i})\n ax = fig.add_subplot(grid)\n axes.append(ax)\n plot_fits(fit, offset, ax=ax, **plot_config)\n return axes\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.figure" ] ]
firojalam/transformers
[ "58282c10f887a90932cbc0fd0dec0c556b98c19d" ]
[ "examples/transformers/data/metrics/__init__.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, 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\nimport csv\nimport sys\nimport logging\nimport numpy as np\nimport re\nimport pandas as pd\nlogger = logging.getLogger(__name__)\n\ntry:\n from scipy.stats import pearsonr, spearmanr\n #from sklearn.metrics import matthews_corrcoef, f1_score\n from sklearn.metrics import matthews_corrcoef, f1_score, precision_recall_fscore_support, classification_report, \\\n confusion_matrix, roc_auc_score\n _has_sklearn = True\nexcept (AttributeError, ImportError) as e:\n logger.warning(\"To use data.metrics please install scikit-learn. See https://scikit-learn.org/stable/index.html\")\n _has_sklearn = False\n\ndef is_sklearn_available():\n return _has_sklearn\n\nif _has_sklearn:\n\n def simple_accuracy(preds, labels):\n return (preds == labels).mean()\n\n\n def acc_and_f1(preds, labels):\n acc = simple_accuracy(preds, labels)\n f1 = f1_score(y_true=labels, y_pred=preds)\n return {\n \"acc\": acc,\n \"f1\": f1,\n \"acc_and_f1\": (acc + f1) / 2,\n }\n\n\n def pearson_and_spearman(preds, labels):\n pearson_corr = pearsonr(preds, labels)[0]\n spearman_corr = spearmanr(preds, labels)[0]\n return {\n \"pearson\": pearson_corr,\n \"spearmanr\": spearman_corr,\n \"corr\": (pearson_corr + spearman_corr) / 2,\n }\n\n def format_conf_mat(y_true,y_pred):\n\n conf_mat = pd.crosstab(np.array(y_true), np.array(y_pred), rownames=['gold'], colnames=['pred'], margins=True)\n pred_columns = conf_mat.columns.tolist()\n gold_rows = conf_mat.index.tolist()\n conf_mat_str = \"\"\n header = \"Pred\\nGold\"\n for h in pred_columns:\n header = header + \"\\t\" + str(h)\n conf_mat_str = header + \"\\n\"\n index = 0\n for r_index, row in conf_mat.iterrows():\n row_str = str(gold_rows[index]) # for class label (name)\n index += 1\n for col_item in row:\n row_str = row_str + \"\\t\" + str(col_item)\n conf_mat_str = conf_mat_str + row_str + \"\\n\"\n return conf_mat_str\n\n\n def format_classifaction_report(report):\n report_data = \"class_label\\tP\\tR\\tF1\\tsupport\\n\"\n for k,row in report.items():\n if(k==\"accuracy\"):\n continue\n report_data = report_data+str(k)+\"\\t\"+str(row['precision'])+\"\\t\"+str(row['recall'])+\"\\t\"+str(row['f1-score'])+\"\\t\"+str(row['support'])+\"\\n\"\n return report_data\n\n\n def roc_auc_score_multiclass(actual_class, pred_class, average=\"weighted\"):\n\n # creating a set of all the unique classes using the actual class list\n unique_class = set(actual_class)\n roc_auc_dict = {}\n for per_class in unique_class:\n # creating a list of all the classes except the current class\n other_class = [x for x in unique_class if x != per_class]\n\n # marking the current class as 1 and all other classes as 0\n new_actual_class = [0 if x in other_class else 1 for x in actual_class]\n new_pred_class = [0 if x in other_class else 1 for x in pred_class]\n\n # using the sklearn metrics method to calculate the roc_auc_score\n roc_auc = roc_auc_score(new_actual_class, new_pred_class, average=average)\n roc_auc_dict[per_class] = roc_auc\n\n list_values = [v for v in roc_auc_dict.values()]\n average = np.average(list_values)\n return average\n\n def acc_and_p_r_f_per_class(preds, labels, label_list):\n acc = simple_accuracy(preds, labels)\n prf = precision_recall_fscore_support(y_true=labels, y_pred=preds, average='weighted')\n # prf_per_class = precision_recall_fscore_support(y_true=labels, y_pred=preds, average=None, labels=label_list)\n #print(label_list)\n # logger.info(list(set(labels)))\n # logger.info(len(labels))\n # logger.info(list(set(preds)))\n # logger.info(len(preds))\n logger.info(label_list)\n label_map = [i for i, label in enumerate(label_list)]\n logger.info(label_map)\n prf_per_class = classification_report(y_true=labels, y_pred=preds, digits=4, labels=label_map,output_dict=True)\n prf_per_class = format_classifaction_report(prf_per_class)\n # to calculate per class accuracy\n cm = confusion_matrix(y_true=labels, y_pred=preds)\n #cm_str = np.array2string(cm, separator='\\t')\n cm_str = format_conf_mat(labels, preds)\n per_class_acc=cm.diagonal() / cm.sum(axis=1)\n #per_class_acc = per_class_acc.tolist()\n per_class_acc_str =\"\"\n for item in per_class_acc.tolist():\n per_class_acc_str=per_class_acc_str+str(item)+\"\\t\"\n\n AUC = roc_auc_score_multiclass(labels, preds)\n\n return {\n \"acc\": acc,\n \"prec\": prf[0],\n \"rec\": prf[1],\n \"f1\": prf[2],\n \"AUC\": AUC,\n \"perclass\": prf_per_class,\n \"confusion_matrix\": cm_str,\n \"perclassAcc\": per_class_acc_str.strip(),\n }\n\n\n def glue_compute_metrics(task_name, preds, labels,label_list):\n assert len(preds) == len(labels)\n if task_name == \"cola\":\n return {\"mcc\": matthews_corrcoef(labels, preds)}\n elif task_name == \"sst-2\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif (task_name == \"multitask\" or task_name == \"multiclass\"):\n #return {\"acc-multitask: \": simple_accuracy(preds, labels)}\n return {\"results\": acc_and_p_r_f_per_class(preds, labels, label_list)}\n elif task_name == \"mrpc\":\n return acc_and_f1(preds, labels)\n elif task_name == \"sts-b\":\n return pearson_and_spearman(preds, labels)\n elif task_name == \"qqp\":\n return acc_and_f1(preds, labels)\n elif task_name == \"mnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"mnli-mm\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"qnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"rte\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"wnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n else:\n raise KeyError(task_name)\n" ]
[ [ "numpy.array", "sklearn.metrics.roc_auc_score", "scipy.stats.pearsonr", "sklearn.metrics.matthews_corrcoef", "sklearn.metrics.confusion_matrix", "sklearn.metrics.precision_recall_fscore_support", "scipy.stats.spearmanr", "sklearn.metrics.f1_score", "numpy.average", "sklearn.metrics.classification_report" ] ]
Rachananagavelli/IR-detction
[ "e8c746edad6aa8c5dfc8c46c4aa6d36e6f17368b" ]
[ "localization.py" ]
[ "import numpy as np\nimport cv2 as cv\nimport glob\nimport matplotlib.pyplot as plt\nimport sys\nfrom PIL import Image\nimport argparse\nimport os\n\n# convenience code to annotate calibration points by clicking\n# python localization.py dataset/beach/map.png dataset/beach/calib_map.txt --click\nif '--click' in sys.argv:\n input_fname = sys.argv[1]\n output_fname = sys.argv[2]\n img = cv.imread(input_fname)\n img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n fig = plt.figure()\n\n clicked_points = []\n def update():\n plt.clf()\n plt.imshow(img, cmap='gray')\n plt.plot([p[0] for p in clicked_points], [p[1] for p in clicked_points], 'rx')\n fig.canvas.draw()\n\n def onclick(event):\n x,y = int(np.round(event.xdata)), int(np.round(event.ydata))\n print('clicked',x,y)\n clicked_points.append([x, y])\n update()\n\n def onkey(event):\n if event.key==' ':\n np.savetxt(output_fname, clicked_points)\n sys.exit(1)\n\n fig.canvas.mpl_connect('button_press_event', onclick)\n fig.canvas.mpl_connect('key_press_event', onkey)\n update()\n plt.show()\n sys.exit(1)\n\n# code to project 2D detections on to an overhead map\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--datasets\", type=str, default=\"beach\", required=True, help=\"Dataset directory name\")\nparser.add_argument( '--map', type=str, required=True, help='satellite image')\nparser.add_argument(\"--gridSize\", type=int, default=10, help=\"size of each square in the calibration grid\")\nparser.add_argument(\"--stepSize\", type=int, default=1, help=\"density of drawing calibration grid\")\nflags = parser.parse_args()\n\n# visualize calibration points in overhead map\nplt.figure()\nmap_ax = plt.gca()\n# oriented bounding box of calibration area in overhead map\ncalib_map = flags.map.replace('.png', '.txt')\ncalib_map = np.loadtxt(calib_map)\nmap_origin = calib_map[0]\nmap_x_vector = calib_map[1] - calib_map[0]\nmap_y_vector = calib_map[2] - calib_map[0]\nmaxX = 330\nmaxY = 130\nx = 0\nwhile x <= maxX:\n p1 = map_origin + 1.0 * x / maxX * map_x_vector\n p2 = map_origin + map_y_vector + 1.0 * x / maxX * map_x_vector\n plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'k', linewidth=1, alpha=0.5)\n x += flags.gridSize\ny = 0\nwhile y <= maxY:\n p1 = map_origin + 1.0 * y / maxY * map_y_vector\n p2 = map_origin + map_x_vector + 1.0 * y / maxY * map_y_vector\n plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'k', linewidth=1, alpha=0.5)\n y += flags.gridSize\n# image of overhead map / satellite image\nmap_fname = flags.map\nmap_np = np.array(Image.open(map_fname))\nplt.imshow(map_np)\nplt.annotate('(%d,%d)'%(0,0), xy=(calib_map[0,0], calib_map[0,1]), xytext=(20, 20), textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\nplt.annotate('(%d,%d)'%(maxX,0), xy=(calib_map[1,0], calib_map[1,1]), xytext=(20, 20), textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\nplt.annotate('(%d,%d)'%(0,maxY), xy=(calib_map[2,0], calib_map[2,1]), xytext=(20, 20), textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\nplt.annotate('(%d,%d)'%(maxX,maxY), xy=(calib_map[3,0], calib_map[3,1]), xytext=(20, 20), textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\nplt.annotate('CCTV #2, #3, #4\\nLAT=38.1899232\\nLON=128.6040349', xy=(258, 424), xytext=(-30, -30), textcoords='offset points', ha='right', va='top',\n bbox=dict(boxstyle='round,pad=0.5', fc='red', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\nplt.annotate('CCTV #1, #5, #6\\nLAT=38.1893355\\nLON=128.6047293', xy=(367, 583), xytext=(-30, -30), textcoords='offset points', ha='right', va='top',\n bbox=dict(boxstyle='round,pad=0.5', fc='red', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\n\nfor dataset in flags.datasets.split(','):\n\n print('Loading from', dataset)\n # calibration points in world coordinates (assume Z coordinate of 0)\n calib_3d = dataset + '/calib_3d.txt'\n # corresponding calibration point coordinates in the input image\n calib_2d = dataset + '/calib_2d.txt'\n calib_3d = np.loadtxt(calib_3d)\n calib_3d = np.hstack((calib_3d, np.zeros((len(calib_3d), 1)))).astype(np.float32)\n calib_2d = np.loadtxt(calib_2d).astype(np.float32)\n calib_2d = calib_2d.reshape(-1,1,2)\n\n img_idx = 1\n while True:\n # input image\n img_fname = dataset + '/%d.png' % img_idx\n # input semantic segmentation mask\n label_fname = dataset + '/prediction%d.png' % img_idx\n if os.path.exists(label_fname):\n break\n img_idx += 1\n image_np = np.array(Image.open(img_fname))\n gray = np.mean(image_np, axis=2)\n mask = np.array(Image.open(label_fname))\n print('Input', image_np.shape, image_np.dtype, mask.shape, mask.dtype)\n image_np[:,:,0] = gray\n image_np[:,:,1] = gray\n image_np[:,:,2] = gray\n image_np[mask] = 0.5 * image_np[mask] + [0, 128, 0]\n\n # solve for camera parameters\n _, mtx, _, rvecs, tvecs = cv.calibrateCamera([calib_3d], [calib_2d], gray.shape[::-1], None, None, flags=cv.CALIB_ZERO_TANGENT_DIST+cv.CALIB_FIX_K1+cv.CALIB_FIX_K2+cv.CALIB_FIX_K3)\n fx = mtx[0,0]\n fy = mtx[1,1]\n cx = mtx[0,2]\n cy = mtx[1,2]\n R, _ = cv.Rodrigues(rvecs[0])\n T = tvecs[0]\n print('Camera parameters:')\n print(fx,fy,cx,cy)\n print(rvecs, R)\n print(tvecs)\n calib_2d_reprojected, _ = cv.projectPoints(calib_3d, rvecs[0], tvecs[0], mtx, np.zeros(5,dtype=np.float32))\n\n # get detection centroids from semantic segmentation mask\n min_cluster = 10\n max_cluster = 1000\n dt_2D = []\n ret, dt_com = cv.connectedComponents(mask.astype(np.uint8))\n for i in range(1, dt_com.max()+1):\n if np.sum(dt_com==i) > min_cluster and np.sum(dt_com==i) < max_cluster:\n my, mx = np.nonzero(dt_com==i)\n dt_2D.append([np.mean(mx), np.mean(my)])\n\n # project detection centroids to world coordinates at Z=0\n dt_3D = np.zeros((len(dt_2D), 3), dtype=np.float32)\n for i in range(len(dt_2D)):\n u,v = dt_2D[i]\n u = (u - cx) / fx\n v = (v - cy) / fy\n N = R.dot([0,0,1])\n z = N.dot(T) / (N[0]*u + N[1]*v + N[2])\n xyz = np.array([z*u, z*v, z])\n dt_3D[i,:] = R.T.dot(xyz - T).flatten()\n\n # visualize calibration points and detection centroids in input image\n plt.figure()\n plt.plot(calib_2d[:,:,0], calib_2d[:,:,1], 'ro')\n plt.plot(calib_2d_reprojected[:,:,0], calib_2d_reprojected[:,:,1], 'bx')\n plt.imshow(image_np)\n for i in range(len(calib_3d)):\n plt.annotate('(%d,%d)'%(calib_3d[i,0],calib_3d[i,1]), xy=(calib_2d[i,0,0], calib_2d[i,0,1]), xytext=(20, 20), textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\n x1 = int(np.floor(1.0 * calib_3d[:,0].min() / flags.gridSize)) * flags.gridSize\n x2 = int(np.ceil(1.0 * calib_3d[:,0].max() / flags.gridSize)) * flags.gridSize\n y1 = int(np.floor(1.0 * calib_3d[:,1].min() / flags.gridSize)) * flags.gridSize\n y2 = int(np.ceil(1.0 * calib_3d[:,1].max() / flags.gridSize)) * flags.gridSize\n # draw grid lines\n x = x1\n while x <= x2:\n pts = np.array([[x,y,0] for y in range(y1, y2+flags.stepSize, flags.stepSize)], dtype=np.float32)\n projected, _ = cv.projectPoints(pts, rvecs[0], tvecs[0], mtx, np.zeros(5,dtype=np.float32))\n plt.plot(projected[:,:,0], projected[:,:,1], 'k')\n x += flags.gridSize\n y = y1\n while y <= y2:\n pts = np.array([[x,y,0] for x in range(x1, x2+flags.stepSize, flags.stepSize)], dtype=np.float32)\n projected, _ = cv.projectPoints(pts, rvecs[0], tvecs[0], mtx, np.zeros(5,dtype=np.float32))\n plt.plot(projected[:,:,0], projected[:,:,1], 'k')\n y += flags.gridSize\n\n # add detection centroids to overhead map\n dt_map = np.zeros((len(dt_3D), 2))\n for i in range(len(dt_3D)):\n dt_map[i] = map_origin + dt_3D[i,0] / maxX * map_x_vector + dt_3D[i,1] / maxY * map_y_vector\n map_ax.plot(dt_map[:,0], dt_map[:,1], 'x', linewidth=3, label='CCTV'+dataset.split('_')[-1])\n\nmap_ax.legend()\nplt.show()\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.pyplot.imshow", "numpy.nonzero", "matplotlib.pyplot.plot", "numpy.round", "matplotlib.pyplot.clf", "numpy.mean", "numpy.savetxt", "numpy.array", "matplotlib.pyplot.show", "numpy.zeros", "numpy.sum", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
agamemnonc/pyqtgraph
[ "ed6586c7ddd3ad95eadd40cb8fda7c4c1d4c746b" ]
[ "pyqtgraph/graphicsItems/AxisItem.py" ]
[ "from ..Qt import QtGui, QtCore\nfrom ..python2_3 import asUnicode\nimport numpy as np\nfrom ..Point import Point\nfrom .. import debug as debug\nimport weakref\nfrom .. import functions as fn\nfrom .. import getConfigOption\nfrom .GraphicsWidget import GraphicsWidget\n\n__all__ = ['AxisItem']\nclass AxisItem(GraphicsWidget):\n \"\"\"\n GraphicsItem showing a single plot axis with ticks, values, and label.\n Can be configured to fit on any side of a plot, and can automatically synchronize its displayed scale with ViewBox items.\n Ticks can be extended to draw a grid.\n If maxTickLength is negative, ticks point into the plot.\n \"\"\"\n\n def __init__(self, orientation, pen=None, linkView=None, parent=None, maxTickLength=-5, showValues=True, text='', units='', unitPrefix='', **args):\n \"\"\"\n ============== ===============================================================\n **Arguments:**\n orientation one of 'left', 'right', 'top', or 'bottom'\n maxTickLength (px) maximum length of ticks to draw. Negative values draw\n into the plot, positive values draw outward.\n linkView (ViewBox) causes the range of values displayed in the axis\n to be linked to the visible range of a ViewBox.\n showValues (bool) Whether to display values adjacent to ticks\n pen (QPen) Pen used when drawing ticks.\n text The text (excluding units) to display on the label for this\n axis.\n units The units for this axis. Units should generally be given\n without any scaling prefix (eg, 'V' instead of 'mV'). The\n scaling prefix will be automatically prepended based on the\n range of data displayed.\n **args All extra keyword arguments become CSS style options for\n the <span> tag which will surround the axis label and units.\n ============== ===============================================================\n \"\"\"\n\n GraphicsWidget.__init__(self, parent)\n self.label = QtGui.QGraphicsTextItem(self)\n self.picture = None\n self.orientation = orientation\n if orientation not in ['left', 'right', 'top', 'bottom']:\n raise Exception(\"Orientation argument must be one of 'left', 'right', 'top', or 'bottom'.\")\n if orientation in ['left', 'right']:\n self.label.rotate(-90)\n\n self.style = {\n 'tickTextOffset': [5, 2], ## (horizontal, vertical) spacing between text and axis\n 'tickTextWidth': 30, ## space reserved for tick text\n 'tickTextHeight': 18,\n 'autoExpandTextSpace': True, ## automatically expand text space if needed\n 'tickFont': None,\n 'stopAxisAtTick': (False, False), ## whether axis is drawn to edge of box or to last tick\n 'textFillLimits': [ ## how much of the axis to fill up with tick text, maximally.\n (0, 0.8), ## never fill more than 80% of the axis\n (2, 0.6), ## If we already have 2 ticks with text, fill no more than 60% of the axis\n (4, 0.4), ## If we already have 4 ticks with text, fill no more than 40% of the axis\n (6, 0.2), ## If we already have 6 ticks with text, fill no more than 20% of the axis\n ],\n 'showValues': showValues,\n 'tickLength': maxTickLength,\n 'maxTickLevel': 2,\n 'maxTextLevel': 2,\n }\n\n self.textWidth = 30 ## Keeps track of maximum width / height of tick text\n self.textHeight = 18\n\n # If the user specifies a width / height, remember that setting\n # indefinitely.\n self.fixedWidth = None\n self.fixedHeight = None\n\n self.labelText = text\n self.labelUnits = units\n self.labelUnitPrefix = unitPrefix\n self.labelStyle = args\n self.logMode = False\n self.tickFont = None\n\n self._tickLevels = None ## used to override the automatic ticking system with explicit ticks\n self._tickSpacing = None # used to override default tickSpacing method\n self.scale = 1.0\n self.autoSIPrefix = True\n self.autoSIPrefixScale = 1.0\n\n self.showLabel(False)\n\n self.setRange(0, 1)\n\n if pen is None:\n self.setPen()\n else:\n self.setPen(pen)\n\n self._linkedView = None\n if linkView is not None:\n self.linkToView(linkView)\n\n self.grid = False\n #self.setCacheMode(self.DeviceCoordinateCache)\n\n def setStyle(self, **kwds):\n \"\"\"\n Set various style options.\n\n =================== =======================================================\n Keyword Arguments:\n tickLength (int) The maximum length of ticks in pixels.\n Positive values point toward the text; negative\n values point away.\n tickTextOffset (int) reserved spacing between text and axis in px\n tickTextWidth (int) Horizontal space reserved for tick text in px\n tickTextHeight (int) Vertical space reserved for tick text in px\n autoExpandTextSpace (bool) Automatically expand text space if the tick\n strings become too long.\n tickFont (QFont or None) Determines the font used for tick\n values. Use None for the default font.\n stopAxisAtTick (tuple: (bool min, bool max)) If True, the axis\n line is drawn only as far as the last tick.\n Otherwise, the line is drawn to the edge of the\n AxisItem boundary.\n textFillLimits (list of (tick #, % fill) tuples). This structure\n determines how the AxisItem decides how many ticks\n should have text appear next to them. Each tuple in\n the list specifies what fraction of the axis length\n may be occupied by text, given the number of ticks\n that already have text displayed. For example::\n\n [(0, 0.8), # Never fill more than 80% of the axis\n (2, 0.6), # If we already have 2 ticks with text,\n # fill no more than 60% of the axis\n (4, 0.4), # If we already have 4 ticks with text,\n # fill no more than 40% of the axis\n (6, 0.2)] # If we already have 6 ticks with text,\n # fill no more than 20% of the axis\n\n showValues (bool) indicates whether text is displayed adjacent\n to ticks.\n =================== =======================================================\n\n Added in version 0.9.9\n \"\"\"\n for kwd,value in kwds.items():\n if kwd not in self.style:\n raise NameError(\"%s is not a valid style argument.\" % kwd)\n\n if kwd in ('tickLength', 'tickTextOffset', 'tickTextWidth', 'tickTextHeight'):\n if not isinstance(value, int):\n raise ValueError(\"Argument '%s' must be int\" % kwd)\n\n if kwd == 'tickTextOffset':\n if self.orientation in ('left', 'right'):\n self.style['tickTextOffset'][0] = value\n else:\n self.style['tickTextOffset'][1] = value\n elif kwd == 'stopAxisAtTick':\n try:\n assert len(value) == 2 and isinstance(value[0], bool) and isinstance(value[1], bool)\n except:\n raise ValueError(\"Argument 'stopAxisAtTick' must have type (bool, bool)\")\n self.style[kwd] = value\n else:\n self.style[kwd] = value\n\n self.picture = None\n self._adjustSize()\n self.update()\n\n def close(self):\n self.scene().removeItem(self.label)\n self.label = None\n self.scene().removeItem(self)\n\n def setGrid(self, grid):\n \"\"\"Set the alpha value (0-255) for the grid, or False to disable.\n\n When grid lines are enabled, the axis tick lines are extended to cover\n the extent of the linked ViewBox, if any.\n \"\"\"\n self.grid = grid\n self.picture = None\n self.prepareGeometryChange()\n self.update()\n\n def setLogMode(self, log):\n \"\"\"\n If *log* is True, then ticks are displayed on a logarithmic scale and values\n are adjusted accordingly. (This is usually accessed by changing the log mode\n of a :func:`PlotItem <pyqtgraph.PlotItem.setLogMode>`)\n \"\"\"\n self.logMode = log\n self.picture = None\n self.update()\n\n def setTickFont(self, font):\n self.tickFont = font\n self.picture = None\n self.prepareGeometryChange()\n ## Need to re-allocate space depending on font size?\n\n self.update()\n\n def resizeEvent(self, ev=None):\n #s = self.size()\n\n ## Set the position of the label\n nudge = 5\n br = self.label.boundingRect()\n p = QtCore.QPointF(0, 0)\n if self.orientation == 'left':\n p.setY(int(self.size().height()/2 + br.width()/2))\n p.setX(-nudge)\n elif self.orientation == 'right':\n p.setY(int(self.size().height()/2 + br.width()/2))\n p.setX(int(self.size().width()-br.height()+nudge))\n elif self.orientation == 'top':\n p.setY(-nudge)\n p.setX(int(self.size().width()/2. - br.width()/2.))\n elif self.orientation == 'bottom':\n p.setX(int(self.size().width()/2. - br.width()/2.))\n p.setY(int(self.size().height()-br.height()+nudge))\n self.label.setPos(p)\n self.picture = None\n\n def showLabel(self, show=True):\n \"\"\"Show/hide the label text for this axis.\"\"\"\n #self.drawLabel = show\n self.label.setVisible(show)\n if self.orientation in ['left', 'right']:\n self._updateWidth()\n else:\n self._updateHeight()\n if self.autoSIPrefix:\n self.updateAutoSIPrefix()\n\n def setLabel(self, text=None, units=None, unitPrefix=None, **args):\n \"\"\"Set the text displayed adjacent to the axis.\n\n ============== =============================================================\n **Arguments:**\n text The text (excluding units) to display on the label for this\n axis.\n units The units for this axis. Units should generally be given\n without any scaling prefix (eg, 'V' instead of 'mV'). The\n scaling prefix will be automatically prepended based on the\n range of data displayed.\n **args All extra keyword arguments become CSS style options for\n the <span> tag which will surround the axis label and units.\n ============== =============================================================\n\n The final text generated for the label will look like::\n\n <span style=\"...options...\">{text} (prefix{units})</span>\n\n Each extra keyword argument will become a CSS option in the above template.\n For example, you can set the font size and color of the label::\n\n labelStyle = {'color': '#FFF', 'font-size': '14pt'}\n axis.setLabel('label text', units='V', **labelStyle)\n\n \"\"\"\n show_label = False\n if text is not None:\n self.labelText = text\n show_label = True\n if units is not None:\n self.labelUnits = units\n show_label = True\n if show_label:\n self.showLabel()\n if unitPrefix is not None:\n self.labelUnitPrefix = unitPrefix\n if len(args) > 0:\n self.labelStyle = args\n self.label.setHtml(self.labelString())\n self._adjustSize()\n self.picture = None\n self.update()\n\n def labelString(self):\n if self.labelUnits == '':\n if not self.autoSIPrefix or self.autoSIPrefixScale == 1.0:\n units = ''\n else:\n units = asUnicode('(x%g)') % (1.0/self.autoSIPrefixScale)\n else:\n #print repr(self.labelUnitPrefix), repr(self.labelUnits)\n units = asUnicode('(%s%s)') % (asUnicode(self.labelUnitPrefix), asUnicode(self.labelUnits))\n\n s = asUnicode('%s %s') % (asUnicode(self.labelText), asUnicode(units))\n\n style = ';'.join(['%s: %s' % (k, self.labelStyle[k]) for k in self.labelStyle])\n\n return asUnicode(\"<span style='%s'>%s</span>\") % (style, asUnicode(s))\n\n def _updateMaxTextSize(self, x):\n ## Informs that the maximum tick size orthogonal to the axis has\n ## changed; we use this to decide whether the item needs to be resized\n ## to accomodate.\n if self.orientation in ['left', 'right']:\n mx = max(self.textWidth, x)\n if mx > self.textWidth or mx < self.textWidth-10:\n self.textWidth = mx\n if self.style['autoExpandTextSpace'] is True:\n self._updateWidth()\n #return True ## size has changed\n else:\n mx = max(self.textHeight, x)\n if mx > self.textHeight or mx < self.textHeight-10:\n self.textHeight = mx\n if self.style['autoExpandTextSpace'] is True:\n self._updateHeight()\n #return True ## size has changed\n\n def _adjustSize(self):\n if self.orientation in ['left', 'right']:\n self._updateWidth()\n else:\n self._updateHeight()\n\n def setHeight(self, h=None):\n \"\"\"Set the height of this axis reserved for ticks and tick labels.\n The height of the axis label is automatically added.\n\n If *height* is None, then the value will be determined automatically\n based on the size of the tick text.\"\"\"\n self.fixedHeight = h\n self._updateHeight()\n\n def _updateHeight(self):\n if not self.isVisible():\n h = 0\n else:\n if self.fixedHeight is None:\n if not self.style['showValues']:\n h = 0\n elif self.style['autoExpandTextSpace'] is True:\n h = self.textHeight\n else:\n h = self.style['tickTextHeight']\n h += self.style['tickTextOffset'][1] if self.style['showValues'] else 0\n h += max(0, self.style['tickLength'])\n if self.label.isVisible():\n h += self.label.boundingRect().height() * 0.8\n else:\n h = self.fixedHeight\n\n self.setMaximumHeight(h)\n self.setMinimumHeight(h)\n self.picture = None\n\n def setWidth(self, w=None):\n \"\"\"Set the width of this axis reserved for ticks and tick labels.\n The width of the axis label is automatically added.\n\n If *width* is None, then the value will be determined automatically\n based on the size of the tick text.\"\"\"\n self.fixedWidth = w\n self._updateWidth()\n\n def _updateWidth(self):\n if not self.isVisible():\n w = 0\n else:\n if self.fixedWidth is None:\n if not self.style['showValues']:\n w = 0\n elif self.style['autoExpandTextSpace'] is True:\n w = self.textWidth\n else:\n w = self.style['tickTextWidth']\n w += self.style['tickTextOffset'][0] if self.style['showValues'] else 0\n w += max(0, self.style['tickLength'])\n if self.label.isVisible():\n w += self.label.boundingRect().height() * 0.8 ## bounding rect is usually an overestimate\n else:\n w = self.fixedWidth\n\n self.setMaximumWidth(w)\n self.setMinimumWidth(w)\n self.picture = None\n\n def pen(self):\n if self._pen is None:\n return fn.mkPen(getConfigOption('foreground'))\n return fn.mkPen(self._pen)\n\n def setPen(self, *args, **kwargs):\n \"\"\"\n Set the pen used for drawing text, axes, ticks, and grid lines.\n If no arguments are given, the default foreground color will be used\n (see :func:`setConfigOption <pyqtgraph.setConfigOption>`).\n \"\"\"\n self.picture = None\n if args or kwargs:\n self._pen = fn.mkPen(*args, **kwargs)\n else:\n self._pen = fn.mkPen(getConfigOption('foreground'))\n self.labelStyle['color'] = '#' + fn.colorStr(self._pen.color())[:6]\n self.setLabel()\n self.update()\n\n def setScale(self, scale=None):\n \"\"\"\n Set the value scaling for this axis.\n\n Setting this value causes the axis to draw ticks and tick labels as if\n the view coordinate system were scaled. By default, the axis scaling is\n 1.0.\n \"\"\"\n # Deprecated usage, kept for backward compatibility\n if scale is None:\n scale = 1.0\n self.enableAutoSIPrefix(True)\n\n if scale != self.scale:\n self.scale = scale\n self.setLabel()\n self.picture = None\n self.update()\n\n def enableAutoSIPrefix(self, enable=True):\n \"\"\"\n Enable (or disable) automatic SI prefix scaling on this axis.\n\n When enabled, this feature automatically determines the best SI prefix\n to prepend to the label units, while ensuring that axis values are scaled\n accordingly.\n\n For example, if the axis spans values from -0.1 to 0.1 and has units set\n to 'V' then the axis would display values -100 to 100\n and the units would appear as 'mV'\n\n This feature is enabled by default, and is only available when a suffix\n (unit string) is provided to display on the label.\n \"\"\"\n self.autoSIPrefix = enable\n self.updateAutoSIPrefix()\n\n def updateAutoSIPrefix(self):\n if self.label.isVisible():\n if self.logMode:\n _range = 10**np.array(self.range)\n else:\n _range = self.range\n (scale, prefix) = fn.siScale(max(abs(_range[0]*self.scale), abs(_range[1]*self.scale)))\n if self.labelUnits == '' and prefix in ['k', 'm']: ## If we are not showing units, wait until 1e6 before scaling.\n scale = 1.0\n prefix = ''\n self.autoSIPrefixScale = scale\n self.setLabel(unitPrefix=prefix)\n else:\n self.autoSIPrefixScale = 1.0\n\n self.picture = None\n self.update()\n\n\n def setRange(self, mn, mx):\n \"\"\"Set the range of values displayed by the axis.\n Usually this is handled automatically by linking the axis to a ViewBox with :func:`linkToView <pyqtgraph.AxisItem.linkToView>`\"\"\"\n if any(np.isinf((mn, mx))) or any(np.isnan((mn, mx))):\n raise Exception(\"Not setting range to [%s, %s]\" % (str(mn), str(mx)))\n self.range = [mn, mx]\n if self.autoSIPrefix:\n self.updateAutoSIPrefix()\n self.picture = None\n self.update()\n\n def linkedView(self):\n \"\"\"Return the ViewBox this axis is linked to\"\"\"\n if self._linkedView is None:\n return None\n else:\n return self._linkedView()\n\n def linkToView(self, view):\n \"\"\"Link this axis to a ViewBox, causing its displayed range to match the visible range of the view.\"\"\"\n oldView = self.linkedView()\n self._linkedView = weakref.ref(view)\n if self.orientation in ['right', 'left']:\n if oldView is not None:\n oldView.sigYRangeChanged.disconnect(self.linkedViewChanged)\n view.sigYRangeChanged.connect(self.linkedViewChanged)\n else:\n if oldView is not None:\n oldView.sigXRangeChanged.disconnect(self.linkedViewChanged)\n view.sigXRangeChanged.connect(self.linkedViewChanged)\n\n if oldView is not None:\n oldView.sigResized.disconnect(self.linkedViewChanged)\n view.sigResized.connect(self.linkedViewChanged)\n\n def linkedViewChanged(self, view, newRange=None):\n if self.orientation in ['right', 'left']:\n if newRange is None:\n newRange = view.viewRange()[1]\n if view.yInverted():\n self.setRange(*newRange[::-1])\n else:\n self.setRange(*newRange)\n else:\n if newRange is None:\n newRange = view.viewRange()[0]\n if view.xInverted():\n self.setRange(*newRange[::-1])\n else:\n self.setRange(*newRange)\n\n def boundingRect(self):\n linkedView = self.linkedView()\n if linkedView is None or self.grid is False:\n rect = self.mapRectFromParent(self.geometry())\n ## extend rect if ticks go in negative direction\n ## also extend to account for text that flows past the edges\n tl = self.style['tickLength']\n if self.orientation == 'left':\n rect = rect.adjusted(0, -15, -min(0,tl), 15)\n elif self.orientation == 'right':\n rect = rect.adjusted(min(0,tl), -15, 0, 15)\n elif self.orientation == 'top':\n rect = rect.adjusted(-15, 0, 15, -min(0,tl))\n elif self.orientation == 'bottom':\n rect = rect.adjusted(-15, min(0,tl), 15, 0)\n return rect\n else:\n return self.mapRectFromParent(self.geometry()) | linkedView.mapRectToItem(self, linkedView.boundingRect())\n\n def paint(self, p, opt, widget):\n profiler = debug.Profiler()\n if self.picture is None:\n try:\n picture = QtGui.QPicture()\n painter = QtGui.QPainter(picture)\n specs = self.generateDrawSpecs(painter)\n profiler('generate specs')\n if specs is not None:\n self.drawPicture(painter, *specs)\n profiler('draw picture')\n finally:\n painter.end()\n self.picture = picture\n #p.setRenderHint(p.Antialiasing, False) ## Sometimes we get a segfault here ???\n #p.setRenderHint(p.TextAntialiasing, True)\n self.picture.play(p)\n\n def setTicks(self, ticks):\n \"\"\"Explicitly determine which ticks to display.\n This overrides the behavior specified by tickSpacing(), tickValues(), and tickStrings()\n The format for *ticks* looks like::\n\n [\n [ (majorTickValue1, majorTickString1), (majorTickValue2, majorTickString2), ... ],\n [ (minorTickValue1, minorTickString1), (minorTickValue2, minorTickString2), ... ],\n ...\n ]\n\n If *ticks* is None, then the default tick system will be used instead.\n \"\"\"\n self._tickLevels = ticks\n self.picture = None\n self.update()\n\n def setTickSpacing(self, major=None, minor=None, levels=None):\n \"\"\"\n Explicitly determine the spacing of major and minor ticks. This\n overrides the default behavior of the tickSpacing method, and disables\n the effect of setTicks(). Arguments may be either *major* and *minor*,\n or *levels* which is a list of (spacing, offset) tuples for each\n tick level desired.\n\n If no arguments are given, then the default behavior of tickSpacing\n is enabled.\n\n Examples::\n\n # two levels, all offsets = 0\n axis.setTickSpacing(5, 1)\n # three levels, all offsets = 0\n axis.setTickSpacing([(3, 0), (1, 0), (0.25, 0)])\n # reset to default\n axis.setTickSpacing()\n \"\"\"\n\n if levels is None:\n if major is None:\n levels = None\n else:\n levels = [(major, 0), (minor, 0)]\n self._tickSpacing = levels\n self.picture = None\n self.update()\n\n\n def tickSpacing(self, minVal, maxVal, size):\n \"\"\"Return values describing the desired spacing and offset of ticks.\n\n This method is called whenever the axis needs to be redrawn and is a\n good method to override in subclasses that require control over tick locations.\n\n The return value must be a list of tuples, one for each set of ticks::\n\n [\n (major tick spacing, offset),\n (minor tick spacing, offset),\n (sub-minor tick spacing, offset),\n ...\n ]\n \"\"\"\n # First check for override tick spacing\n if self._tickSpacing is not None:\n return self._tickSpacing\n\n dif = abs(maxVal - minVal)\n if dif == 0:\n return []\n\n ## decide optimal minor tick spacing in pixels (this is just aesthetics)\n optimalTickCount = max(2., np.log(size))\n\n ## optimal minor tick spacing\n optimalSpacing = dif / optimalTickCount\n\n ## the largest power-of-10 spacing which is smaller than optimal\n p10unit = 10 ** np.floor(np.log10(optimalSpacing))\n\n ## Determine major/minor tick spacings which flank the optimal spacing.\n intervals = np.array([1., 2., 10., 20., 100.]) * p10unit\n minorIndex = 0\n while intervals[minorIndex+1] <= optimalSpacing:\n minorIndex += 1\n\n levels = [\n (intervals[minorIndex+2], 0),\n (intervals[minorIndex+1], 0),\n #(intervals[minorIndex], 0) ## Pretty, but eats up CPU\n ]\n\n if self.style['maxTickLevel'] >= 2:\n ## decide whether to include the last level of ticks\n minSpacing = min(size / 20., 30.)\n maxTickCount = size / minSpacing\n if dif / intervals[minorIndex] <= maxTickCount:\n levels.append((intervals[minorIndex], 0))\n \n return levels\n \n ##### This does not work -- switching between 2/5 confuses the automatic text-level-selection\n ### Determine major/minor tick spacings which flank the optimal spacing.\n #intervals = np.array([1., 2., 5., 10., 20., 50., 100.]) * p10unit\n #minorIndex = 0\n #while intervals[minorIndex+1] <= optimalSpacing:\n #minorIndex += 1\n\n ### make sure we never see 5 and 2 at the same time\n #intIndexes = [\n #[0,1,3],\n #[0,2,3],\n #[2,3,4],\n #[3,4,6],\n #[3,5,6],\n #][minorIndex]\n\n #return [\n #(intervals[intIndexes[2]], 0),\n #(intervals[intIndexes[1]], 0),\n #(intervals[intIndexes[0]], 0)\n #]\n\n def tickValues(self, minVal, maxVal, size):\n \"\"\"\n Return the values and spacing of ticks to draw::\n\n [\n (spacing, [major ticks]),\n (spacing, [minor ticks]),\n ...\n ]\n\n By default, this method calls tickSpacing to determine the correct tick locations.\n This is a good method to override in subclasses.\n \"\"\"\n minVal, maxVal = sorted((minVal, maxVal))\n\n\n minVal *= self.scale\n maxVal *= self.scale\n #size *= self.scale\n\n ticks = []\n tickLevels = self.tickSpacing(minVal, maxVal, size)\n allValues = np.array([])\n for i in range(len(tickLevels)):\n spacing, offset = tickLevels[i]\n\n ## determine starting tick\n start = (np.ceil((minVal-offset) / spacing) * spacing) + offset\n\n ## determine number of ticks\n num = int((maxVal-start) / spacing) + 1\n values = (np.arange(num) * spacing + start) / self.scale\n ## remove any ticks that were present in higher levels\n ## we assume here that if the difference between a tick value and a previously seen tick value\n ## is less than spacing/100, then they are 'equal' and we can ignore the new tick.\n values = list(filter(lambda x: all(np.abs(allValues-x) > spacing/self.scale*0.01), values))\n allValues = np.concatenate([allValues, values])\n ticks.append((spacing/self.scale, values))\n\n if self.logMode:\n return self.logTickValues(minVal, maxVal, size, ticks)\n\n\n #nticks = []\n #for t in ticks:\n #nvals = []\n #for v in t[1]:\n #nvals.append(v/self.scale)\n #nticks.append((t[0]/self.scale,nvals))\n #ticks = nticks\n\n return ticks\n\n def logTickValues(self, minVal, maxVal, size, stdTicks):\n\n ## start with the tick spacing given by tickValues().\n ## Any level whose spacing is < 1 needs to be converted to log scale\n\n ticks = []\n for (spacing, t) in stdTicks:\n if spacing >= 1.0:\n ticks.append((spacing, t))\n\n if len(ticks) < 3:\n v1 = int(np.floor(minVal))\n v2 = int(np.ceil(maxVal))\n #major = list(range(v1+1, v2))\n\n minor = []\n for v in range(v1, v2):\n minor.extend(v + np.log10(np.arange(1, 10)))\n minor = [x for x in minor if x>minVal and x<maxVal]\n ticks.append((None, minor))\n return ticks\n\n def tickStrings(self, values, scale, spacing):\n \"\"\"Return the strings that should be placed next to ticks. This method is called\n when redrawing the axis and is a good method to override in subclasses.\n The method is called with a list of tick values, a scaling factor (see below), and the\n spacing between ticks (this is required since, in some instances, there may be only\n one tick and thus no other way to determine the tick spacing)\n\n The scale argument is used when the axis label is displaying units which may have an SI scaling prefix.\n When determining the text to display, use value*scale to correctly account for this prefix.\n For example, if the axis label's units are set to 'V', then a tick value of 0.001 might\n be accompanied by a scale value of 1000. This indicates that the label is displaying 'mV', and\n thus the tick should display 0.001 * 1000 = 1.\n \"\"\"\n if self.logMode:\n return self.logTickStrings(values, scale, spacing)\n\n places = max(0, np.ceil(-np.log10(spacing*scale)))\n strings = []\n for v in values:\n vs = v * scale\n if abs(vs) < .001 or abs(vs) >= 10000:\n vstr = \"%g\" % vs\n else:\n vstr = (\"%%0.%df\" % places) % vs\n strings.append(vstr)\n return strings\n\n def logTickStrings(self, values, scale, spacing):\n return [\"%0.1g\"%x for x in 10 ** np.array(values).astype(float) * np.array(scale)]\n\n def generateDrawSpecs(self, p):\n \"\"\"\n Calls tickValues() and tickStrings() to determine where and how ticks should\n be drawn, then generates from this a set of drawing commands to be\n interpreted by drawPicture().\n \"\"\"\n profiler = debug.Profiler()\n\n #bounds = self.boundingRect()\n bounds = self.mapRectFromParent(self.geometry())\n\n linkedView = self.linkedView()\n if linkedView is None or self.grid is False:\n tickBounds = bounds\n else:\n tickBounds = linkedView.mapRectToItem(self, linkedView.boundingRect())\n\n if self.orientation == 'left':\n span = (bounds.topRight(), bounds.bottomRight())\n tickStart = tickBounds.right()\n tickStop = bounds.right()\n tickDir = -1\n axis = 0\n elif self.orientation == 'right':\n span = (bounds.topLeft(), bounds.bottomLeft())\n tickStart = tickBounds.left()\n tickStop = bounds.left()\n tickDir = 1\n axis = 0\n elif self.orientation == 'top':\n span = (bounds.bottomLeft(), bounds.bottomRight())\n tickStart = tickBounds.bottom()\n tickStop = bounds.bottom()\n tickDir = -1\n axis = 1\n elif self.orientation == 'bottom':\n span = (bounds.topLeft(), bounds.topRight())\n tickStart = tickBounds.top()\n tickStop = bounds.top()\n tickDir = 1\n axis = 1\n #print tickStart, tickStop, span\n\n ## determine size of this item in pixels\n points = list(map(self.mapToDevice, span))\n if None in points:\n return\n lengthInPixels = Point(points[1] - points[0]).length()\n if lengthInPixels == 0:\n return\n\n # Determine major / minor / subminor axis ticks\n if self._tickLevels is None:\n tickLevels = self.tickValues(self.range[0], self.range[1], lengthInPixels)\n tickStrings = None\n else:\n ## parse self.tickLevels into the formats returned by tickLevels() and tickStrings()\n tickLevels = []\n tickStrings = []\n for level in self._tickLevels:\n values = []\n strings = []\n tickLevels.append((None, values))\n tickStrings.append(strings)\n for val, strn in level:\n values.append(val)\n strings.append(strn)\n\n ## determine mapping between tick values and local coordinates\n dif = self.range[1] - self.range[0]\n if dif == 0:\n xScale = 1\n offset = 0\n else:\n if axis == 0:\n xScale = -bounds.height() / dif\n offset = self.range[0] * xScale - bounds.height()\n else:\n xScale = bounds.width() / dif\n offset = self.range[0] * xScale\n\n xRange = [x * xScale - offset for x in self.range]\n xMin = min(xRange)\n xMax = max(xRange)\n\n profiler('init')\n\n tickPositions = [] # remembers positions of previously drawn ticks\n\n ## compute coordinates to draw ticks\n ## draw three different intervals, long ticks first\n tickSpecs = []\n for i in range(len(tickLevels)):\n tickPositions.append([])\n ticks = tickLevels[i][1]\n\n ## length of tick\n tickLength = self.style['tickLength'] / ((i*0.5)+1.0)\n\n lineAlpha = 255 / (i+1)\n if self.grid is not False:\n lineAlpha *= self.grid/255. * np.clip((0.05 * lengthInPixels / (len(ticks)+1)), 0., 1.)\n\n for v in ticks:\n ## determine actual position to draw this tick\n x = (v * xScale) - offset\n if x < xMin or x > xMax: ## last check to make sure no out-of-bounds ticks are drawn\n tickPositions[i].append(None)\n continue\n tickPositions[i].append(x)\n\n p1 = [x, x]\n p2 = [x, x]\n p1[axis] = tickStart\n p2[axis] = tickStop\n if self.grid is False:\n p2[axis] += tickLength*tickDir\n tickPen = self.pen()\n color = tickPen.color()\n color.setAlpha(lineAlpha)\n tickPen.setColor(color)\n tickSpecs.append((tickPen, Point(p1), Point(p2)))\n profiler('compute ticks')\n\n\n if self.style['stopAxisAtTick'][0] is True:\n minTickPosition = min(map(min, tickPositions))\n if axis == 0:\n stop = max(span[0].y(), minTickPosition)\n span[0].setY(stop)\n else:\n stop = max(span[0].x(), minTickPosition)\n span[0].setX(stop)\n if self.style['stopAxisAtTick'][1] is True:\n maxTickPosition = max(map(max, tickPositions))\n if axis == 0:\n stop = min(span[1].y(), maxTickPosition)\n span[1].setY(stop)\n else:\n stop = min(span[1].x(), maxTickPosition)\n span[1].setX(stop)\n axisSpec = (self.pen(), span[0], span[1])\n\n\n textOffset = self.style['tickTextOffset'][axis] ## spacing between axis and text\n #if self.style['autoExpandTextSpace'] is True:\n #textWidth = self.textWidth\n #textHeight = self.textHeight\n #else:\n #textWidth = self.style['tickTextWidth'] ## space allocated for horizontal text\n #textHeight = self.style['tickTextHeight'] ## space allocated for horizontal text\n\n textSize2 = 0\n textRects = []\n textSpecs = [] ## list of draw\n\n # If values are hidden, return early\n if not self.style['showValues']:\n return (axisSpec, tickSpecs, textSpecs)\n\n for i in range(min(len(tickLevels), self.style['maxTextLevel']+1)):\n ## Get the list of strings to display for this level\n if tickStrings is None:\n spacing, values = tickLevels[i]\n strings = self.tickStrings(values, self.autoSIPrefixScale * self.scale, spacing)\n else:\n strings = tickStrings[i]\n\n if len(strings) == 0:\n continue\n\n ## ignore strings belonging to ticks that were previously ignored\n for j in range(len(strings)):\n if tickPositions[i][j] is None:\n strings[j] = None\n\n ## Measure density of text; decide whether to draw this level\n rects = []\n for s in strings:\n if s is None:\n rects.append(None)\n else:\n br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, asUnicode(s))\n ## boundingRect is usually just a bit too large\n ## (but this probably depends on per-font metrics?)\n br.setHeight(br.height() * 0.8)\n\n rects.append(br)\n textRects.append(rects[-1])\n\n if len(textRects) > 0:\n ## measure all text, make sure there's enough room\n if axis == 0:\n textSize = np.sum([r.height() for r in textRects])\n textSize2 = np.max([r.width() for r in textRects])\n else:\n textSize = np.sum([r.width() for r in textRects])\n textSize2 = np.max([r.height() for r in textRects])\n else:\n textSize = 0\n textSize2 = 0\n\n if i > 0: ## always draw top level\n ## If the strings are too crowded, stop drawing text now.\n ## We use three different crowding limits based on the number\n ## of texts drawn so far.\n textFillRatio = float(textSize) / lengthInPixels\n finished = False\n for nTexts, limit in self.style['textFillLimits']:\n if len(textSpecs) >= nTexts and textFillRatio >= limit:\n finished = True\n break\n if finished:\n break\n\n #spacing, values = tickLevels[best]\n #strings = self.tickStrings(values, self.scale, spacing)\n # Determine exactly where tick text should be drawn\n for j in range(len(strings)):\n vstr = strings[j]\n if vstr is None: ## this tick was ignored because it is out of bounds\n continue\n vstr = asUnicode(vstr)\n x = tickPositions[i][j]\n #textRect = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, vstr)\n textRect = rects[j]\n height = textRect.height()\n width = textRect.width()\n #self.textHeight = height\n offset = max(0,self.style['tickLength']) + textOffset\n if self.orientation == 'left':\n textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter\n rect = QtCore.QRectF(tickStop-offset-width, x-(height/2), width, height)\n elif self.orientation == 'right':\n textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter\n rect = QtCore.QRectF(tickStop+offset, x-(height/2), width, height)\n elif self.orientation == 'top':\n textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignCenter|QtCore.Qt.AlignBottom\n rect = QtCore.QRectF(x-width/2., tickStop-offset-height, width, height)\n elif self.orientation == 'bottom':\n textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignCenter|QtCore.Qt.AlignTop\n rect = QtCore.QRectF(x-width/2., tickStop+offset, width, height)\n\n #p.setPen(self.pen())\n #p.drawText(rect, textFlags, vstr)\n textSpecs.append((rect, textFlags, vstr))\n profiler('compute text')\n\n ## update max text size if needed.\n self._updateMaxTextSize(textSize2)\n\n return (axisSpec, tickSpecs, textSpecs)\n\n def drawPicture(self, p, axisSpec, tickSpecs, textSpecs):\n profiler = debug.Profiler()\n\n p.setRenderHint(p.Antialiasing, False)\n p.setRenderHint(p.TextAntialiasing, True)\n\n ## draw long line along axis\n pen, p1, p2 = axisSpec\n p.setPen(pen)\n p.drawLine(p1, p2)\n p.translate(0.5,0) ## resolves some damn pixel ambiguity\n\n ## draw ticks\n for pen, p1, p2 in tickSpecs:\n p.setPen(pen)\n p.drawLine(p1, p2)\n profiler('draw ticks')\n\n ## Draw all text\n if self.tickFont is not None:\n p.setFont(self.tickFont)\n p.setPen(self.pen())\n for rect, flags, text in textSpecs:\n p.drawText(rect, flags, text)\n #p.drawRect(rect)\n profiler('draw text')\n\n def show(self):\n GraphicsWidget.show(self)\n if self.orientation in ['left', 'right']:\n self._updateWidth()\n else:\n self._updateHeight()\n\n def hide(self):\n GraphicsWidget.hide(self)\n if self.orientation in ['left', 'right']:\n self._updateWidth()\n else:\n self._updateHeight()\n\n def wheelEvent(self, ev):\n if self.linkedView() is None:\n return\n if self.orientation in ['left', 'right']:\n self.linkedView().wheelEvent(ev, axis=1)\n else:\n self.linkedView().wheelEvent(ev, axis=0)\n ev.accept()\n\n def mouseDragEvent(self, event):\n if self.linkedView() is None:\n return\n if self.orientation in ['left', 'right']:\n return self.linkedView().mouseDragEvent(event, axis=1)\n else:\n return self.linkedView().mouseDragEvent(event, axis=0)\n\n def mouseClickEvent(self, event):\n if self.linkedView() is None:\n return\n return self.linkedView().mouseClickEvent(event)\n" ]
[ [ "numpy.log", "numpy.abs", "numpy.isnan", "numpy.arange", "numpy.concatenate", "numpy.ceil", "numpy.log10", "numpy.floor", "numpy.array", "numpy.isinf" ] ]
hetaShah27/metriks
[ "a0e62df847b8997bfc32b337d7e41db16d0a8ce4" ]
[ "tests/test_confusion_matrix_at_k.py" ]
[ "import numpy as np\nimport metriks\n\n\ndef test_confusion_matrix_at_k_wikipedia():\n \"\"\"\n Tests the wikipedia example.\n\n https://en.wikipedia.org/wiki/Mean_reciprocal_rank\n \"\"\"\n\n # Flag indicating which is actually relevant\n y_true = np.array([\n [0, 0, 1],\n [0, 1, 0],\n [1, 0, 0],\n ])\n\n # The predicted probability\n y_prob = np.array([\n [0.4, 0.6, 0.3],\n [0.1, 0.2, 0.9],\n [0.9, 0.6, 0.3],\n ])\n\n expected = (\n np.array([1, 0, 1]),\n np.array([1, 2, 1]),\n np.array([0, 0, 1]),\n np.array([1, 1, 0])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 2)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n\ndef test_confusion_matrix_at_k_with_errors():\n \"\"\"Test confusion_matrix_at_k where there are errors in the probabilities\"\"\"\n y_true = np.array([\n [1, 1, 0],\n [1, 0, 1],\n [1, 1, 0],\n [1, 0, 1],\n [0, 1, 0],\n [0, 1, 1],\n [0, 1, 1],\n [1, 0, 1],\n [1, 1, 1],\n ])\n\n y_prob = np.array([\n [0.7, 0.6, 0.3],\n [0.9, 0.2, 0.1], # 3rd probability is an error\n [0.7, 0.8, 0.9], # 3rd probability is an error\n [0.9, 0.8, 0.3], # 2nd and 3rd probability are swapped\n [0.4, 0.6, 0.3],\n [0.1, 0.6, 0.9],\n [0.1, 0.6, 0.9],\n [0.1, 0.6, 0.5],\n [0.9, 0.8, 0.7],\n ])\n\n # Check results\n expected = (\n np.array([2, 0, 2]),\n np.array([1, 3, 1]),\n np.array([2, 0, 3]),\n np.array([4, 6, 3])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 2)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n\ndef test_confusion_matrix_at_k_perfect():\n \"\"\"Test confusion_matrix_at_k where the probabilities are perfect\"\"\"\n y_true = np.array([\n [0, 1, 0],\n [1, 0, 0],\n [0, 1, 0],\n [1, 0, 0],\n [0, 0, 1],\n ])\n\n y_prob = np.array([\n [0.3, 0.7, 0.0],\n [0.1, 0.0, 0.0],\n [0.1, 0.5, 0.3],\n [0.6, 0.2, 0.4],\n [0.1, 0.2, 0.3],\n ])\n\n # Check results\n expected = (\n np.array([3, 3, 4]),\n np.array([0, 0, 0]),\n np.array([0, 0, 0]),\n np.array([2, 2, 1])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 1)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n\ndef test_confusion_matrix_at_k_perfect_multiple_true():\n \"\"\"Test confusion_matrix_at_k where the probabilities are perfect and there\n are multiple true labels for some samples\"\"\"\n y_true = np.array([\n [1, 1, 0],\n [1, 0, 0],\n [0, 1, 1],\n [1, 0, 1],\n [0, 1, 1],\n ])\n\n y_prob = np.array([\n [0.3, 0.7, 0.0],\n [0.1, 0.05, 0.0],\n [0.1, 0.5, 0.3],\n [0.6, 0.2, 0.4],\n [0.1, 0.2, 0.3],\n ])\n\n # Check results for k=0\n expected = (\n np.array([2, 2, 2]),\n np.array([0, 0, 0]),\n np.array([3, 3, 3]),\n np.array([0, 0, 0])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 0)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n # Check results for k=2\n expected = (\n np.array([2, 1, 2]),\n np.array([0, 1, 0]),\n np.array([0, 0, 0]),\n np.array([3, 3, 3])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 2)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n\ndef test_confusion_matrix_at_k_few_zeros():\n \"\"\"Test confusion_matrix_at_k where there are very few zeros\"\"\"\n y_true = np.array([\n [0, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 0]\n ])\n\n y_prob = np.array([\n [0.1, 0.4, 0.35, 0.8, 0.9],\n [0.3, 0.2, 0.7, 0.8, 0.6],\n [0.1, 0.2, 0.3, 0.4, 0.5]\n ])\n\n # Check results for k=2\n expected = (\n np.array([1, 0, 0, 0, 0]),\n np.array([0, 0, 0, 0, 1]),\n np.array([2, 3, 2, 0, 1]),\n np.array([0, 0, 1, 3, 1])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 2)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n # Check results for k=5\n expected = {\n 'moved': {'fp': 1, 'tn': 0, 'fn': 0, 'tp': 2},\n 'hadAJob': {'fp': 0, 'tn': 0, 'fn': 0, 'tp': 3},\n 'farmIncome': {'fp': 0, 'tn': 0, 'fn': 0, 'tp': 3},\n 'married': {'fp': 0, 'tn': 0, 'fn': 0, 'tp': 3},\n 'alimony': {'fp': 1, 'tn': 0, 'fn': 0, 'tp': 2}\n }\n expected = (\n np.array([0, 0, 0, 0, 0]),\n np.array([1, 0, 0, 0, 1]),\n np.array([0, 0, 0, 0, 0]),\n np.array([2, 3, 3, 3, 2])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 5)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n\ndef test_confusion_matrix_at_k_zeros():\n \"\"\"Test confusion_matrix_at_k where there is a sample of all zeros\"\"\"\n y_true = np.array([\n [0, 0, 1, 1],\n [1, 1, 1, 0],\n [0, 0, 0, 0]\n ])\n\n y_prob = np.array([\n [0.1, 0.4, 0.35, 0.8],\n [0.3, 0.2, 0.7, 0.8],\n [0.1, 0.2, 0.3, 0.4]\n ])\n\n # Check results\n expected = {\n 'moved': {'fp': 0, 'tn': 2, 'fn': 1, 'tp': 0},\n 'hadAJob': {'fp': 1, 'tn': 1, 'fn': 1, 'tp': 0},\n 'farmIncome': {'fp': 1, 'tn': 0, 'fn': 1, 'tp': 1},\n 'married': {'fp': 2, 'tn': 0, 'fn': 0, 'tp': 1}\n }\n expected = (\n np.array([2, 1, 0, 0]),\n np.array([0, 1, 1, 2]),\n np.array([1, 1, 1, 0]),\n np.array([0, 0, 1, 1])\n )\n result = metriks.confusion_matrix_at_k(y_true, y_prob, 2)\n for i in range(4):\n assert expected[i].all() == result[i].all(), AssertionError(\n 'Expected:\\n{expected}. \\nGot:\\n{actual}'\n .format(expected=expected, actual=result)\n )\n\n print(result)\n\n\nif __name__ == '__main__':\n test_confusion_matrix_at_k_wikipedia()\n test_confusion_matrix_at_k_with_errors()\n test_confusion_matrix_at_k_perfect()\n test_confusion_matrix_at_k_perfect_multiple_true()\n test_confusion_matrix_at_k_few_zeros()\n test_confusion_matrix_at_k_zeros()\n" ]
[ [ "numpy.array" ] ]
ProgrammerWaterworth/Mastering-OpenCV-4-with-Python
[ "c90305898f1413267404f1ac83075133299060bb", "c90305898f1413267404f1ac83075133299060bb" ]
[ "Chapter12/01-chapter-content/tensorflow/introduction_tensorflow/tensorflow_basic_op.py", "Chapter12/01-chapter-content/opencv/blob_from_images/blob_from_images_cropping.py" ]
[ "\"\"\"\nBasic Operations example using TensorFlow library.\n\"\"\"\n\n# Import required packages:\nimport tensorflow as tf\n\n# path to the folder that we want to save the logs for Tensorboard\nlogs_path = \"./logs\"\n\n# Define placeholders:\nX_1 = tf.placeholder(tf.int16, name=\"X_1\")\nX_2 = tf.placeholder(tf.int16, name=\"X_2\")\n\n# Define a multiplication operation:\nmultiply = tf.multiply(X_1, X_2, name=\"my_multiplication\")\n\n# Start the session and run the operation with different inputs:\nwith tf.Session() as sess:\n summary_writer = tf.summary.FileWriter(logs_path, sess.graph)\n\n print(\"2 x 3 = {}\".format(sess.run(multiply, feed_dict={X_1: 2, X_2: 3})))\n print(\"[2, 3] x [3, 4] = {}\".format(sess.run(multiply, feed_dict={X_1: [2, 3], X_2: [3, 4]})))\n", "\"\"\"\nUnderstanding cv2.dnn.blobFromImages() and cv2.dnn.imagesFromBlob() in OpenCV with cropping\n\"\"\"\n\n# Import required packages:\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef get_cropped_img(img):\n \"\"\"Returns the cropped image\"\"\"\n\n # Create a copy of the image:\n img_copy = img.copy()\n\n # calculate size of resulting image:\n size = min(img_copy.shape[1], img_copy.shape[0])\n\n # calculate x1, and y1\n x1 = int(0.5 * (img_copy.shape[1] - size))\n y1 = int(0.5 * (img_copy.shape[0] - size))\n\n # crop and return the image\n return img_copy[y1:(y1 + size), x1:(x1 + size)]\n\n\ndef show_img_with_matplotlib(color_img, title, pos):\n \"\"\"Shows an image using matplotlib capabilities\"\"\"\n\n img_RGB = color_img[:, :, ::-1]\n\n ax = plt.subplot(2, 2, pos)\n plt.imshow(img_RGB)\n plt.title(title)\n plt.axis('off')\n\n\ndef get_images_from_blob(blob_imgs, scalefactor, dim, mean, swap_rb, mean_added):\n \"\"\"Returns images from blob\"\"\"\n\n images_from_blob = cv2.dnn.imagesFromBlob(blob_imgs)\n imgs = []\n\n for image_blob in images_from_blob:\n image_from_blob = np.reshape(image_blob, dim) / scalefactor\n image_from_blob_mean = np.uint8(image_from_blob)\n image_from_blob = image_from_blob_mean + np.uint8(mean)\n if mean_added is True:\n if swap_rb:\n image_from_blob = image_from_blob[:, :, ::-1]\n imgs.append(image_from_blob)\n else:\n if swap_rb:\n image_from_blob_mean = image_from_blob_mean[:, :, ::-1]\n imgs.append(image_from_blob_mean)\n\n return imgs\n\n\n# Load images and get the list of images:\nimage = cv2.imread(\"face_test.jpg\")\nimage2 = cv2.imread(\"face_test_2.jpg\")\nimages = [image, image2]\n\n# To see how cropping works, we are going to perform the cropping formulation that\n# both blobFromImage() and blobFromImages() perform applying it to one of the input images:\ncropped_img = get_cropped_img(image)\n# cv2.imwrite(\"cropped_img.jpg\", cropped_img)\n\n# Call cv2.dnn.blobFromImages():\nblob_images = cv2.dnn.blobFromImages(images, 1.0, (300, 300), [104., 117., 123.], False, False)\nblob_blob_images_cropped = cv2.dnn.blobFromImages(images, 1.0, (300, 300), [104., 117., 123.], False, True)\n\n# Get different images from the blob:\nimgs_from_blob = get_images_from_blob(blob_images, 1.0, (300, 300, 3), [104., 117., 123.], False, True)\nimgs_from_blob_cropped = get_images_from_blob(blob_blob_images_cropped, 1.0, (300, 300, 3), [104., 117., 123.], False,\n True)\n\n# Create the dimensions of the figure and set title:\nfig = plt.figure(figsize=(10, 8))\nplt.suptitle(\"cv2.dnn.blobFromImages() visualization with cropping\", fontsize=14, fontweight='bold')\nfig.patch.set_facecolor('silver')\n\n# Show the input images\nshow_img_with_matplotlib(imgs_from_blob[0], \"img 1 from blob \" + str(imgs_from_blob[0].shape), 1)\nshow_img_with_matplotlib(imgs_from_blob[1], \"img 2 from blob \" + str(imgs_from_blob[1].shape), 2)\nshow_img_with_matplotlib(imgs_from_blob_cropped[0], \"img 1 from blob cropped \" + str(imgs_from_blob[1].shape), 3)\nshow_img_with_matplotlib(imgs_from_blob_cropped[1], \"img 2 from blob cropped \" + str(imgs_from_blob[1].shape), 4)\n\n# Show the Figure:\nplt.show()\n" ]
[ [ "tensorflow.multiply", "tensorflow.summary.FileWriter", "tensorflow.placeholder", "tensorflow.Session" ], [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.title", "numpy.reshape", "numpy.uint8", "matplotlib.pyplot.subplot", "matplotlib.pyplot.axis", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
artdreamer/stable-baselines3
[ "198d8a02a296a67898d54c3acb19dafea18ccd27" ]
[ "stable_baselines3/ppo/ppo.py" ]
[ "import warnings\nfrom typing import Any, Dict, Optional, Type, Union\n\nimport numpy as np\nimport torch as th\nfrom gym import spaces\nfrom torch.nn import functional as F\n\nfrom stable_baselines3.common.on_policy_algorithm import OnPolicyAlgorithm\nfrom stable_baselines3.common.policies import ActorCriticPolicy\nfrom stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule\nfrom stable_baselines3.common.utils import explained_variance, get_schedule_fn\n\n\nclass PPO(OnPolicyAlgorithm):\n \"\"\"\n Proximal Policy Optimization algorithm (PPO) (clip version)\n\n Paper: https://arxiv.org/abs/1707.06347\n Code: This implementation borrows code from OpenAI Spinning Up (https://github.com/openai/spinningup/)\n https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail and\n and Stable Baselines (PPO2 from https://github.com/hill-a/stable-baselines)\n\n Introduction to PPO: https://spinningup.openai.com/en/latest/algorithms/ppo.html\n\n :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)\n :param env: The environment to learn from (if registered in Gym, can be str)\n :param learning_rate: The learning rate, it can be a function\n of the current progress remaining (from 1 to 0)\n :param n_steps: The number of steps to run for each environment per update\n (i.e. rollout buffer size is n_steps * n_envs where n_envs is number of environment copies running in parallel)\n NOTE: n_steps * n_envs must be greater than 1 (because of the advantage normalization)\n See https://github.com/pytorch/pytorch/issues/29372\n :param batch_size: Minibatch size\n :param n_epochs: Number of epoch when optimizing the surrogate loss\n :param gamma: Discount factor\n :param gae_lambda: Factor for trade-off of bias vs variance for Generalized Advantage Estimator\n :param clip_range: Clipping parameter, it can be a function of the current progress\n remaining (from 1 to 0).\n :param clip_range_vf: Clipping parameter for the value function,\n it can be a function of the current progress remaining (from 1 to 0).\n This is a parameter specific to the OpenAI implementation. If None is passed (default),\n no clipping will be done on the value function.\n IMPORTANT: this clipping depends on the reward scaling.\n :param normalize_advantage: Whether to normalize or not the advantage\n :param ent_coef: Entropy coefficient for the loss calculation\n :param vf_coef: Value function coefficient for the loss calculation\n :param max_grad_norm: The maximum value for the gradient clipping\n :param use_sde: Whether to use generalized State Dependent Exploration (gSDE)\n instead of action noise exploration (default: False)\n :param sde_sample_freq: Sample a new noise matrix every n steps when using gSDE\n Default: -1 (only sample at the beginning of the rollout)\n :param target_kl: Limit the KL divergence between updates,\n because the clipping is not enough to prevent large update\n see issue #213 (cf https://github.com/hill-a/stable-baselines/issues/213)\n By default, there is no limit on the kl div.\n :param tensorboard_log: the log location for tensorboard (if None, no logging)\n :param create_eval_env: Whether to create a second environment that will be\n used for evaluating the agent periodically. (Only available when passing string for the environment)\n :param policy_kwargs: additional arguments to be passed to the policy on creation\n :param verbose: the verbosity level: 0 no output, 1 info, 2 debug\n :param seed: Seed for the pseudo random generators\n :param device: Device (cpu, cuda, ...) on which the code should be run.\n Setting it to auto, the code will be run on the GPU if possible.\n :param _init_setup_model: Whether or not to build the network at the creation of the instance\n \"\"\"\n\n def __init__(\n self,\n policy: Union[str, Type[ActorCriticPolicy]],\n env: Union[GymEnv, str],\n learning_rate: Union[float, Schedule] = 3e-4,\n n_steps: int = 2048,\n batch_size: int = 64,\n n_epochs: int = 10,\n gamma: float = 0.99,\n gae_lambda: float = 0.95,\n clip_range: Union[float, Schedule] = 0.2,\n clip_range_vf: Union[None, float, Schedule] = None,\n normalize_advantage: bool = True,\n ent_coef: float = 0.0,\n vf_coef: float = 0.5,\n max_grad_norm: float = 0.5,\n use_sde: bool = False,\n sde_sample_freq: int = -1,\n target_kl: Optional[float] = None,\n tensorboard_log: Optional[str] = None,\n create_eval_env: bool = False,\n policy_kwargs: Optional[Dict[str, Any]] = None,\n verbose: int = 0,\n seed: Optional[int] = None,\n device: Union[th.device, str] = \"auto\",\n _init_setup_model: bool = True,\n ):\n\n super(PPO, self).__init__(\n policy,\n env,\n learning_rate=learning_rate,\n n_steps=n_steps,\n gamma=gamma,\n gae_lambda=gae_lambda,\n ent_coef=ent_coef,\n vf_coef=vf_coef,\n max_grad_norm=max_grad_norm,\n use_sde=use_sde,\n sde_sample_freq=sde_sample_freq,\n tensorboard_log=tensorboard_log,\n policy_kwargs=policy_kwargs,\n verbose=verbose,\n device=device,\n create_eval_env=create_eval_env,\n seed=seed,\n _init_setup_model=False,\n supported_action_spaces=(\n spaces.Box,\n spaces.Discrete,\n spaces.MultiDiscrete,\n spaces.MultiBinary,\n ),\n )\n\n # Sanity check, otherwise it will lead to noisy gradient and NaN\n # because of the advantage normalization\n if normalize_advantage:\n assert (\n batch_size > 1\n ), \"`batch_size` must be greater than 1. See https://github.com/DLR-RM/stable-baselines3/issues/440\"\n\n if self.env is not None:\n # Check that `n_steps * n_envs > 1` to avoid NaN\n # when doing advantage normalization\n buffer_size = self.env.num_envs * self.n_steps\n assert (\n buffer_size > 1\n ), f\"`n_steps * n_envs` must be greater than 1. Currently n_steps={self.n_steps} and n_envs={self.env.num_envs}\"\n # Check that the rollout buffer size is a multiple of the mini-batch size\n untruncated_batches = buffer_size // batch_size\n if buffer_size % batch_size > 0:\n warnings.warn(\n f\"You have specified a mini-batch size of {batch_size},\"\n f\" but because the `RolloutBuffer` is of size `n_steps * n_envs = {buffer_size}`,\"\n f\" after every {untruncated_batches} untruncated mini-batches,\"\n f\" there will be a truncated mini-batch of size {buffer_size % batch_size}\\n\"\n f\"We recommend using a `batch_size` that is a factor of `n_steps * n_envs`.\\n\"\n f\"Info: (n_steps={self.n_steps} and n_envs={self.env.num_envs})\"\n )\n self.batch_size = batch_size\n self.n_epochs = n_epochs\n self.clip_range = clip_range\n self.clip_range_vf = clip_range_vf\n self.normalize_advantage = normalize_advantage\n self.target_kl = target_kl\n\n if _init_setup_model:\n self._setup_model()\n\n def _setup_model(self) -> None:\n super(PPO, self)._setup_model()\n\n # Initialize schedules for policy/value clipping\n self.clip_range = get_schedule_fn(self.clip_range)\n if self.clip_range_vf is not None:\n if isinstance(self.clip_range_vf, (float, int)):\n assert self.clip_range_vf > 0, \"`clip_range_vf` must be positive, \" \"pass `None` to deactivate vf clipping\"\n\n self.clip_range_vf = get_schedule_fn(self.clip_range_vf)\n\n def train(self) -> None:\n \"\"\"\n Update policy using the currently gathered rollout buffer.\n \"\"\"\n # Switch to train mode (this affects batch norm / dropout)\n self.policy.set_training_mode(True)\n # Update optimizer learning rate\n self._update_learning_rate(self.policy.optimizer)\n # Compute current clip range\n clip_range = self.clip_range(self._current_progress_remaining)\n # Optional: clip range for the value function\n if self.clip_range_vf is not None:\n clip_range_vf = self.clip_range_vf(self._current_progress_remaining)\n\n entropy_losses = []\n pg_losses, value_losses = [], []\n clip_fractions = []\n\n continue_training = True\n\n # train for n_epochs epochs\n for epoch in range(self.n_epochs):\n approx_kl_divs = []\n # Do a complete pass on the rollout buffer\n for rollout_data in self.rollout_buffer.get(self.batch_size):\n actions = rollout_data.actions\n if isinstance(self.action_space, spaces.Discrete):\n # Convert discrete action from float to long\n actions = rollout_data.actions.long().flatten()\n\n # Re-sample the noise matrix because the log_std has changed\n if self.use_sde:\n self.policy.reset_noise(self.batch_size)\n\n values, log_prob, entropy = self.policy.evaluate_actions(rollout_data.observations, actions)\n values = values.flatten()\n # Normalize advantage\n advantages = rollout_data.advantages\n if self.normalize_advantage:\n advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)\n\n # ratio between old and new policy, should be one at the first iteration\n ratio = th.exp(log_prob - rollout_data.old_log_prob)\n\n # clipped surrogate loss\n policy_loss_1 = advantages * ratio\n policy_loss_2 = advantages * th.clamp(ratio, 1 - clip_range, 1 + clip_range)\n policy_loss = -th.min(policy_loss_1, policy_loss_2).mean()\n\n # Logging\n pg_losses.append(policy_loss.item())\n clip_fraction = th.mean((th.abs(ratio - 1) > clip_range).float()).item()\n clip_fractions.append(clip_fraction)\n\n if self.clip_range_vf is None:\n # No clipping\n values_pred = values\n else:\n # Clip the different between old and new value\n # NOTE: this depends on the reward scaling\n values_pred = rollout_data.old_values + th.clamp(\n values - rollout_data.old_values, -clip_range_vf, clip_range_vf\n )\n # Value loss using the TD(gae_lambda) target\n value_loss = F.mse_loss(rollout_data.returns, values_pred)\n value_losses.append(value_loss.item())\n\n # Entropy loss favor exploration\n if entropy is None:\n # Approximate entropy when no analytical form\n entropy_loss = -th.mean(-log_prob)\n else:\n entropy_loss = -th.mean(entropy)\n\n entropy_losses.append(entropy_loss.item())\n\n loss = policy_loss + self.ent_coef * entropy_loss + self.vf_coef * value_loss\n\n # Calculate approximate form of reverse KL Divergence for early stopping\n # see issue #417: https://github.com/DLR-RM/stable-baselines3/issues/417\n # and discussion in PR #419: https://github.com/DLR-RM/stable-baselines3/pull/419\n # and Schulman blog: http://joschu.net/blog/kl-approx.html\n with th.no_grad():\n log_ratio = log_prob - rollout_data.old_log_prob\n approx_kl_div = th.mean((th.exp(log_ratio) - 1) - log_ratio).cpu().numpy()\n approx_kl_divs.append(approx_kl_div)\n\n if self.target_kl is not None and approx_kl_div > 1.5 * self.target_kl:\n continue_training = False\n if self.verbose >= 1:\n print(f\"Early stopping at step {epoch} due to reaching max kl: {approx_kl_div:.2f}\")\n break\n\n # Optimization step\n self.policy.optimizer.zero_grad()\n loss.backward()\n # Clip grad norm\n th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm)\n self.policy.optimizer.step()\n\n if not continue_training:\n break\n\n self._n_updates += self.n_epochs\n explained_var = explained_variance(self.rollout_buffer.values.flatten(), self.rollout_buffer.returns.flatten())\n\n # Logs\n self.logger.record(\"train/entropy_loss\", np.mean(entropy_losses))\n self.logger.record(\"train/policy_gradient_loss\", np.mean(pg_losses))\n self.logger.record(\"train/value_loss\", np.mean(value_losses))\n self.logger.record(\"train/approx_kl\", np.mean(approx_kl_divs))\n self.logger.record(\"train/clip_fraction\", np.mean(clip_fractions))\n self.logger.record(\"train/loss\", loss.item())\n self.logger.record(\"train/explained_variance\", explained_var)\n if hasattr(self.policy, \"log_std\"):\n self.logger.record(\"train/std\", th.exp(self.policy.log_std).mean().item())\n\n self.logger.record(\"train/n_updates\", self._n_updates, exclude=\"tensorboard\")\n self.logger.record(\"train/clip_range\", clip_range)\n if self.clip_range_vf is not None:\n self.logger.record(\"train/clip_range_vf\", clip_range_vf)\n\n def learn(\n self,\n total_timesteps: int,\n callback: MaybeCallback = None,\n log_interval: int = 1,\n eval_env: Optional[GymEnv] = None,\n eval_freq: int = -1,\n n_eval_episodes: int = 5,\n tb_log_name: str = \"PPO\",\n eval_log_path: Optional[str] = None,\n reset_num_timesteps: bool = True,\n ) -> \"PPO\":\n\n return super(PPO, self).learn(\n total_timesteps=total_timesteps,\n callback=callback,\n log_interval=log_interval,\n eval_env=eval_env,\n eval_freq=eval_freq,\n n_eval_episodes=n_eval_episodes,\n tb_log_name=tb_log_name,\n eval_log_path=eval_log_path,\n reset_num_timesteps=reset_num_timesteps,\n )\n" ]
[ [ "torch.mean", "torch.abs", "torch.min", "torch.exp", "torch.nn.functional.mse_loss", "torch.no_grad", "numpy.mean", "torch.clamp" ] ]
pollen-robotics/reachy-2.0
[ "1721c2d93737e576e328bfdb78376d1b0163d3d6" ]
[ "software/reachy/utils/__init__.py" ]
[ "\"\"\"Utility toolbox submodules.\"\"\"\n\nimport numpy as np\n\nfrom scipy.spatial.transform import Rotation as R\n\n\ndef rot(axis, deg):\n \"\"\"Compute 3D rotation matrix given euler rotation.\"\"\"\n return R.from_euler(axis, np.deg2rad(deg)).as_matrix()\n" ]
[ [ "numpy.deg2rad" ] ]
rootroom100/study-picamera-examples
[ "a991f92f5bc6a2be2b53308b8205d0fd65a53ba0" ]
[ "camera/processor/face_detector.py" ]
[ "from __future__ import print_function\r\nfrom imutils.video.pivideostream import PiVideoStream\r\nimport imutils\r\nimport time\r\nimport numpy as np\r\nimport cv2\r\n\r\nclass FaceDetector(object):\r\n def __init__(self, flip = True):\r\n self.vs = PiVideoStream(resolution=(800, 608)).start()\r\n self.flip = flip\r\n time.sleep(2.0)\r\n\r\n # opencvの顔分類器(CascadeClassifier)をインスタンス化する\r\n self.face_cascade = cv2.CascadeClassifier('camera/processor/model/haarcascades/haarcascade_frontalface_default.xml')\r\n\r\n def __del__(self):\r\n self.vs.stop()\r\n\r\n def flip_if_needed(self, frame):\r\n if self.flip:\r\n return np.flip(frame, 0)\r\n return frame\r\n \r\n #カメラから画像を取得してjpgに変換\r\n def get_frame(self):\r\n frame = self.flip_if_needed(self.vs.read())\r\n frame = self.process_image(frame)\r\n ret, jpeg = cv2.imencode('.jpg', frame)\r\n return jpeg.tobytes()\r\n\r\n def process_image(self, frame):\r\n # opencvでframe(カラー画像)をグレースケールに変換\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n # 上記でグレースケールに変換したものをインスタンス化した顔分類器の\r\n # detectMultiScaleメソッドで処理し、認識した顔の座標情報を取得する\r\n faces = self.face_cascade.detectMultiScale(gray, 1.3, 3)\r\n \r\n # 取得した座標情報を元に、cv2.rectangleを使ってframe上に\r\n # 顔の位置を描画する\r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)\r\n\r\n # フレームに文字列を表示させる。\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n cv2.putText(frame,'TESTTEXT',(x,y+h), font, 1,(255,255,255),2,cv2.LINE_AA,False)\r\n\r\n # frameを戻り値として返す\r\n return frame\r\n" ]
[ [ "numpy.flip" ] ]
astromid/pandemicdatahack-track3
[ "0812dad4ed08c4bb952d80d0610b2fa92d27901a" ]
[ "src/base_regressor.py" ]
[ "import random\nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import mean_squared_error\nfrom lightgbm import LGBMRegressor\nfrom .base_preprocessor import BasePreprocessor\nSEED = 1377\nN_FOLDS = 10\n\nrandom.seed(SEED)\nnp.random.seed(SEED)\n\n\nclass BaseRegressor:\n def __init__(self, path_to_raw):\n self.preprocessor = BasePreprocessor(path_to_raw)\n self.fold_preprocessors = []\n\n def preprocess(self, path_to_raw='../data/raw'):\n self.train = self.preprocessor.transform_train()\n self.test = self.preprocessor.transform_test()\n\n def create_model_and_fit(self, X_train, y_train, X_val, y_val, hparams=None):\n model = LGBMRegressor(max_depth=5, n_estimators=500, n_jobs=16)\n model.fit(\n X_train,\n y_train,\n )\n\n return model, mean_squared_error(model.predict(X_val), y_val)\n\n def fit(self, hparams=None):\n skf = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\n\n self.cv_metrics = []\n\n self.models = []\n self.clf_models = []\n i = 0\n for train_indexes, val_indexes in skf.split(self.train, self.train['publish_year']):\n # print(f\"Fold {i}\")\n i += 1\n X_train = self.train.iloc[train_indexes]\n y_train = X_train['salary']\n X_train = X_train.drop(['id', 'salary'], axis=1)\n\n X_val = self.train.iloc[val_indexes]\n y_val = X_val['salary']\n X_val = X_val.drop(['id', 'salary'], axis=1)\n\n clf_model, model, val_metric = self.create_model_and_fit(X_train, y_train, X_val, y_val, hparams)\n self.clf_models.append(clf_model)\n self.models.append(model)\n print(f\"Fold {i} val rmsle: {val_metric}\")\n self.cv_metrics.append(val_metric)\n\n def val_info(self):\n print(self.cv_metrics)\n print(\"Mean: \", np.mean(self.cv_metrics))\n print(\"Std: \", np.std(self.cv_metrics))\n return np.mean(self.cv_metrics)\n\n def create_test_submission(self, file):\n sub = self.test[[\"id\"]]\n X_test = self.test.drop(['id'], axis=1)\n test_preds = []\n for idx, model in enumerate(self.models):\n X_test = self.fold_preprocessors[idx].transform(X_test)\n test_pred = model.predict(X_test)\n test_preds.append(np.exp(test_pred) - 1)\n prediction = np.mean(test_preds, axis=0)\n sub[\"salary\"] = prediction\n sub.to_csv(file, index=False)\n" ]
[ [ "numpy.random.seed", "sklearn.model_selection.StratifiedKFold", "numpy.std", "numpy.mean", "numpy.exp" ] ]
ArsamAryandoust/BEVPO
[ "7763e28c1fa895c6689f394b7d99f9fd878cd5b2", "7763e28c1fa895c6689f394b7d99f9fd878cd5b2" ]
[ "src/bevpo/datasets/prep_ubermovement.py", "src/bevpo/save_results.py" ]
[ "import pandas as pd\nimport numpy as np\nimport math\n\ndef create_city_zone_coordinates(path_to_json_data):\n\n \"\"\" Calls the functions import_geojson and calc_centroids to get\n a list of city cone coordinates and created a pandas DataFrame in the \n required format, i.e. wiht columns zone_lat and zone_long, as well as\n zone_id as index column\n \"\"\"\n\n # map Uber Movement zone IDs to lists of lats and longs\n (\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates\n ) = import_geojson(path_to_json_data)\n\n # calculate centroids of city zone polygons\n (\n map_movement_id_to_centroid_lat,\n map_movement_id_to_centroid_long\n ) = calc_centroids(\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates\n )\n\n # create a pandas Dataframe in required format for bevpo\n city_zone_coordinates = pd.DataFrame(\n list(map_movement_id_to_centroid_lat.items()), \n columns = ['zone_id','zone_lat']\n )\n \n city_zone_coordinates['zone_long'] = (\n map_movement_id_to_centroid_long.values()\n )\n \n # set the zone_id column as index\n city_zone_coordinates.set_index('zone_id', inplace=True)\n\n return city_zone_coordinates\n\n\ndef import_geojson(path_to_json_data):\n\n \"\"\" Imports the geojson data from the passed path and maps Uber Movement\n city zone IDs to a flattened list of latitude and longitude coordinates\n in the format of two dictionaries. Uses the recursive function called\n foster_coordinates_recursive to flatten the differently nested data.\n \"\"\"\n \n data = pd.read_json(path_to_json_data)\n data.pop('type')\n data = data['features']\n \n map_json_entry_to_movement_id = dict()\n\n for json_id, json_entry in enumerate(data):\n \n map_json_entry_to_movement_id[json_id] = int(\n json_entry['properties']['MOVEMENT_ID']\n )\n \n map_movement_id_to_latitude_coordinates = dict()\n map_movement_id_to_longitude_coordinates = dict()\n\n for k, v in map_json_entry_to_movement_id.items():\n map_movement_id_to_latitude_coordinates[v] = []\n map_movement_id_to_longitude_coordinates[v] = []\n\n\n for json_id, movement_id in map_json_entry_to_movement_id.items():\n coordinates = data[json_id]['geometry']['coordinates']\n \n (\n map_movement_id_to_latitude_coordinates, \n map_movement_id_to_longitude_coordinates\n ) = foster_coordinates_recursive(\n movement_id,\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates,\n coordinates\n )\n \n \n map_movement_id_to_coordinates = (\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates\n )\n\n return map_movement_id_to_coordinates\n\n\ndef foster_coordinates_recursive(\n movement_id,\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates,\n coordinates\n):\n\n \"\"\" Flattens the coordinates of a passed city zone id (movement_id)\n and coordiates list recursively and saves their numeric values\n in the dictionaries that map movement ids to a list of latitude and \n longitude coordinates.\n \"\"\"\n\n dummy = 0\n\n for j in coordinates:\n\n if type(j) != list and dummy == 0:\n\n map_movement_id_to_longitude_coordinates[movement_id].append(j)\n dummy = 1\n continue\n\n elif type(j) != list and dummy == 1:\n\n map_movement_id_to_latitude_coordinates[movement_id].append(j)\n break\n\n else:\n\n dummy = 0\n coordinates = j\n (\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates\n ) = foster_coordinates_recursive(\n movement_id,\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates,\n coordinates\n )\n\n map_movement_id_to_coordinates = (\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates\n )\n\n return map_movement_id_to_coordinates\n\n\ndef calc_centroids(\n map_movement_id_to_latitude_coordinates,\n map_movement_id_to_longitude_coordinates\n):\n\n \"\"\" Calculates the centroid of passed city zone polygons. Should a city\n zone consist of unregularities or multiple polygons, this is identified\n by centroid coordinates that are not within the bound of minimum and \n maximum values of all coordinates of that city zone. In this case, the\n centroids are replaced with the mean of lat and long coordinates.\n \"\"\"\n \n # create empty dictionary for mapping Uber Movement IDs to city zone areas\n map_movement_id_to_cityzone_area = dict()\n\n # iterate over all movement IDs and latitude coordinates\n for movement_id, lat_coordinates in map_movement_id_to_latitude_coordinates.items():\n \n # get also the longitude coordinates\n long_coordinates = map_movement_id_to_longitude_coordinates[movement_id]\n \n # calculate currently iterated city zone area\n area_cityzone = 0\n for i in range(len(lat_coordinates)-1):\n\n area_cityzone = (\n area_cityzone\n + long_coordinates[i] * lat_coordinates[i+1]\n - long_coordinates[i+1] * lat_coordinates[i]\n )\n \n area_cityzone = (\n area_cityzone\n + long_coordinates[i+1] * lat_coordinates[0]\n - long_coordinates[0] * lat_coordinates[i+1]\n )\n \n area_cityzone *= 0.5\n #area_cityzone = abs(area_cityzone)\n \n map_movement_id_to_cityzone_area[movement_id] = area_cityzone\n \n # create empty dictionaries for mapping Uber Movement IDs to city zone centroids\n map_movement_id_to_centroid_lat = dict()\n map_movement_id_to_centroid_long = dict()\n \n # iterate over all movement IDs and latitude coordinates\n for movement_id, lat_coordinates in map_movement_id_to_latitude_coordinates.items():\n \n # get also the longitude coordinates\n long_coordinates = map_movement_id_to_longitude_coordinates[movement_id]\n \n \n # calculate currently iterated city zone area\n centroid_lat = 0\n centroid_long = 0\n for i in range(len(lat_coordinates)-1):\n \n centroid_long += (\n long_coordinates[i]\n + long_coordinates[i+1]\n ) * (\n long_coordinates[i] * lat_coordinates[i+1]\n - long_coordinates[i+1] * lat_coordinates[i]\n )\n\n centroid_lat += (\n lat_coordinates[i]\n + lat_coordinates[i+1]\n ) * (\n long_coordinates[i] * lat_coordinates[i+1]\n - long_coordinates[i+1] * lat_coordinates[i]\n )\n\n centroid_long += (\n long_coordinates[i+1]\n + long_coordinates[0]\n ) * (\n long_coordinates[i+1] * lat_coordinates[0]\n - long_coordinates[0] * lat_coordinates[i+1]\n )\n \n centroid_lat += (\n lat_coordinates[i+1]\n + lat_coordinates[0]\n ) * (\n long_coordinates[i+1] * lat_coordinates[0]\n - long_coordinates[0] * lat_coordinates[i+1]\n )\n \n\n centroid_lat /= (\n 6 * map_movement_id_to_cityzone_area[movement_id]\n )\n centroid_long /= (\n 6 * map_movement_id_to_cityzone_area[movement_id]\n )\n \n # Uber Movement city zones sometimes consist of multiple distinct polygons\n if (\n centroid_lat < min(lat_coordinates)\n or centroid_lat > max(lat_coordinates)\n or centroid_long < min(long_coordinates)\n or centroid_long > max(long_coordinates)\n ):\n # in this case we calculate the mean instead of centroid\n centroid_lat = np.mean(lat_coordinates)\n centroid_long = np.mean(long_coordinates) \n \n map_movement_id_to_centroid_lat[movement_id] = centroid_lat\n map_movement_id_to_centroid_long[movement_id] = centroid_long\n \n map_movement_id_to_centroid_coordinates = (\n map_movement_id_to_centroid_lat,\n map_movement_id_to_centroid_long\n )\n \n return map_movement_id_to_centroid_coordinates\n \n\ndef create_od_matrix_lists(path_to_rawdata):\n\n \"\"\" imports the raw Uber Movement travel time data and creates tw0 lists of\n origin destination (OD) matrices. A first list contains the mean travel time\n and a distinct second list contains the standard deviation of travel time. \n Each matrix and therefore each list element corresponds to a single time \n step. \n \"\"\"\n \n rename_dict_mean = {\n 'sourceid': 'source_id',\n 'dstid': 'dest_id'\n }\n \n rename_dict_stddev = {\n 'sourceid': 'source_id',\n 'dstid': 'dest_id',\n 'standard_deviation_travel_time': 'stddev_travel_time'\n }\n \n travel_data = pd.read_csv(path_to_rawdata)\n od_mean_travel_time_list = []\n od_std_travel_time_list = []\n\n T = 24\n for t in range(T):\n hod_travel_data = travel_data.loc[travel_data['hod'] == t]\n od_mean_travel_time_list.append(\n hod_travel_data[\n ['sourceid', 'dstid','mean_travel_time']\n ].rename(columns=rename_dict_mean)\n )\n od_std_travel_time_list.append(\n hod_travel_data[\n ['sourceid', 'dstid','standard_deviation_travel_time']\n ].rename(columns=rename_dict_stddev)\n )\n \n \n od_travel_time_lists = (\n od_mean_travel_time_list,\n od_std_travel_time_list\n )\n \n return od_travel_time_lists\n", "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport imageio\nimport os\nfrom mpl_toolkits import mplot3d\n\ndef save_results(tfs):\n\n \"\"\" Creates results folders, csv and plots and saves these in the respective\n folders.\n \"\"\"\n \n create_resultsfolder(tfs)\n save_as_csv(tfs)\n save_as_plots(tfs)\n \n save_maps('parking', tfs, tfs.parking_map, 150000, 'parking_map.gif')\n save_maps('driving', tfs, tfs.driving_map, 150000, 'driving_map.gif')\n if tfs.charging_profile is not None:\n save_maps('charging', tfs, tfs.charging_map, 150000, 'charging_map.gif')\n\n\ndef create_resultsfolder(tfs):\n\n \"\"\" Creates a folder called bevpo_results on the tfs.path_to_results for\n saving both the plots and numeric values of the traffic simulation outcome.\n \"\"\"\n\n if tfs.path_to_results.endswith('/'):\n tfs.path_to_bevpo_results = tfs.path_to_results\n else:\n tfs.path_to_bevpo_results = tfs.path_to_results + '/'\n\n tfs.path_to_csv = tfs.path_to_bevpo_results + 'numeric/'\n tfs.path_to_figures = tfs.path_to_bevpo_results + 'figures/'\n tfs.path_to_images = tfs.path_to_bevpo_results + 'images/'\n tfs.path_to_png = tfs.path_to_images + 'png/'\n tfs.path_to_pdf = tfs.path_to_images + 'pdf/'\n \n # create required folders for saving results if not existent yet\n if not os.path.isdir(tfs.path_to_bevpo_results):\n os.makedirs(tfs.path_to_bevpo_results)\n if not os.path.isdir(tfs.path_to_csv):\n os.mkdir(tfs.path_to_csv)\n if not os.path.isdir(tfs.path_to_figures):\n os.mkdir(tfs.path_to_figures)\n if not os.path.isdir(tfs.path_to_images):\n os.mkdir(tfs.path_to_images)\n if not os.path.isdir(tfs.path_to_png):\n os.mkdir(tfs.path_to_png)\n if not os.path.isdir(tfs.path_to_pdf):\n os.mkdir(tfs.path_to_pdf)\n \n \ndef save_as_csv(tfs):\n\n \"\"\" Saves the numeric results to csv files.\"\"\"\n \n ### Save driving and parking maps\n df_columns = []\n for t in range(tfs.T):\n column = 't={}'.format(t)\n df_columns.append(column)\n \n saving_path = tfs.path_to_csv + 'driving_map.csv'\n df = pd.DataFrame(\n tfs.driving_map, \n index=tfs.city_zone_coordinates.index.values,\n columns=df_columns\n )\n df.to_csv(\n saving_path,\n index_label='zone_id'\n )\n \n saving_path = tfs.path_to_csv + 'parking_map.csv'\n df = pd.DataFrame(\n tfs.parking_map,\n index=tfs.city_zone_coordinates.index.values,\n columns=df_columns\n )\n df.to_csv(\n saving_path,\n index_label='zone_id'\n )\n \n ### Save charging maps for electric vehicles\n if tfs.charging_profile is not None:\n saving_path = tfs.path_to_csv + 'charging_map.csv'\n df = pd.DataFrame(\n tfs.charging_map,\n index=tfs.city_zone_coordinates.index.values,\n columns=df_columns\n )\n df.to_csv(\n saving_path,\n index_label='zone_id'\n )\n \n ### Save traffic system properties\n saving_path = tfs.path_to_csv + 'traffic_properties.csv'\n \n df_index = []\n df_index.append('total')\n for t in range(tfs.T):\n index = 't={}'.format(t)\n df_index.append(index)\n \n df_columns=[\n 'avg driving time (min)',\n 'avg driving distance (km)',\n 'circadian rhythm (%)'\n ]\n \n avg_properties = np.column_stack(\n (\n tfs.avg_driving_times, \n tfs.avg_driving_distances,\n np.append(\n '',\n np.round(tfs.circadian_rhythm * 100).astype(int)\n )\n )\n )\n df = pd.DataFrame(\n avg_properties, \n columns=df_columns,\n index=df_index\n )\n df['driving share lifetime (%)'] = ''\n df['parking share lifetime (%)'] = ''\n \n df.iloc[0, 3] = tfs.driving_share_lifetime\n df.iloc[0, 4] = tfs.parking_share_lifetime\n \n df.to_csv(saving_path)\n \n ### Save travel distributions\n saving_path = tfs.path_to_csv + 'distance_distributions.csv'\n df_index = []\n df_index.append('total (%)')\n for t in range(tfs.T):\n index = 't={}'.format(t)\n df_index.append(index)\n \n df_columns = []\n for bin_value in tfs.distr_bins_km:\n column = '{} km'.format(round(bin_value))\n df_columns.append(column)\n \n distr_distances = np.row_stack(\n (\n tfs.distr_distances_total, \n tfs.distr_distances_per_t\n )\n )\n df = pd.DataFrame(\n distr_distances, \n columns=df_columns,\n index=df_index\n )\n df.to_csv(saving_path)\n \n saving_path = tfs.path_to_csv + 'duration_distributions.csv'\n df_index = []\n df_index.append('total (%)')\n for t in range(tfs.T):\n index = 't={}'.format(t)\n df_index.append(index)\n \n df_columns = []\n for bin_value in tfs.distr_bins_s:\n column = '{} s'.format(round(bin_value))\n df_columns.append(column)\n \n distr_durations = np.row_stack(\n (\n tfs.distr_durations_total, \n tfs.distr_durations_per_t\n )\n )\n df = pd.DataFrame(\n distr_durations, \n columns=df_columns,\n index=df_index\n )\n df.to_csv(saving_path)\n\n\ndef save_maps(\n title, \n tfs, \n tfs_map, \n scatter_factor, \n gif_filename,\n fig_size=13,\n font=16\n):\n\n \"\"\" Creates driving, parking and charging maps. \"\"\"\n # create folders for saving files first\n tfs.path_to_png_map = tfs.path_to_png + title + '/'\n tfs.path_to_pdf_map = tfs.path_to_pdf + title + '/'\n \n if not os.path.isdir(tfs.path_to_png_map):\n os.mkdir(tfs.path_to_png_map)\n if not os.path.isdir(tfs.path_to_pdf_map):\n os.mkdir(tfs.path_to_pdf_map) \n \n # save png and pdf images of the map first, and keep files in filename_list\n filename_list = []\n for t in range(tfs.T):\n\n plt.figure(\n figsize=(fig_size, fig_size)\n )\n\n plt.scatter(\n tfs.city_zone_coordinates['zone_long'].values,\n tfs.city_zone_coordinates['zone_lat'].values,\n tfs_map[:, t] * scatter_factor,\n alpha=0.7\n )\n plt.title(title + f'\\n t={t}')\n plt.xlabel('longitude')\n plt.ylabel('latitude')\n\n filename_png = f't={t}.png'\n filename_pdf = f't={t}.pdf'\n filename_list.append(filename_png)\n saving_path_png = tfs.path_to_png_map + filename_png\n saving_path_pdf = tfs.path_to_pdf_map + filename_pdf\n plt.savefig(saving_path_png)\n plt.savefig(saving_path_pdf)\n plt.close()\n\n # create a gif from map images\n path_to_gif = tfs.path_to_figures + gif_filename\n\n with imageio.get_writer(path_to_gif, mode='I', fps=3) as writer:\n for filename in filename_list:\n loading_path = tfs.path_to_png_map + filename\n image = imageio.imread(loading_path)\n writer.append_data(image)\n\n\ndef save_as_plots(\n tfs,\n fig_size=13,\n font=16,\n):\n\n \"\"\" Saves the resulting statistics to .png and .pdf plots.\"\"\" \n\n ### Save circadian rhythm\n \n saving_path_pdf = tfs.path_to_figures + 'circadian_rhythm.pdf'\n saving_path_png = tfs.path_to_figures + 'circadian_rhythm.png'\n fig = plt.figure(\n figsize=(fig_size, fig_size)\n )\n plt.plot(\n np.round(\n tfs.circadian_rhythm * 100\n ).astype(int)\n )\n plt.title(\n 'Circadian rhythm of traffic',\n fontsize=font\n )\n plt.xlabel(\n 'time',\n fontsize=font\n )\n plt.ylabel(\n 'traffic activity [%]',\n fontsize=font\n )\n plt.xticks(\n fontsize=font\n )\n plt.yticks(\n fontsize=font\n )\n fig.savefig(saving_path_pdf)\n fig.savefig(saving_path_png)\n plt.close(fig)\n \n ### Save provided charging profile\n if tfs.charging_profile is not None:\n saving_path_pdf = tfs.path_to_figures + 'charging_profile.pdf'\n saving_path_png = tfs.path_to_figures + 'charging_profile.png'\n fig = plt.figure(\n figsize=(fig_size, fig_size)\n )\n plt.plot(\n np.round(\n tfs.charging_profile_dist * 100\n ).astype(int)\n )\n plt.title(\n 'EV charging distribution over time',\n fontsize=font\n )\n plt.xlabel(\n 'time',\n fontsize=font\n )\n plt.ylabel(\n 'charging [%]',\n fontsize=font\n )\n plt.xticks(\n fontsize=font\n )\n plt.yticks(\n fontsize=font\n )\n fig.savefig(saving_path_pdf)\n fig.savefig(saving_path_png)\n plt.close(fig) \n \n \n ### Save travel distance distributions\n \n saving_path_pdf = tfs.path_to_figures + 'travel_distance.pdf'\n saving_path_png = tfs.path_to_figures + 'travel_distance.png'\n fig = plt.figure(\n figsize=(fig_size, fig_size)\n )\n plt.bar(\n range(len(tfs.distr_bins_km)),\n tfs.distr_distances_total\n )\n plt.xticks(\n range(len(tfs.distr_bins_km)),\n np.round(tfs.distr_bins_km).astype(int),\n fontsize=font\n )\n \n plt.title(\n 'Travelled distances per trip',\n fontsize=font\n )\n plt.xlabel(\n 'distance [km]',\n fontsize=font\n )\n plt.yticks(\n fontsize=font\n )\n plt.ylabel(\n 'trips [%]',\n fontsize=font\n )\n fig.savefig(saving_path_pdf)\n fig.savefig(saving_path_png)\n plt.close(fig)\n \n \n ### Save travel duration distributions\n \n saving_path_pdf = tfs.path_to_figures + 'travel_duration.pdf'\n saving_path_png = tfs.path_to_figures + 'travel_duration.png'\n fig = plt.figure(\n figsize=(fig_size, fig_size)\n )\n plt.bar(\n range(len(tfs.distr_bins_s)),\n tfs.distr_durations_total\n )\n plt.xticks(\n range(len(tfs.distr_bins_s)),\n np.round(tfs.distr_bins_s/60, 2),\n fontsize=font\n )\n plt.yticks(\n fontsize=font\n )\n plt.title(\n 'Travelled durations per trip',\n fontsize=font\n )\n plt.xlabel(\n 'duration [min]',\n fontsize=font\n )\n plt.ylabel(\n 'trips [%]',\n fontsize=font\n )\n fig.savefig(saving_path_pdf)\n fig.savefig(saving_path_png)\n plt.close(fig)\n \n \n saving_path_pdf = tfs.path_to_figures + 'travel_distance_per_t.pdf'\n saving_path_png = tfs.path_to_figures + 'travel_distance_per_t.png'\n fig = plt.figure(\n figsize=(fig_size, fig_size)\n )\n ax = plt.axes(projection='3d')\n ax.plot_surface(\n tfs.distr_bins_km,\n np.expand_dims(np.arange(tfs.T), 1),\n tfs.distr_distances_per_t,\n )\n ax.set_title(\n 'Travel distance distribution',\n fontsize=font\n )\n ax.set_xlabel(\n 'travel distance [km]',\n fontsize=font\n )\n ax.set_ylabel(\n 'time step (t)',\n fontsize=font\n )\n ax.set_zlabel(\n 'sampled cars',\n fontsize=font\n )\n fig.savefig(saving_path_png)\n fig.savefig(saving_path_pdf)\n plt.close(fig)\n \n saving_path_pdf = tfs.path_to_figures + 'travel_duration_per_t.pdf'\n saving_path_png = tfs.path_to_figures + 'travel_duration_per_t.png'\n fig = plt.figure(\n figsize=(fig_size, fig_size)\n )\n ax = plt.axes(projection='3d')\n ax.plot_surface(\n tfs.distr_bins_s,\n np.expand_dims(np.arange(tfs.T), 1),\n tfs.distr_durations_per_t,\n )\n ax.set_title(\n 'Travel duration distribution',\n fontsize=font\n )\n ax.set_xlabel(\n 'travel time [s]',\n fontsize=font\n )\n ax.set_ylabel(\n 'time step (t)',\n fontsize=font\n )\n ax.set_zlabel(\n 'sampled cars',\n fontsize=font\n )\n fig.savefig(saving_path_png)\n fig.savefig(saving_path_pdf)\n plt.close(fig)\n \n" ]
[ [ "pandas.read_csv", "numpy.mean", "pandas.read_json" ], [ "matplotlib.pyplot.yticks", "matplotlib.pyplot.title", "matplotlib.pyplot.scatter", "numpy.arange", "pandas.DataFrame", "matplotlib.pyplot.savefig", "matplotlib.pyplot.axes", "numpy.round", "matplotlib.pyplot.ylabel", "numpy.row_stack", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.figure" ] ]
Owen718/sea-thru
[ "4f5bb54f75b39bef7fdf9cb2e58b7676d5ae6402" ]
[ "seathru.py" ]
[ "import collections\nimport sys\nimport argparse\nimport numpy as np\nimport sklearn as sk\nimport scipy as sp\nimport scipy.optimize\nimport scipy.stats\nimport math\nfrom PIL import Image\nimport rawpy\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom skimage import exposure\nfrom skimage.restoration import denoise_bilateral, denoise_tv_chambolle, estimate_sigma\nfrom skimage.morphology import closing, opening, erosion, dilation, disk, diamond, square\n\nmatplotlib.use('TkAgg')\n\n'''\nFinds points for which to estimate backscatter\nby partitioning the image into different depth\nranges and taking the darkest RGB triplets \nfrom that set as estimations of the backscatter\n'''\ndef find_backscatter_estimation_points(img, depths, num_bins=10, fraction=0.01, max_vals=20, min_depth_percent=0.0):\n z_max, z_min = np.max(depths), np.min(depths)\n min_depth = z_min + (min_depth_percent * (z_max - z_min))\n z_ranges = np.linspace(z_min, z_max, num_bins + 1)\n img_norms = np.mean(img, axis=2)\n points_r = []\n points_g = []\n points_b = []\n for i in range(len(z_ranges) - 1):\n a, b = z_ranges[i], z_ranges[i+1]\n locs = np.where(np.logical_and(depths > min_depth, np.logical_and(depths >= a, depths <= b)))\n norms_in_range, px_in_range, depths_in_range = img_norms[locs], img[locs], depths[locs]\n arr = sorted(zip(norms_in_range, px_in_range, depths_in_range), key=lambda x: x[0])\n points = arr[:min(math.ceil(fraction * len(arr)), max_vals)]\n points_r.extend([(z, p[0]) for n, p, z in points])\n points_g.extend([(z, p[1]) for n, p, z in points])\n points_b.extend([(z, p[2]) for n, p, z in points])\n return np.array(points_r), np.array(points_g), np.array(points_b)\n\n'''\nEstimates coefficients for the backscatter curve\nbased on the backscatter point values and their depths\n'''\ndef find_backscatter_values(B_pts, depths, restarts=10, max_mean_loss_fraction=0.1):\n B_vals, B_depths = B_pts[:, 1], B_pts[:, 0]\n z_max, z_min = np.max(depths), np.min(depths)\n max_mean_loss = max_mean_loss_fraction * (z_max - z_min)\n coefs = None\n best_loss = np.inf\n def estimate(depths, B_inf, beta_B, J_prime, beta_D_prime):\n val = (B_inf * (1 - np.exp(-1 * beta_B * depths))) + (J_prime * np.exp(-1 * beta_D_prime * depths))\n return val\n def loss(B_inf, beta_B, J_prime, beta_D_prime):\n val = np.mean(np.abs(B_vals - estimate(B_depths, B_inf, beta_B, J_prime, beta_D_prime)))\n return val\n bounds_lower = [0,0,0,0]\n bounds_upper = [1,5,1,5]\n for _ in range(restarts):\n try:\n optp, pcov = sp.optimize.curve_fit(\n f=estimate,\n xdata=B_depths,\n ydata=B_vals,\n p0=np.random.random(4) * bounds_upper,\n bounds=(bounds_lower, bounds_upper),\n )\n l = loss(*optp)\n if l < best_loss:\n best_loss = l\n coefs = optp\n except RuntimeError as re:\n print(re, file=sys.stderr)\n if best_loss > max_mean_loss:\n print('Warning: could not find accurate reconstruction. Switching to linear model.', flush=True)\n slope, intercept, r_value, p_value, std_err = sp.stats.linregress(B_depths, B_vals)\n BD = (slope * depths) + intercept\n return BD, np.array([slope, intercept])\n return estimate(depths, *coefs), coefs\n\n'''\nEstimate illumination map from local color space averaging\n'''\ndef estimate_illumination(img, B, neighborhood_map, num_neighborhoods, p=0.5, f=2.0, max_iters=100, tol=1E-5):\n D = img - B\n avg_cs = np.zeros_like(img)\n avg_cs_prime = np.copy(avg_cs)\n sizes = np.zeros(num_neighborhoods)\n locs_list = [None] * num_neighborhoods\n for label in range(1, num_neighborhoods + 1):\n locs_list[label - 1] = np.where(neighborhood_map == label)\n sizes[label - 1] = np.size(locs_list[label - 1][0])\n for _ in range(max_iters):\n for label in range(1, num_neighborhoods + 1):\n locs = locs_list[label - 1]\n size = sizes[label - 1] - 1\n avg_cs_prime[locs] = (1 / size) * (np.sum(avg_cs[locs]) - avg_cs[locs])\n new_avg_cs = (D * p) + (avg_cs_prime * (1 - p))\n if(np.max(np.abs(avg_cs - new_avg_cs)) < tol):\n break\n avg_cs = new_avg_cs\n return f * denoise_bilateral(np.maximum(0, avg_cs))\n\n'''\nEstimate values for beta_D\n'''\ndef estimate_wideband_attentuation(depths, illum, radius = 6, max_val = 10.0):\n eps = 1E-8\n BD = np.minimum(max_val, -np.log(illum + eps) / (np.maximum(0, depths) + eps))\n mask = np.where(np.logical_and(depths > eps, illum > eps), 1, 0)\n refined_attenuations = denoise_bilateral(closing(np.maximum(0, BD * mask), disk(radius)))\n return refined_attenuations, []\n\n'''\nCalculate the values of beta_D for an image from the depths, illuminations, and constants\n'''\ndef calculate_beta_D(depths, a, b, c, d):\n return (a * np.exp(b * depths)) + (c * np.exp(d * depths))\n\n'''\nFilter the data such that only one point is selected per \"bin\", defined using a radius.\nThe median value is selected per bin.\nThis prevents the regression from being overwhelmed due to the\nlarge amount of junk data at certain points in the range.\n'''\ndef filter_data(X, Y, radius_fraction=0.01):\n idxs = np.argsort(X)\n X_s = X[idxs]\n Y_s = Y[idxs]\n x_max, x_min = np.max(X), np.min(X)\n radius = (radius_fraction * (x_max - x_min))\n ds = np.cumsum(X_s - np.roll(X_s, (1,)))\n dX = [X_s[0]]\n dY = [Y_s[0]]\n tempX = []\n tempY = []\n pos = 0\n for i in range(1, ds.shape[0]):\n if ds[i] - ds[pos] >= radius:\n tempX.append(X_s[i])\n tempY.append(Y_s[i])\n idxs = np.argsort(tempY)\n med_idx = len(idxs) // 2\n dX.append(tempX[med_idx])\n dY.append(tempY[med_idx])\n pos = i\n else:\n tempX.append(X_s[i])\n tempY.append(Y_s[i])\n return np.array(dX), np.array(dY)\n\n'''\nEstimate coefficients for the 2-term exponential\ndescribing the wideband attenuation\n'''\ndef refine_wideband_attentuation(depths, illum, estimation, restarts=10, min_depth_fraction = 0.1, max_mean_loss_fraction=np.inf, l=1.0, radius_fraction=0.01):\n eps = 1E-8\n z_max, z_min = np.max(depths), np.min(depths)\n min_depth = z_min + (min_depth_fraction * (z_max - z_min))\n max_mean_loss = max_mean_loss_fraction * (z_max - z_min)\n coefs = None\n best_loss = np.inf\n locs = np.where(np.logical_and(illum > 0, np.logical_and(depths > min_depth, estimation > eps)))\n def calculate_reconstructed_depths(depths, illum, a, b, c, d):\n eps = 1E-5\n res = -np.log(illum + eps) / (calculate_beta_D(depths, a, b, c, d) + eps)\n return res\n def loss(a, b, c, d):\n return np.mean(np.abs(depths[locs] - calculate_reconstructed_depths(depths[locs], illum[locs], a, b, c, d)))\n dX, dY = filter_data(depths[locs], estimation[locs], radius_fraction)\n for _ in range(restarts):\n try:\n optp, pcov = sp.optimize.curve_fit(\n f=calculate_beta_D,\n xdata=dX,\n ydata=dY,\n p0=np.abs(np.random.random(4)) * np.array([1., -1., 1., -1.]),\n bounds=([0, -100, 0, -100], [100, 0, 100, 0]))\n L = loss(*optp)\n if L < best_loss:\n best_loss = L\n coefs = optp\n except RuntimeError as re:\n print(re, file=sys.stderr)\n # Uncomment to see the regression\n # plt.clf()\n # plt.scatter(depths[locs], estimation[locs])\n # plt.plot(np.sort(depths[locs]), calculate_beta_D(np.sort(depths[locs]), *coefs))\n # plt.show()\n if best_loss > max_mean_loss:\n print('Warning: could not find accurate reconstruction. Switching to linear model.', flush=True)\n slope, intercept, r_value, p_value, std_err = sp.stats.linregress(depths[locs], estimation[locs])\n BD = (slope * depths + intercept)\n return l * BD, np.array([slope, intercept])\n print(f'Found best loss {best_loss}', flush=True)\n BD = l * calculate_beta_D(depths, *coefs)\n return BD, coefs\n\n'''\nReconstruct the scene and globally white balance\nbased the Gray World Hypothesis\n'''\ndef recover_image(img, depths, B, beta_D, nmap):\n res = (img - B) * np.exp(beta_D * np.expand_dims(depths, axis=2))\n res = np.maximum(0.0, np.minimum(1.0, res))\n res[nmap == 0] = 0\n res = scale(wbalance_gw(res))\n res[nmap == 0] = img[nmap == 0]\n return res\n\n\n'''\nReconstruct the scene and globally white balance\n'''\ndef recover_image_S4(img, B, illum, nmap):\n eps = 1E-8\n res = (img - B) / (illum + eps)\n res = np.maximum(0.0, np.minimum(1.0, res))\n res[nmap == 0] = img[nmap == 0]\n return scale(wbalance_no_red_gw(res))\n\n\n'''\nConstructs a neighborhood map from depths and \nepsilon\n'''\ndef construct_neighborhood_map(depths, epsilon=0.05):\n eps = (np.max(depths) - np.min(depths)) * epsilon\n nmap = np.zeros_like(depths).astype(np.int32)\n n_neighborhoods = 1\n while np.any(nmap == 0):\n locs_x, locs_y = np.where(nmap == 0)\n start_index = np.random.randint(0, len(locs_x))\n start_x, start_y = locs_x[start_index], locs_y[start_index]\n q = collections.deque()\n q.append((start_x, start_y))\n while not len(q) == 0:\n x, y = q.pop()\n if np.abs(depths[x, y] - depths[start_x, start_y]) <= eps:\n nmap[x, y] = n_neighborhoods\n if 0 <= x < depths.shape[0] - 1:\n x2, y2 = x + 1, y\n if nmap[x2, y2] == 0:\n q.append((x2, y2))\n if 1 <= x < depths.shape[0]:\n x2, y2 = x - 1, y\n if nmap[x2, y2] == 0:\n q.append((x2, y2))\n if 0 <= y < depths.shape[1] - 1:\n x2, y2 = x, y + 1\n if nmap[x2, y2] == 0:\n q.append((x2, y2))\n if 1 <= y < depths.shape[1]:\n x2, y2 = x, y - 1\n if nmap[x2, y2] == 0:\n q.append((x2, y2))\n n_neighborhoods += 1\n zeros_size_arr = sorted(zip(*np.unique(nmap[depths == 0], return_counts=True)), key=lambda x: x[1], reverse=True)\n if len(zeros_size_arr) > 0:\n nmap[nmap == zeros_size_arr[0][0]] = 0 #reset largest background to 0\n return nmap, n_neighborhoods - 1\n\n'''\nFinds the closest nonzero label to a location\n'''\ndef find_closest_label(nmap, start_x, start_y):\n mask = np.zeros_like(nmap).astype(np.bool)\n q = collections.deque()\n q.append((start_x, start_y))\n while not len(q) == 0:\n x, y = q.pop()\n if 0 <= x < nmap.shape[0] and 0 <= y < nmap.shape[1]:\n if nmap[x, y] != 0:\n return nmap[x, y]\n mask[x, y] = True\n if 0 <= x < nmap.shape[0] - 1:\n x2, y2 = x + 1, y\n if not mask[x2, y2]:\n q.append((x2, y2))\n if 1 <= x < nmap.shape[0]:\n x2, y2 = x - 1, y\n if not mask[x2, y2]:\n q.append((x2, y2))\n if 0 <= y < nmap.shape[1] - 1:\n x2, y2 = x, y + 1\n if not mask[x2, y2]:\n q.append((x2, y2))\n if 1 <= y < nmap.shape[1]:\n x2, y2 = x, y - 1\n if not mask[x2, y2]:\n q.append((x2, y2))\n\n\n'''\nRefines the neighborhood map to remove artifacts\n'''\ndef refine_neighborhood_map(nmap, min_size = 10, radius = 3):\n refined_nmap = np.zeros_like(nmap)\n vals, counts = np.unique(nmap, return_counts=True)\n neighborhood_sizes = sorted(zip(vals, counts), key=lambda x: x[1], reverse=True)\n num_labels = 1\n for label, size in neighborhood_sizes:\n if size >= min_size and label != 0:\n refined_nmap[nmap == label] = num_labels\n num_labels += 1\n for label, size in neighborhood_sizes:\n if size < min_size and label != 0:\n for x, y in zip(*np.where(nmap == label)):\n refined_nmap[x, y] = find_closest_label(refined_nmap, x, y)\n refined_nmap = closing(refined_nmap, square(radius))\n return refined_nmap, num_labels - 1\n\n\ndef load_image_and_depth_map(img_fname, depths_fname, size_limit = 1024):\n depths = Image.open(depths_fname)\n try:\n img = Image.fromarray(rawpy.imread(img_fname).postprocess())\n except rawpy.LibRawFileUnsupportedError:\n img = Image.open(img_fname)\n img.thumbnail((size_limit, size_limit), Image.ANTIALIAS)\n depths = depths.resize(img.size, Image.ANTIALIAS)\n return np.float32(img) / 255.0, np.array(depths)\n\n'''\nWhite balance with 'grey world' hypothesis\n'''\ndef wbalance_gw(img):\n r = img[:,:,0]\n g = img[:,:,1]\n b = img[:,:,2]\n dr = 1.0 / np.mean(r[r != 0])\n dg = 1.0 / np.mean(g[g != 0])\n db = 1.0 / np.mean(b[b != 0])\n dsum = dr + dg + db\n dr = dr / dsum * 3.\n dg = dg / dsum * 3.\n db = db / dsum * 3.\n\n img[:, :, 0] *= dr\n img[:, :, 1] *= dg\n img[:, :, 2] *= db\n return img\n\n\n'''\nWhite balance based on top 10% average values of each channel\n'''\ndef wbalance_10p(img):\n dr = 1.0 / np.mean(np.sort(img[:, :, 0], axis=None)[int(round(-1 * np.size(img[:, :, 0]) * 0.1)):])\n dg = 1.0 / np.mean(np.sort(img[:, :, 1], axis=None)[int(round(-1 * np.size(img[:, :, 0]) * 0.1)):])\n db = 1.0 / np.mean(np.sort(img[:, :, 2], axis=None)[int(round(-1 * np.size(img[:, :, 0]) * 0.1)):])\n dsum = dr + dg + db\n dr = dr / dsum * 3.\n dg = dg / dsum * 3.\n db = db / dsum * 3.\n\n img[:, :, 0] *= dr\n img[:, :, 1] *= dg\n img[:, :, 2] *= db\n return img\n\n'''\nWhite balance based on top 10% average values of blue and green channel\n'''\ndef wbalance_no_red_10p(img):\n dg = 1.0 / np.mean(np.sort(img[:, :, 1], axis=None)[int(round(-1 * np.size(img[:, :, 0]) * 0.1)):])\n db = 1.0 / np.mean(np.sort(img[:, :, 2], axis=None)[int(round(-1 * np.size(img[:, :, 0]) * 0.1)):])\n dsum = dg + db\n dg = dg / dsum * 2.\n db = db / dsum * 2.\n img[:, :, 0] *= (db + dg) / 2\n img[:, :, 1] *= dg\n img[:, :, 2] *= db\n return img\n\n'''\nWhite balance with 'grey world' hypothesis\n'''\ndef wbalance_no_red_gw(img):\n r = img[:,:,0]\n g = img[:,:,1]\n b = img[:,:,2]\n dr = 1.0 / np.mean(r[r != 0])\n dg = 1.0 / np.mean(g[g != 0])\n db = 1.0 / np.mean(b[b != 0])\n dsum = dg + db\n dg = dg / dsum * 2.\n db = db / dsum * 2.\n\n img[:, :, 0] *= (db + dg) / 2\n img[:, :, 1] *= dg\n img[:, :, 2] *= db\n return img\n\ndef scale(img):\n return (img - np.min(img)) / (np.max(img) - np.min(img))\n\ndef run_pipeline(img, depths, args):\n if 'output_graphs' not in args:\n args.output_graphs = False\n if args.output_graphs:\n plt.imshow(depths)\n plt.title('Depth Map')\n plt.show()\n\n print('Estimating backscatter...', flush=True)\n ptsR, ptsG, ptsB = find_backscatter_estimation_points(img, depths, fraction=0.01, min_depth_percent=args.min_depth)\n\n print('Finding backscatter coefficients...', flush=True)\n Br, coefsR = find_backscatter_values(ptsR, depths, restarts=25)\n Bg, coefsG = find_backscatter_values(ptsG, depths, restarts=25)\n Bb, coefsB = find_backscatter_values(ptsB, depths, restarts=25)\n\n if args.output_graphs:\n print('Coefficients: \\n{}\\n{}\\n{}'.format(coefsR, coefsG, coefsB), flush=True)\n def eval_xs(xs, coefs):\n if len(coefs) == 2:\n return xs * coefs[0] + coefs[1]\n else:\n return ((coefs[0] * (1 - np.exp(-coefs[1] * xs))) + (coefs[2] * np.exp(-coefs[3] * xs)))\n # check optimization for B channel\n plt.clf()\n plt.scatter(ptsB[:, 0].ravel(), ptsB[:, 1].ravel(), c='b')\n xs = np.linspace(np.min(ptsB[:, 0]), np.max(ptsB[:, 0]), 1000)\n ys = eval_xs(xs, coefsB)\n # ys = find_backscatter_values(ptsB, xs)\n plt.plot(xs.ravel(), ys.ravel(), c='b')\n plt.scatter(ptsG[:, 0].ravel(), ptsG[:, 1].ravel(), c='g')\n xs = np.linspace(np.min(ptsG[:, 0]), np.max(ptsG[:, 0]), 1000)\n ys = eval_xs(xs, coefsG)\n # ys = find_backscatter_values(ptsG, xs)\n plt.plot(xs.ravel(), ys.ravel(), c='g')\n plt.scatter(ptsR[:, 0].ravel(), ptsR[:, 1].ravel(), c='r')\n xs = np.linspace(np.min(ptsR[:, 0]), np.max(ptsR[:, 0]), 1000)\n ys = eval_xs(xs, coefsR)\n # ys = find_backscatter_values(ptsR, xs)\n plt.plot(xs.ravel(), ys.ravel(), c='r')\n plt.xlabel('Depth (m)')\n plt.ylabel('Color value')\n plt.title('Modelled $B_c$ values')\n plt.savefig('Bc_values.png')\n plt.show()\n\n print('Constructing neighborhood map...', flush=True)\n nmap, _ = construct_neighborhood_map(depths, 0.1)\n\n print('Refining neighborhood map...', flush=True)\n nmap, n = refine_neighborhood_map(nmap, 50)\n if args.output_graphs:\n plt.imshow(nmap)\n plt.title('Neighborhood map')\n plt.show()\n\n print('Estimating illumination...', flush=True)\n illR = estimate_illumination(img[:, :, 0], Br, nmap, n, p=args.p, max_iters=100, tol=1E-5, f=args.f)\n illG = estimate_illumination(img[:, :, 1], Bg, nmap, n, p=args.p, max_iters=100, tol=1E-5, f=args.f)\n illB = estimate_illumination(img[:, :, 2], Bb, nmap, n, p=args.p, max_iters=100, tol=1E-5, f=args.f)\n ill = np.stack([illR, illG, illB], axis=2)\n if args.output_graphs:\n plt.imshow(ill)\n plt.title('Illuminant map')\n plt.show()\n\n print('Estimating wideband attenuation...', flush=True)\n beta_D_r, _ = estimate_wideband_attentuation(depths, illR)\n refined_beta_D_r, coefsR = refine_wideband_attentuation(depths, illR, beta_D_r, radius_fraction=args.spread_data_fraction, l=args.l)\n beta_D_g, _ = estimate_wideband_attentuation(depths, illG)\n refined_beta_D_g, coefsG = refine_wideband_attentuation(depths, illG, beta_D_g, radius_fraction=args.spread_data_fraction, l=args.l)\n beta_D_b, _ = estimate_wideband_attentuation(depths, illB)\n refined_beta_D_b, coefsB = refine_wideband_attentuation(depths, illB, beta_D_b, radius_fraction=args.spread_data_fraction, l=args.l)\n\n if args.output_graphs:\n print('Coefficients: \\n{}\\n{}\\n{}'.format(coefsR, coefsG, coefsB), flush=True)\n # plot the wideband attenuation values\n plt.clf()\n plt.imshow(np.stack([scale(refined_beta_D_r), np.zeros_like(beta_D_r), np.zeros_like(beta_D_r)], axis=2))\n plt.show()\n plt.clf()\n plt.imshow(np.stack([np.zeros_like(beta_D_r), scale(refined_beta_D_g), np.zeros_like(beta_D_r)], axis=2))\n plt.show()\n plt.clf()\n plt.imshow(np.stack([np.zeros_like(beta_D_r), np.zeros_like(beta_D_r), scale(refined_beta_D_b)], axis=2))\n plt.show()\n\n # check optimization for beta_D channel\n if args.output_graphs:\n eps = 1E-5\n def eval_xs(xs, coefs):\n if len(coefs) == 2:\n return xs * coefs[0] + coefs[1]\n else:\n return (coefs[0] * np.exp(coefs[1] * xs)) + (coefs[2] * np.exp(coefs[3] * xs))\n locs = np.where(\n np.logical_and(beta_D_r > eps, np.logical_and(beta_D_g > eps, np.logical_and(depths > eps, beta_D_b > eps))))\n plt.scatter(depths[locs].ravel(), beta_D_b[locs].ravel(), c='b', alpha=0.1, edgecolors='none')\n xs = np.linspace(np.min(depths[locs]), np.max(depths[locs]), 1000)\n ys = eval_xs(xs, coefsB)\n plt.plot(xs.ravel(), ys.ravel(), c='b')\n plt.scatter(depths[locs].ravel(), beta_D_g[locs].ravel(), c='g', alpha=0.1, edgecolors='none')\n ys = eval_xs(xs, coefsG)\n plt.plot(xs.ravel(), ys.ravel(), c='g')\n plt.scatter(depths[locs].ravel(), beta_D_r[locs].ravel(), c='r', alpha=0.1, edgecolors='none')\n ys = eval_xs(xs, coefsR)\n plt.plot(xs.ravel(), ys.ravel(), c='r')\n plt.xlabel('Depth (m)')\n plt.ylabel('$\\\\beta^D$')\n plt.title('Modelled $\\\\beta^D$ values')\n plt.savefig('betaD_values.png')\n plt.show()\n\n print('Reconstructing image...', flush=True)\n B = np.stack([Br, Bg, Bb], axis=2)\n beta_D = np.stack([refined_beta_D_r, refined_beta_D_g, refined_beta_D_b], axis=2)\n recovered = recover_image(img, depths, B, beta_D, nmap)\n\n\n if args.output_graphs:\n beta_D = (beta_D - np.min(beta_D)) / (np.max(beta_D) - np.min(beta_D))\n fig = plt.figure(figsize=(50, 20))\n fig.add_subplot(2, 3, 1)\n plt.imshow(img)\n plt.title('Original Image')\n fig.add_subplot(2, 3, 2)\n plt.imshow(nmap)\n plt.title('Neighborhood Map')\n fig.add_subplot(2, 3, 3)\n plt.imshow(B)\n plt.title('Backscatter Estimation')\n fig.add_subplot(2, 3, 4)\n plt.imshow(ill)\n plt.title('Illumination Map')\n fig.add_subplot(2, 3, 5)\n plt.imshow(beta_D)\n plt.title('Attenuation Coefficients')\n fig.add_subplot(2, 3, 6)\n plt.imshow(recovered)\n plt.title('Recovered Image')\n plt.tight_layout(True)\n plt.savefig('components.png')\n plt.show()\n\n return recovered\n\ndef preprocess_for_monodepth(img_fname, output_fname, size_limit=1024):\n img = Image.fromarray(rawpy.imread(img_fname).postprocess())\n img.thumbnail((size_limit, size_limit), Image.ANTIALIAS)\n img_adapteq = exposure.equalize_adapthist(np.array(img), clip_limit=0.03)\n Image.fromarray((np.round(img_adapteq * 255.0)).astype(np.uint8)).save(output_fname)\n\ndef preprocess_sfm_depth_map(depths, min_depth, max_depth):\n z_min = np.min(depths) + (min_depth * (np.max(depths) - np.min(depths)))\n z_max = np.min(depths) + (max_depth * (np.max(depths) - np.min(depths)))\n if max_depth != 0:\n depths[depths == 0] = z_max\n depths[depths < z_min] = 0\n return depths\n\ndef preprocess_monodepth_depth_map(depths, additive_depth, multiply_depth):\n depths = ((depths - np.min(depths)) / (\n np.max(depths) - np.min(depths))).astype(np.float32)\n depths = (multiply_depth * (1.0 - depths)) + additive_depth\n return depths\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--image', required=True, help='Input image')\n parser.add_argument('--depth-map', required=True, help='Input depth map')\n parser.add_argument('--output', default='output.png', help='Output filename')\n parser.add_argument('--f', type=float, default=2.0, help='f value (controls brightness)')\n parser.add_argument('--l', type=float, default=0.5, help='l value (controls balance of attenuation constants)')\n parser.add_argument('--p', type=float, default=0.01, help='p value (controls locality of illuminant map)')\n parser.add_argument('--min-depth', type=float, default=0.1, help='Minimum depth value to use in estimations (range 0-1)')\n parser.add_argument('--max-depth', type=float, default=1.0, help='Replacement depth percentile value for invalid depths (range 0-1)')\n parser.add_argument('--spread-data-fraction', type=float, default=0.01, help='Require data to be this fraction of depth range away from each other in attenuation estimations')\n parser.add_argument('--size', type=int, default=320, help='Size to output')\n parser.add_argument('--output-graphs', action='store_true', help='Output graphs')\n parser.add_argument('--preprocess-for-monodepth', action='store_true', help='Preprocess for monodepth depth maps')\n parser.add_argument('--monodepth', action='store_true', help='Preprocess for monodepth')\n parser.add_argument('--monodepth-add-depth', type=float, default=2.0, help='Additive value for monodepth map')\n parser.add_argument('--monodepth-multiply-depth', type=float, default=10.0, help='Multiplicative value for monodepth map')\n parser.add_argument('--equalize-image', action='store_true', help='Histogram equalization for final output')\n args = parser.parse_args()\n\n if args.preprocess_for_monodepth:\n preprocess_for_monodepth(args.image, args.output, args.size)\n else:\n print('Loading image...', flush=True)\n img, depths = load_image_and_depth_map(args.image, args.depth_map, args.size)\n if args.monodepth:\n depths = preprocess_monodepth_depth_map(depths, args.monodepth_add_depth, args.monodepth_multiply_depth)\n else:\n depths = preprocess_sfm_depth_map(depths, args.min_depth, args.max_depth)\n recovered = run_pipeline(img, depths, args)\n if args.equalize_image:\n recovered = exposure.equalize_adapthist(np.array(recovered), clip_limit=0.03)\n sigma_est = estimate_sigma(recovered, multichannel=True, average_sigmas=True)\n recovered = denoise_tv_chambolle(recovered, sigma_est, multichannel=True)\n plt.imsave(args.output, recovered)\n print('Done.')\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.expand_dims", "numpy.minimum", "numpy.linspace", "numpy.round", "numpy.max", "numpy.mean", "numpy.zeros_like", "numpy.any", "numpy.exp", "numpy.where", "numpy.roll", "matplotlib.pyplot.tight_layout", "numpy.unique", "numpy.stack", "numpy.copy", "numpy.size", "numpy.float32", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.imsave", "numpy.log", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.savefig", "scipy.stats.linregress", "numpy.argsort", "numpy.logical_and", "numpy.array", "matplotlib.pyplot.show", "numpy.sum", "matplotlib.pyplot.ylabel", "numpy.maximum", "numpy.abs", "numpy.random.random", "matplotlib.use", "numpy.sort", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel" ] ]
balamurali-m/Feature-Selection
[ "23291f4ec2a963946b1e5f3fec48b93f675736c2" ]
[ "Feature Selection - Tree Based.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nFeature Selection - Tree Based\r\nAuthor: Balamurali.M\r\n##\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom sklearn.ensemble import ExtraTreesClassifier\r\nfrom sklearn.feature_selection import SelectFromModel\r\n\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n#Generating matrix with random explanatory and response variables\r\nmatr = np.random.randint(200, size=(100, 20))\r\nprint (matr.shape)\r\n\r\ntrain_exp = matr[:80, :19]\r\ntrain_res = matr[:80, 19:]\r\ntest_exp = matr[80:, :19]\r\ntest_act = matr[80:, 19:]\r\n\r\nprint('train_exp',train_exp.shape)\r\nprint('train_res',train_res.shape)\r\nprint('test_exp',test_exp.shape)\r\nprint('test_act',test_act.shape)\r\n\r\nclass FS_ABC:\r\n def __init__(self, w1, x1, y1, z1):\r\n self.w1 = w1\r\n self.x1 = x1\r\n self.y1 = y1\r\n self.z1 = z1 \r\n \r\n def FS_TBS(self):\r\n a1 = ExtraTreesClassifier()\r\n a1 = a1.fit(self.w1, self.x1)\r\n return a1\r\n \r\nmatr_exp = FS_ABC(train_exp, train_res, test_exp, test_act)\r\nb1 = matr_exp.FS_TBS()\r\nprint(b1.feature_importances_)\r\nc1 = SelectFromModel(b1, prefit=True)\r\nd1 = c1.transform(train_exp)\r\nprint (d1)\r\n" ]
[ [ "sklearn.feature_selection.SelectFromModel", "sklearn.ensemble.ExtraTreesClassifier", "numpy.random.randint" ] ]
beproxy/tf_checkpoint_vs_pickle
[ "a40ec0134da8ffd215654f2a110f5684372389c3" ]
[ "machinery.py" ]
[ "from sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nimport pandas as pd\nimport math\nfrom sklearn.metrics import mean_squared_error\n\n\nclass Machinery:\n def __init__(self, filename, seqlen):\n self.seqlen = seqlen\n self.filename = filename\n self.dataset = self.open_dataset()\n self.train_set, self.test_set = self.split_train_test_data()\n self.sc = MinMaxScaler(feature_range=(0, 1))\n self.train_set_scaled = self.trainset_fit_transform()\n self.x_y_normalize = self.split_train_x_y()\n self.X_test = self.testset_transform()\n\n # Extracting data from file\n def open_dataset(self):\n print(f\"Extracting data from file {self.filename}...\")\n dataset = pd.read_csv(self.filename)\n dataset.set_index('Date', inplace=True)\n return dataset\n\n # Data set is split between training set and testing set\n def split_train_test_data(self):\n train_set = self.dataset[:'2019'].iloc[:, 1:2].values\n test_set = self.dataset['2019':].iloc[:, 1:2].values\n return train_set, test_set\n\n # Minimize training data set\n def trainset_fit_transform(self):\n return self.sc.fit_transform(self.train_set)\n\n # Train set is split between X and y and reshape\n def split_train_x_y(self):\n print(\"Train set is split between X and y...\")\n X, y = [], []\n for i in range(self.seqlen, self.train_set.shape[0]):\n X.append(self.train_set_scaled[i - self.seqlen:i, 0])\n y.append(self.train_set_scaled[i, 0])\n X, y = np.array(X), np.array(y)\n X = np.reshape(X, (X.shape[0], X.shape[1], 1))\n return X, y\n\n # Transform testing dataset and reshape\n def testset_transform(self):\n dataset_total = pd.concat((self.dataset[\"High\"][:'2018'], self.dataset[\"High\"]['2019':]), axis=0)\n inputs = dataset_total[len(dataset_total) - len(self.test_set) - self.seqlen:].values\n inputs = inputs.reshape(-1, 1)\n inputs = self.sc.transform(inputs)\n X_test = []\n for i in range(self.seqlen, inputs.shape[0]):\n X_test.append(inputs[i - self.seqlen:i, 0])\n X_test = np.array(X_test)\n return np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n\n # Prediction\n def prediction_data(self, model):\n prediction = model.predict(self.X_test)\n return self.sc.inverse_transform(prediction)\n\n # Evaluate model (root mean square error)\n def return_rmse(self, prediction):\n return math.sqrt(mean_squared_error(self.test_set, prediction))\n" ]
[ [ "pandas.concat", "pandas.read_csv", "numpy.reshape", "sklearn.metrics.mean_squared_error", "numpy.array", "sklearn.preprocessing.MinMaxScaler" ] ]
urielsinger/CDMF
[ "bfa5bacc3aedf71b34cd457b20ca5d649df435b6" ]
[ "CDMF/dataset.py" ]
[ "import torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.dataloader import default_collate\nimport pytorch_lightning as pl\n\n\nclass CDMFDataModule(pl.LightningDataModule):\n \"\"\"\n Example of a DataModule handling data for the CDMF model.\n Currently only generated random data.\n \"\"\"\n def __init__(self, dataset, max_seq_len, batch_size=32, num_workers=0):\n super().__init__()\n self.dataset = dataset\n self.max_seq_len = max_seq_len\n\n self.n_users = None\n self.n_items = None\n self.n_features = None\n\n self.batch_size = batch_size\n self.num_workers = num_workers\n\n def prepare_data(self):\n \"\"\"\n Prepares the dataset (download or create)\n Returns:\n user2seq - dict holding for each user a dictionary holding:\n - items: list of item interaction\n - features: list of features per item interaction\n - timestamps: list of timestamp for each interaction\n - labels: 1 or 0 per item interaction\n \"\"\"\n self.user2seq = {}\n if self.dataset == 'random':\n self.n_users = 100\n self.n_items = 10\n self.n_features = 64\n\n for user in torch.range(1, self.n_users, dtype=torch.long):\n seq_len = torch.randint(low=1, high=self.max_seq_len, size=(1,))[0]\n self.user2seq[user] = {'items': torch.randint(low=1, high=self.n_items + 1, size=(seq_len,)),\n 'features': torch.randn(size=(seq_len, self.n_features)),\n 'timestamps': torch.randint(low=1, high=self.max_seq_len * self.n_users, size=(seq_len,)),\n 'labels': torch.randint(low=0, high=2, size=(seq_len,))}\n else:\n raise Exception(f'dataset {self.dataset} not supported')\n\n def setup(self, stage=None):\n \"\"\"\n Splits the data into train/val/test by splitting the timeline\n \"\"\"\n self.datasets = []\n all_timestamps = torch.cat([seq['timestamps'] for seq in self.user2seq.values()])\n qs = (0., 0.7, 0.85, 1.)\n for i in range(1, len(qs)): # split to train/val/test on timeline\n q = torch.Tensor([qs[i - 1], qs[i]])\n start_timestamp, end_timestamp = torch.quantile(all_timestamps.float(), q=q).tolist()\n\n cur_user2seq = {}\n for user in self.user2seq:\n seq = self.user2seq[user]\n time_mask = (start_timestamp <= seq['timestamps']) * (seq['timestamps'] <= end_timestamp)\n if time_mask.sum() > 0:\n cur_user2seq[user] = {'items': seq['items'][time_mask],\n 'features': seq['features'][time_mask],\n 'timestamps': seq['timestamps'][time_mask],\n 'labels': seq['labels'][time_mask]}\n self.datasets.append(CDMFDataset(cur_user2seq))\n\n def train_dataloader(self):\n return DataLoader(self.datasets[0], shuffle=True, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.pad_collate)\n\n def val_dataloader(self):\n return DataLoader(self.datasets[1], shuffle=False, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.pad_collate)\n\n def test_dataloader(self):\n return DataLoader(self.datasets[2], shuffle=False, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.pad_collate)\n\n def pad_collate(self, batch):\n \"\"\"\n This function is responsible of merging all user-item interaction sequences to a full batch.\n Notice the final batch size might be greater then defined in the DataLoader\n \"\"\"\n batch = [sample for samples in batch for sample in samples]\n max_len = max([len(sample['features']) for sample in batch])\n for i in range(len(batch)):\n cur_len = len(batch[i]['features'])\n pad_len = max_len - cur_len\n batch[i]['features'] = F.pad(input=batch[i]['features'], pad=(0, 0, pad_len, 0), mode='constant', value=0)\n batch[i]['mask'] = torch.BoolTensor([0] * pad_len + [1] * cur_len)\n return default_collate(batch)\n\n\nclass CDMFDataset(Dataset):\n def __init__(self, user2seq):\n super(CDMFDataset, self).__init__()\n self.user2seq = user2seq\n self.users = list(self.user2seq.keys())\n\n def __len__(self):\n return len(self.users)\n\n def __getitem__(self, index):\n \"\"\"\n Returns:\n return a list of all item interaction sequences for the current user. Please notice this function\n flattens all user-item pairs to different samples\n \"\"\"\n user = self.users[index]\n seq = self.user2seq[user]\n\n sorted_indices = torch.argsort(seq['timestamps'])\n items = seq['items'][sorted_indices]\n features = seq['features'][sorted_indices]\n labels = seq['labels'][sorted_indices]\n\n unique_items = torch.unique(items)\n return [{'user': user,\n 'item': item,\n 'features': features[items == item][:-1],\n 'labels': labels[items == item][-1]} for item in unique_items if sum(items == item) > 2]\n" ]
[ [ "torch.BoolTensor", "torch.range", "torch.randint", "torch.Tensor", "torch.randn", "torch.utils.data.DataLoader", "torch.unique", "torch.argsort", "torch.nn.functional.pad", "torch.utils.data.dataloader.default_collate" ] ]
Ashafix/yolo-tf2
[ "5ca83ba411ba1f1a0091464381ee5dc3a4a582d6" ]
[ "yolo_tf2/utils/common.py" ]
[ "import logging\nimport os\nfrom logging import handlers\nfrom pathlib import Path\nfrom time import perf_counter\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import SubElement\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom lxml import etree\nfrom tensorflow.keras.layers import Layer\nfrom tensorflow.keras.losses import binary_crossentropy, sparse_categorical_crossentropy\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.util.tf_export import keras_export\n\ntfa.options.TF_ADDONS_PY_OPS = True\n\n\ndef get_logger(log_file=None):\n \"\"\"\n Initialize logger configuration.\n\n Returns:\n logger.\n \"\"\"\n formatter = logging.Formatter(\n '%(asctime)s %(name)s.%(funcName)s +%(lineno)s: '\n '%(levelname)-8s [%(process)d] %(message)s'\n )\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n if log_file:\n file_handler = handlers.RotatingFileHandler(log_file, backupCount=10)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n console_handler = logging.StreamHandler()\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n return logger\n\n\nLOGGER = get_logger()\n\n\ndef timer(logger):\n \"\"\"\n Timer wrapper.\n logger: logging.RootLogger object\n\n Returns:\n timed\n \"\"\"\n\n def timed(func):\n def wrapper(*args, **kwargs):\n start_time = perf_counter()\n result = func(*args, **kwargs)\n total_time = perf_counter() - start_time\n if logger is not None:\n logger.info(f'{func.__name__} execution time: ' f'{total_time} seconds')\n if result is not None:\n return result\n\n return wrapper\n\n return timed\n\n\ndef ratios_to_coordinates(bx, by, bw, bh, width, height):\n \"\"\"\n Convert relative coordinates to actual coordinates.\n Args:\n bx: Relative center x coordinate.\n by: Relative center y coordinate.\n bw: Relative box width.\n bh: Relative box height.\n width: Image batch width.\n height: Image batch height.\n\n Return:\n x1: x coordinate.\n y1: y coordinate.\n x2: x1 + Bounding box width.\n y2: y1 + Bounding box height.\n \"\"\"\n w, h = bw * width, bh * height\n x, y = bx * width + (w / 2), by * height + (h / 2)\n return x, y, x + w, y + h\n\n\ndef transform_images(x_train, size):\n \"\"\"\n Resize image tensor.\n Args:\n x_train: Image tensor.\n size: new (width, height)\n \"\"\"\n x_train = tf.image.resize(x_train, (size, size))\n return x_train / 255\n\n\n@tf.function\ndef transform_targets_for_output(y_true, grid_size, anchor_idxs):\n n = tf.shape(y_true)[0]\n y_true_out = tf.zeros((n, grid_size, grid_size, tf.shape(anchor_idxs)[0], 6))\n anchor_idxs = tf.cast(anchor_idxs, tf.int32)\n indexes = tf.TensorArray(tf.int32, 1, dynamic_size=True)\n updates = tf.TensorArray(tf.float32, 1, dynamic_size=True)\n idx = 0\n for i in tf.range(n):\n for j in tf.range(tf.shape(y_true)[1]):\n if tf.equal(y_true[i][j][2], 0):\n continue\n anchor_eq = tf.equal(anchor_idxs, tf.cast(y_true[i][j][5], tf.int32))\n if tf.reduce_any(anchor_eq):\n box = y_true[i][j][0:4]\n box_xy = (y_true[i][j][0:2] + y_true[i][j][2:4]) / 2\n anchor_idx = tf.cast(tf.where(anchor_eq), tf.int32)\n grid_xy = tf.cast(box_xy // (1 / grid_size), tf.int32)\n indexes = indexes.write(\n idx, [i, grid_xy[1], grid_xy[0], anchor_idx[0][0]]\n )\n updates = updates.write(\n idx, [box[0], box[1], box[2], box[3], 1, y_true[i][j][4]]\n )\n idx += 1\n return tf.tensor_scatter_nd_update(y_true_out, indexes.stack(), updates.stack())\n\n\ndef transform_targets(y_train, anchors, anchor_masks, size):\n y_outs = []\n grid_size = size // 32\n anchors = tf.cast(anchors, tf.float32)\n anchor_area = anchors[..., 0] * anchors[..., 1]\n box_wh = y_train[..., 2:4] - y_train[..., 0:2]\n box_wh = tf.tile(tf.expand_dims(box_wh, -2), (1, 1, tf.shape(anchors)[0], 1))\n box_area = box_wh[..., 0] * box_wh[..., 1]\n intersection = tf.minimum(box_wh[..., 0], anchors[..., 0]) * tf.minimum(\n box_wh[..., 1], anchors[..., 1]\n )\n iou = intersection / (box_area + anchor_area - intersection)\n anchor_idx = tf.cast(tf.argmax(iou, axis=-1), tf.float32)\n anchor_idx = tf.expand_dims(anchor_idx, axis=-1)\n y_train = tf.concat([y_train, anchor_idx], axis=-1)\n for anchor_idxs in anchor_masks:\n y_outs.append(transform_targets_for_output(y_train, grid_size, anchor_idxs))\n grid_size *= 2\n return tuple(y_outs)\n\n\ndef broadcast_iou(box_1, box_2):\n box_1 = tf.expand_dims(box_1, -2)\n box_2 = tf.expand_dims(box_2, 0)\n new_shape = tf.broadcast_dynamic_shape(tf.shape(box_1), tf.shape(box_2))\n box_1 = tf.broadcast_to(box_1, new_shape)\n box_2 = tf.broadcast_to(box_2, new_shape)\n int_w = tf.maximum(\n tf.minimum(box_1[..., 2], box_2[..., 2])\n - tf.maximum(box_1[..., 0], box_2[..., 0]),\n 0,\n )\n int_h = tf.maximum(\n tf.minimum(box_1[..., 3], box_2[..., 3])\n - tf.maximum(box_1[..., 1], box_2[..., 1]),\n 0,\n )\n int_area = int_w * int_h\n box_1_area = (box_1[..., 2] - box_1[..., 0]) * (box_1[..., 3] - box_1[..., 1])\n box_2_area = (box_2[..., 2] - box_2[..., 0]) * (box_2[..., 3] - box_2[..., 1])\n return int_area / (box_1_area + box_2_area - int_area)\n\n\ndef get_boxes(pred, anchors, classes):\n grid_size = tf.shape(pred)[1]\n box_xy, box_wh, object_probability, class_probabilities = tf.split(\n pred, (2, 2, 1, classes), axis=-1\n )\n box_xy = tf.sigmoid(box_xy)\n object_probability = tf.sigmoid(object_probability)\n class_probabilities = tf.sigmoid(class_probabilities)\n pred_box = tf.concat((box_xy, box_wh), axis=-1)\n grid = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\n grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2)\n box_xy = (box_xy + tf.cast(grid, tf.float32)) / tf.cast(grid_size, tf.float32)\n box_wh = tf.exp(box_wh) * anchors\n box_x1y1 = box_xy - box_wh / 2\n box_x2y2 = box_xy + box_wh / 2\n bbox = tf.concat([box_x1y1, box_x2y2], axis=-1)\n return bbox, object_probability, class_probabilities, pred_box\n\n\ndef calculate_loss(anchors, classes=80, ignore_thresh=0.5):\n def yolo_loss(y_true, y_pred):\n pred_box, pred_obj, pred_class, pred_xywh = get_boxes(y_pred, anchors, classes)\n pred_xy = pred_xywh[..., 0:2]\n pred_wh = pred_xywh[..., 2:4]\n true_box, true_obj, true_class_idx = tf.split(y_true, (4, 1, 1), axis=-1)\n true_xy = (true_box[..., 0:2] + true_box[..., 2:4]) / 2\n true_wh = true_box[..., 2:4] - true_box[..., 0:2]\n box_loss_scale = 2 - true_wh[..., 0] * true_wh[..., 1]\n grid_size = tf.shape(y_true)[1]\n grid = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\n grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2)\n true_xy = true_xy * tf.cast(grid_size, tf.float32) - tf.cast(grid, tf.float32)\n true_wh = tf.math.log(true_wh / anchors)\n true_wh = tf.where(tf.math.is_inf(true_wh), tf.zeros_like(true_wh), true_wh)\n obj_mask = tf.squeeze(true_obj, -1)\n best_iou = tf.map_fn(\n lambda x: tf.reduce_max(\n broadcast_iou(x[0], tf.boolean_mask(x[1], tf.cast(x[2], tf.bool))),\n axis=-1,\n ),\n (pred_box, true_box, obj_mask),\n fn_output_signature=tf.float32,\n )\n ignore_mask = tf.cast(best_iou < ignore_thresh, tf.float32)\n xy_loss = (\n obj_mask\n * box_loss_scale\n * tf.reduce_sum(tf.square(true_xy - pred_xy), axis=-1)\n )\n wh_loss = (\n obj_mask\n * box_loss_scale\n * tf.reduce_sum(tf.square(true_wh - pred_wh), axis=-1)\n )\n obj_loss = binary_crossentropy(true_obj, pred_obj)\n obj_loss = obj_mask * obj_loss + (1 - obj_mask) * ignore_mask * obj_loss\n class_loss = obj_mask * sparse_categorical_crossentropy(\n true_class_idx, pred_class\n )\n xy_loss = tf.reduce_sum(xy_loss, axis=(1, 2, 3))\n wh_loss = tf.reduce_sum(wh_loss, axis=(1, 2, 3))\n obj_loss = tf.reduce_sum(obj_loss, axis=(1, 2, 3))\n class_loss = tf.reduce_sum(class_loss, axis=(1, 2, 3))\n return xy_loss + wh_loss + obj_loss + class_loss\n\n return yolo_loss\n\n\ndef add_xml_path(xml_file, path):\n \"\"\"\n Add a path element to the xml file and save.\n Args:\n xml_file: .xml file path.\n path: str, path to add.\n\n Returns:\n None\n \"\"\"\n tree = ElementTree.parse(xml_file)\n top = tree.getroot()\n folder_tag = tree.find('folder')\n folder_tag.text = path\n file_name_tag = tree.find('filename')\n path_tag = SubElement(top, 'path')\n path_tag.text = get_abs_path(folder_tag.text, file_name_tag.text)\n rough_string = ElementTree.tostring(top, 'utf8')\n root = etree.fromstring(rough_string)\n pretty = etree.tostring(root, pretty_print=True, encoding='utf-8').replace(\n ' '.encode(), '\\t'.encode()\n )\n os.remove(xml_file)\n with open(xml_file, 'wb') as output:\n output.write(pretty)\n\n\ndef get_detection_data(image, image_name, outputs, class_names):\n \"\"\"\n Organize predictions of a single image into a pandas DataFrame.\n Args:\n image: Image as a numpy array.\n image_name: str, name to write in the image column.\n outputs: Outputs from inference_model.predict()\n class_names: A list of object class names.\n\n Returns:\n data: pandas DataFrame with the detections.\n \"\"\"\n nums = outputs[-1]\n boxes, scores, classes = 3 * [None]\n if isinstance(outputs[0], np.ndarray):\n boxes, scores, classes = [item[0][: int(nums)] for item in outputs[:-1]]\n if not isinstance(outputs[0], np.ndarray):\n boxes, scores, classes = [item[0][: int(nums)].numpy() for item in outputs[:-1]]\n w, h = np.flip(image.shape[0:2])\n data = pd.DataFrame(boxes, columns=['x1', 'y1', 'x2', 'y2'])\n data[['x1', 'x2']] = (data[['x1', 'x2']] * w).astype('int64')\n data[['y1', 'y2']] = (data[['y1', 'y2']] * h).astype('int64')\n data['object_name'] = np.array(class_names)[classes.astype('int64')]\n data['image'] = image_name\n data['score'] = scores\n data['img_width'] = w\n data['img_height'] = h\n data = data[\n [\n 'image',\n 'object_name',\n 'x1',\n 'y1',\n 'x2',\n 'y2',\n 'score',\n 'img_width',\n 'img_height',\n ]\n ]\n return data\n\n\ndef activate_gpu():\n \"\"\"\n Check for GPU existence and if found, activate.\n\n Returns:\n None\n \"\"\"\n physical_devices = tf.config.experimental.list_physical_devices('GPU')\n if len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n LOGGER.info('GPU activated')\n\n\ndef calculate_ratios(x1, y1, x2, y2, width, height):\n \"\"\"\n Calculate relative object ratios in the labeled image.\n Args:\n x1: Start x coordinate.\n y1: Start y coordinate.\n x2: End x coordinate.\n y2: End y coordinate.\n width: Bounding box width.\n height: Bounding box height.\n\n Return:\n bx: Relative center x coordinate.\n by: Relative center y coordinate.\n bw: Relative box width.\n bh: Relative box height.\n \"\"\"\n box_width = abs(x2 - x1)\n box_height = abs(y2 - y1)\n bx = 1 - ((width - min(x1, x2) + (box_width / 2)) / width)\n by = 1 - ((height - min(y1, y2) + (box_height / 2)) / height)\n bw = box_width / width\n bh = box_height / height\n return bx, by, bw, bh\n\n\ndef calculate_display_data(prediction_file, classes_file, img_width, img_height, out):\n \"\"\"\n Convert coordinates to relative labels.\n\n prediction_file: csv file containing label coordinates.\n classes_file: .txt file containing object classes.\n img_width: Image width.\n img_height: Image height.\n out: output path.\n\n Returns:\n None\n \"\"\"\n preds = pd.read_csv(prediction_file)\n rows = []\n indices = {\n item: ind\n for ind, item in enumerate([item.strip() for item in open(classes_file)])\n }\n for ind, item in preds.iterrows():\n img, obj, xx1, yy1, xx2, yy2, score, imgw, imgh, dk = item.values\n bxx, byy, bww, bhh = calculate_ratios(xx1, yy1, xx2, yy2, img_width, img_height)\n rows.append([img, obj, indices[obj], bxx, byy, bww, bhh])\n fr = pd.DataFrame(\n rows,\n columns=[\n 'image',\n 'object_name',\n 'object_index',\n 'bx',\n 'by',\n 'bw',\n 'bh',\n ],\n )\n fr.to_csv(out, index=False)\n\n\n@keras_export('keras.layers.Mish')\nclass Mish(Layer):\n \"\"\"\n Mish new activation function\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.supports_masking = True\n\n def call(self, inputs, *args, **kwargs):\n return tfa.activations.mish(inputs)\n\n @tf_utils.shape_type_conversion\n def compute_output_shape(self, input_shape):\n return input_shape\n\n\ndef get_abs_path(\n *args, verify=False, verify_parents=False, create_parents=False, create=False\n):\n fp = Path(*args).absolute().resolve()\n posix_path = fp.as_posix()\n if create_parents:\n os.makedirs(fp.parent.as_posix(), exist_ok=True)\n if create:\n os.makedirs(fp.as_posix(), exist_ok=True)\n if verify:\n assert fp.exists(), f'Path does not exist {posix_path}'\n if verify_parents:\n parent = fp.parent\n assert parent.exists(), f'Folder not found {parent.as_posix()}'\n return posix_path\n\n\ndef get_image_files(folder_path):\n folder_path = get_abs_path(folder_path, verify=True)\n image_files = [\n get_abs_path(folder_path, filename)\n for filename in os.listdir(folder_path)\n if Path(filename).suffix in ['.png', '.jpg', '.jpeg', '.bmp']\n ]\n if image_files:\n return image_files\n issue = f'No image files found in {folder_path}'\n LOGGER.error(issue)\n raise FileNotFoundError(issue)\n" ]
[ [ "tensorflow.concat", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.minimum", "tensorflow.equal", "pandas.DataFrame", "tensorflow.where", "pandas.read_csv", "tensorflow.config.experimental.set_memory_growth", "tensorflow.python.util.tf_export.keras_export", "tensorflow.squeeze", "tensorflow.square", "tensorflow.argmax", "tensorflow.math.is_inf", "tensorflow.shape", "tensorflow.TensorArray", "tensorflow.reduce_any", "tensorflow.config.experimental.list_physical_devices", "tensorflow.keras.losses.sparse_categorical_crossentropy", "tensorflow.exp", "tensorflow.zeros_like", "tensorflow.keras.losses.binary_crossentropy", "tensorflow.split", "numpy.array", "numpy.flip", "tensorflow.range", "tensorflow.broadcast_to", "tensorflow.maximum", "tensorflow.sigmoid", "tensorflow.expand_dims", "tensorflow.math.log", "tensorflow.image.resize" ] ]
Moving-AI/action-recognition
[ "75249dd4e2a3f6f949f40311d911ab716d2145a5" ]
[ "source/dataprocessing/__init__.py" ]
[ "import logging\nimport os\nimport re\nfrom itertools import chain\nfrom pathlib import Path\n\nimport cv2\nimport imutils\nimport numpy as np\nimport pandas as pd\n\nimport source.funciones as funciones\nfrom source.entities.person import Person\nfrom source.entities.person_frames import PersonMovement\nfrom source.funciones import read_labels_txt\n\nFORMAT = \"%(asctime)s - %(levelname)s: %(message)s\"\nlogging.basicConfig(format=FORMAT)\nlogger = logging.getLogger(__name__)\n\nformatter = logging.Formatter(FORMAT)\nlogger.setLevel(logging.INFO)\n\n\nclass DataProcessor:\n \"\"\"Class used to process data to generate training examples. Has the recquired functions\n to read a video from a directory and extract the frames. Once a labels file is provided\n with the valid frames for each video, the frame groups are made and training data is generated\n and written in a file for later usage.\n \n Returns:\n DataProcessor:\n \"\"\"\n\n def __init__(self, model_path=None, input_dim=(257, 257), threshold=0.5, rescale=(1, 1), backbone='resnet',\n output_stride=None):\n \"\"\"Constructor for the DataProcessor class.\n \n Args:\n model_path (str, optional): Path for the TFLite Posenet file. If None and by default is\n searched in the root/models folder of the repository\n input_dim (tuple, optional): Input dimension for the previously specified model. Defaults to (257, 257).\n threshold (float, optional): Confidence threshold for considering a body joint valid. Defaults to 0.5.\n rescale (tuple, optional): Rescaling factor in the output. Defaults to (1,1).\n \"\"\"\n if model_path is None:\n if backbone == 'resnet':\n MODEL_PATH = Path(__file__).parents[2].joinpath('models/resnet_stride16/model-stride16.json')\n else:\n MODEL_PATH = Path(__file__).parents[2].joinpath(\n \"models/posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite\")\n else:\n MODEL_PATH = model_path\n\n if backbone == 'resnet':\n assert output_stride is not None, 'A value for output_stride must be provided when using resnet as backbone'\n dimensions = (200, 256)\n self.model, graph = funciones.load_model_resnet(str(MODEL_PATH)) # Actually a session.\n self.input_details, self.output_details = funciones.get_tensors_graph(graph)\n self.prepare_frame = funciones.prepare_frame_resnet\n self.input_dim = [(int(x) // output_stride) * output_stride + 1 for x in dimensions]\n self.get_model_output = funciones.get_model_output_resnet\n else:\n self.model, self.input_details, self.output_details = funciones.load_model_mobilenet(str(MODEL_PATH))\n self.prepare_frame = funciones.prepare_frame_mobilenet\n self.input_dim = input_dim\n self.get_model_output = funciones.get_model_output_mobilenet\n\n self.threshold = threshold\n self.rescale = rescale\n self.output_stride = output_stride\n @staticmethod\n def process_video(filename, input_path=None, output_path=None, output_shape=(257, 257), fps_reduce=2, angle=0):\n \"\"\"Process a video from the resources folder and saves all the frames\n inside a folder with the name of the video\n FILENAME_frame_X.jpg\n \n Args:\n filename (str): Name of the video inside resources\n output_shape (tuple, optional): Size of the output images. Defaults to (256,256).\n fps_reduce (int, optional): Take one image out of #fps_reduce. \n Defaults to 2.\n angle (int): Angle that the video images should be rotated. \n \"\"\"\n if output_path is None:\n OUTPUT_PATH = Path(__file__).parents[2].joinpath(\"resources/{}\".format(filename))\n else:\n OUTPUT_PATH = Path(output_path).joinpath(\"/{}\".format(filename))\n\n if input_path is None:\n INPUT_PATH = Path(__file__).parents[2].joinpath(\"resources/{}\".format(filename + \".mp4\"))\n else:\n INPUT_PATH = Path(output_path).joinpath(\"/{}\".format(filename + \".mp4\"))\n\n try:\n os.mkdir(OUTPUT_PATH)\n except:\n os.system(\"rm -r {}\".format(OUTPUT_PATH))\n os.mkdir(OUTPUT_PATH)\n\n # Read video\n video = cv2.VideoCapture(str(INPUT_PATH))\n count = 0\n logger.debug(\"Started reading frames.\")\n while video.isOpened():\n logger.debug(\n \"Reading frame {}/{} from file {}\".format(count + 1, video.get(cv2.CAP_PROP_FRAME_COUNT), filename))\n\n # Frame reading, reshaping and saving\n _, frame = video.read()\n frame = cv2.resize(frame, output_shape)\n # if DataProcessor.check_rotation(\"./resources/{}\".format(filename)) is not None:\n\n frame = imutils.rotate(frame, angle)\n\n if count % fps_reduce == 0:\n cv2.imwrite(\n str(OUTPUT_PATH.joinpath(\"{}_frame_{}.jpg\".format(filename.split(\".\")[0], count // fps_reduce))),\n frame)\n count = count + 1\n\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n if video.get(cv2.CAP_PROP_POS_FRAMES) == video.get(cv2.CAP_PROP_FRAME_COUNT):\n # If the number of captured frames is equal to the total number of frames,\n break\n logger.debug(\"Stop reading files.\")\n video.release()\n\n def training_file_writer(self, labels_path=None, output_file=None, append=False, n=5, times_v=10):\n \"\"\"This function is the main function inside DataProcessor file. It runs the whole pipeline, in this order:\n - Gets actions and frame intervals from the labels file\n - Processes the frame intervals, keeping only the valid ones.\n - Groups the frames in groups of n\n - Coordinates are calculated from those groups\n - The coordinates are added to the output file in .csv format\n \n Args:\n labels_path (str, optional): Absolute path of the labels file. If none is taken from\n action-detection/resources.\n output_file (str, optional): Absolute path of the output csv file. If none is saved into \n action-detection/resources/training_data.csv.\n append (bool, optional): If True, the calculated coordinates are ADDED to the file\n if it's not empty. Defaults to False.\n n (int, optional): Number of frames to obtain coordinates from. Defaults to 5.\n times_v (int, optional): Times point speed is introduced into coordinates. Defaults to 10.\n \n Returns:\n pandas.DataFrame: DataFrame containing the obtained coordinates and the ones in output_file\n if append = True\n \"\"\"\n if labels_path is None:\n labels_path = Path(__file__).parents[2].joinpath(\"resources/{}\".format(\"labels.txt\"))\n else:\n labels_path = Path(labels_path)\n if output_file is None:\n output_file = Path(__file__).parents[2].joinpath(\"resources/{}\".format(\"training_data.csv\"))\n else:\n output_file = Path(output_file)\n\n # Obtain the dictionary of coordinates\n coordinates_dict = self.get_coordinates(str(labels_path), n=n, times_v=times_v)\n try:\n if append:\n df_initial = pd.read_csv(str(output_file))\n df_list = [df_initial]\n else:\n df_list = []\n except:\n if append:\n logger.warning(\"Append is set to true but the reading gave an exception\")\n df_list = []\n\n for video in coordinates_dict:\n if len(coordinates_dict[video]) == 0:\n continue\n else:\n array = np.vstack(coordinates_dict[video])\n df = pd.DataFrame(array)\n action = video.split(\"_\")[0]\n df[\"action\"] = [action] * len(coordinates_dict[video])\n df_list.append(df)\n logger.info(df_list)\n cols_model_orig = [int(x) for x in list(df_list[-1].columns) if str(x).isnumeric()]\n cols_model_target = [str(x) for x in cols_model_orig if str(x).isnumeric()]\n mapper = {}\n for orig, target in zip(cols_model_orig, cols_model_target):\n mapper[orig] = target\n\n df_list = [df_iter.rename(mapper, axis='columns') for df_iter in df_list]\n\n logger.info(\"Concatenating {} DataFrames before writing.\".format(len(df_list)))\n\n df = pd.concat(df_list, axis=0, ignore_index=True)\n\n df.to_csv(str(output_file), index=False, header=False)\n return df\n\n def get_coordinates(self, labels_path=None, n=5, times_v=10):\n \"\"\"This functions is a wrapper that makes this steps:\n - Gets actions and frame intervals from the labels file\n - Processes the frame intervals, keeping only the valid ones.\n - Groups the frames in groups of n\n - Coordinates are calculated from those groups\n Args:\n labels_path (str, optional): Absolute for the labels file. If none, it is searched inside\n action-recognition/resources\n n (int, optional): Lenght of the frame list to process. Defaults to 5.\n times_v (int, optional): Times speeds of the points is introduced as coordinate. Defaults to 10.\n \n Returns:\n dict: Dictionary that contains for each video in the labels file the coordinates after running the\n frame selection pipeline.\n \"\"\"\n\n logger.info(\"Calculating coordinates from labels_path {}\".format(labels_path))\n if labels_path is None:\n labels_path = Path(__file__).parents[2].joinpath(\"resources/{}\".format(\"labels.txt\"))\n else:\n labels_path = Path(labels_path)\n actions = DataProcessor.find_actions(labels_path)\n frame_groups = self.get_frame_groups(actions, labels_path, n)\n coordinates_dict = {}\n for video in frame_groups:\n logger.debug(\"Calculating coordinates for video {}\".format(video))\n for group in frame_groups[video]:\n if len(group) == 0:\n continue\n else:\n if video not in coordinates_dict:\n coordinates_dict[video] = []\n persons = [element[1] for element in group]\n coordinates = PersonMovement(persons, times_v,\n joints_remove=(13, 14, 15, 16),\n model='NN').coords.flatten()\n\n logger.info(\"Tamaño de las coordenadas: {}\".format(coordinates.shape))\n coordinates_dict[video].append(coordinates)\n return coordinates_dict\n\n def process_frame(self, image_path):\n \"\"\"Receives a frame path and returns the person associated\n \n Args:\n image_path (str): String containig the path of an image\n \n Returns:\n Person: Person associated to that frame.\n \"\"\"\n logger.debug(\"Processing frame {}\".format(image_path.split(\"/\")[-1]))\n frame = cv2.imread(image_path)\n frame = self.prepare_frame(frame, self.input_dim)\n output_data, offset_data = self.get_model_output(self.model, frame, self.input_details, self.output_details)\n return Person(output_data, offset_data, self.rescale, self.threshold, output_stride=self.output_stride)\n\n def process_live_frame(self, frame):\n \"\"\"Receives a frame path and returns the person associated\n \n Args:\n\n \n Returns:\n Person: Person associated to that frame.\n \"\"\"\n logger.debug(\"Processing frame passed to the function (live).\")\n\n frame = self.prepare_frame(frame, self.input_dim)\n output_data, offset_data = self.get_model_output(self.model, frame, self.input_details, self.output_details)\n return Person(output_data, offset_data, self.rescale, self.threshold, output_stride=self.output_stride)\n\n def get_frame_groups(self, actions, labels_path, n=5):\n \"\"\"From a labels path, a list of actions and a number of frames per\n training data row gets all posible groups of frames to process.\n \n Args:\n labels_path (str): Path to the labels.txt file\n actions (list): Actions to process\n n (int, optional): Size of the list of people needed. Defaults to 5.\n \n Returns:\n [type]: [description]\n \"\"\"\n logger.info(\"Getting frame groups for labels in {}\".format(labels_path))\n frame_groups = {}\n self.people_dict = {}\n labels = read_labels_txt(str(labels_path), actions)\n for label in labels:\n logger.debug(\"Getting grame groups for label {}\".format(label))\n # Groups of frames longer than n\n valid_frame_intervals = [group for group in labels[label] if group[1] - group[0] >= n - 1]\n # Transform each interval in a list of valid persons\n frame_person_list = [self.get_valid_persons(label, interval, n) for interval in valid_frame_intervals]\n # Get groups of n contiguous persons\n valid_persons_groups = [self.valid_groups(lst, n) for lst in frame_person_list]\n filter_nones = [element for element in valid_persons_groups if element is not None]\n # Complete dictionary\n frame_groups[label] = filter_nones\n # There is an undesired extra level in the lists generated. We remove it\n frame_groups_definitive = {}\n logging.info(\"Cleaning frame groups.\")\n for video in frame_groups:\n frame_groups_definitive[video] = list(chain.from_iterable(frame_groups[video]))\n return frame_groups_definitive\n\n def get_valid_persons(self, fle, interval, n):\n logger.debug(\"Getting valid persons from file {}, interval {}\".format(fle, interval))\n persons_list = self.frame_interval_to_people_list(fle, interval)\n\n # Now we return all the persons in the interval. Valids will be filtered\n # Into consideration the position in the frame.\n\n return persons_list\n\n def frame_interval_to_people_list(self, fle, interval, images_path=None):\n \"\"\"From an interval [start, end] of frames from video, returns a list\n of tuples (index, person(i_Frame)).\n \n Args:\n file (str): folder containing frames\n interval (list): start and end of the interval\n \n Returns:\n list: List of Persons calculated from images\n \"\"\"\n logger.debug(\"Calculating people list from interval {} in file {}\".format(interval, fle))\n if images_path is None:\n PATH = Path(__file__).parents[2].joinpath(\"resources/{}\".format(fle))\n else:\n PATH = Path(images_path).joinpath(\"/{}\".format(fle))\n\n return [[i, self.process_frame(str(PATH) + \"/{}_frame_{}.jpg\".format(fle, i))] \\\n for i in range(interval[0], interval[1] + 1)]\n\n def valid_groups(self, lst, n):\n \"\"\"Given a list of persons, returns the valid lists of contiguous persons\n (frames)\n \n Args:\n n (int): Size of the desired lists of persons\n lst (list): List of lists [int, Person]\n \"\"\"\n valid, result, aux = 0, [], []\n if lst is not None:\n for index, i in enumerate(lst):\n # if it's not the first frame --> Infer keypoints\n # If is the first frame and the frame is valid\n if valid == 0 and i[1].is_valid_first():\n # New group\n aux.append(i)\n valid += 1\n\n # If it's not the first and frames are contiguous\n elif valid > 0 and i[0] - aux[valid - 1][0] == 1:\n\n # If this frame does not complete a group then append to aux\n if valid < n - 1 and i[1].is_valid_other():\n i[1].infer_lc_keypoints(lst[index - 1][1])\n # Value is valid\n aux.append(i)\n valid += 1\n # If this frame completes a group append the resutl\n elif valid == n - 1 and i[1].is_valid_other():\n i[1].infer_lc_keypoints(lst[index - 1][1])\n # Group is now complete\n aux.append(i)\n result.append(aux)\n aux = []\n valid = 0\n # If frames were contiguous, the frame was not valid as other, it becomes first frame if\n # valid as first frame\n elif i[1].is_valid_first():\n aux = [i]\n valid = 1\n # If the next frame is not valid_other and neither does valid_first, we will start\n # from scratch\n else:\n aux = []\n valid = 0\n # If frames wew not contiguous and this frame is valid as first, we try that\n elif valid > 0 and i[0] - aux[valid - 1][0] != 1 and i[1].is_valid_first():\n aux = [i]\n valid = 1\n # In any other case, we will start from scratch\n else:\n aux = []\n valid = 0\n return result\n else:\n return None\n\n @staticmethod\n def find_actions(file):\n actions = set()\n regex = r\"[a-z]+\"\n for line in open(str(file)):\n for match in re.finditer(regex, line):\n actions.add(match.group())\n return list(actions)\n" ]
[ [ "pandas.concat", "numpy.vstack", "pandas.DataFrame" ] ]
elehcim/spectral-cube
[ "0b64e9e3c2a71c5e8ff99eaa8d0e2f433de96087" ]
[ "spectral_cube/tests/test_performance.py" ]
[ "\"\"\"\nPerformance-related tests to make sure we don't use more memory than we should\n\"\"\"\n\nfrom __future__ import print_function, absolute_import, division\n\nimport numpy as np\n\nimport pytest\nimport tempfile\nimport sys\n\ntry:\n import tracemalloc\n tracemallocOK = True\nexcept ImportError:\n tracemallocOK = False\n\n# The comparison of Quantities in test_memory_usage\n# fail with older versions of numpy\nfrom distutils.version import LooseVersion\n\nNPY_VERSION_CHECK = LooseVersion(np.version.version) >= \"1.13\"\n\nfrom .test_moments import moment_cube\nfrom .helpers import assert_allclose\nfrom ..spectral_cube import SpectralCube\nfrom . import utilities\n\nfrom astropy import convolution, units as u\n\ndef find_base_nbytes(obj):\n # from http://stackoverflow.com/questions/34637875/size-of-numpy-strided-array-broadcast-array-in-memory\n if obj.base is not None:\n return find_base_nbytes(obj.base)\n return obj.nbytes\n\ndef test_pix_size():\n mc_hdu = moment_cube()\n sc = SpectralCube.read(mc_hdu)\n\n s,y,x = sc._pix_size()\n\n # float64 by default\n bytes_per_pix = 8\n\n assert find_base_nbytes(s) == sc.shape[0]*bytes_per_pix\n assert find_base_nbytes(y) == sc.shape[1]*sc.shape[2]*bytes_per_pix\n assert find_base_nbytes(x) == sc.shape[1]*sc.shape[2]*bytes_per_pix\n\ndef test_compare_pix_size_approaches():\n mc_hdu = moment_cube()\n sc = SpectralCube.read(mc_hdu)\n\n sa,ya,xa = sc._pix_size()\n s,y,x = (sc._pix_size_slice(ii) for ii in range(3))\n\n assert_allclose(sa, s)\n assert_allclose(ya, y)\n assert_allclose(xa, x)\n\ndef test_pix_cen():\n mc_hdu = moment_cube()\n sc = SpectralCube.read(mc_hdu)\n\n s,y,x = sc._pix_cen()\n\n # float64 by default\n bytes_per_pix = 8\n\n assert find_base_nbytes(s) == sc.shape[0]*bytes_per_pix\n assert find_base_nbytes(y) == sc.shape[1]*sc.shape[2]*bytes_per_pix\n assert find_base_nbytes(x) == sc.shape[1]*sc.shape[2]*bytes_per_pix\n\n@pytest.mark.skipif('True')\ndef test_parallel_performance_smoothing():\n\n import timeit\n\n setup = 'cube,_ = utilities.generate_gaussian_cube(shape=(300,64,64))'\n stmt = 'result = cube.spectral_smooth(kernel=convolution.Gaussian1DKernel(20.0), num_cores={0}, use_memmap=False)'\n\n rslt = {}\n for ncores in (1,2,3,4):\n time = timeit.timeit(stmt=stmt.format(ncores), setup=setup, number=5, globals=globals())\n rslt[ncores] = time\n\n print()\n print(\"memmap=False\")\n print(rslt)\n\n setup = 'cube,_ = utilities.generate_gaussian_cube(shape=(300,64,64))'\n stmt = 'result = cube.spectral_smooth(kernel=convolution.Gaussian1DKernel(20.0), num_cores={0}, use_memmap=True)'\n\n rslt = {}\n for ncores in (1,2,3,4):\n time = timeit.timeit(stmt=stmt.format(ncores), setup=setup, number=5, globals=globals())\n rslt[ncores] = time\n\n stmt = 'result = cube.spectral_smooth(kernel=convolution.Gaussian1DKernel(20.0), num_cores={0}, use_memmap=True, parallel=False)'\n rslt[0] = timeit.timeit(stmt=stmt.format(1), setup=setup, number=5, globals=globals())\n\n print()\n print(\"memmap=True\")\n print(rslt)\n\n\n if False:\n for shape in [(300,64,64), (600,64,64), (900,64,64),\n (300,128,128), (300,256,256), (900,256,256)]:\n\n setup = 'cube,_ = utilities.generate_gaussian_cube(shape={0})'.format(shape)\n stmt = 'result = cube.spectral_smooth(kernel=convolution.Gaussian1DKernel(20.0), num_cores={0}, use_memmap=True)'\n\n rslt = {}\n for ncores in (1,2,3,4):\n time = timeit.timeit(stmt=stmt.format(ncores), setup=setup, number=5, globals=globals())\n rslt[ncores] = time\n\n stmt = 'result = cube.spectral_smooth(kernel=convolution.Gaussian1DKernel(20.0), num_cores={0}, use_memmap=True, parallel=False)'\n rslt[0] = timeit.timeit(stmt=stmt.format(1), setup=setup, number=5, globals=globals())\n\n print()\n print(\"memmap=True shape={0}\".format(shape))\n print(rslt)\n\n# python 2.7 doesn't have tracemalloc\n@pytest.mark.skipif('not tracemallocOK or (sys.version_info.major==3 and sys.version_info.minor<6) or not NPY_VERSION_CHECK')\ndef test_memory_usage():\n \"\"\"\n Make sure that using memmaps happens where expected, for the most part, and\n that memory doesn't get overused.\n \"\"\"\n\n ntf = tempfile.NamedTemporaryFile()\n\n tracemalloc.start()\n\n snap1 = tracemalloc.take_snapshot()\n\n # create a 64 MB cube\n cube,_ = utilities.generate_gaussian_cube(shape=[200,200,200])\n sz = _.dtype.itemsize\n\n snap1b = tracemalloc.take_snapshot()\n diff = snap1b.compare_to(snap1, 'lineno')\n diffvals = np.array([dd.size_diff for dd in diff])\n # at this point, the generated cube should still exist in memory\n assert diffvals.max()*u.B >= 200**3*sz*u.B\n\n del _\n snap2 = tracemalloc.take_snapshot()\n diff = snap2.compare_to(snap1b, 'lineno')\n assert diff[0].size_diff*u.B < -0.3*u.MB\n\n cube.write(ntf.name, format='fits')\n\n # writing the cube should not occupy any more memory\n snap3 = tracemalloc.take_snapshot()\n diff = snap3.compare_to(snap2, 'lineno')\n assert sum([dd.size_diff for dd in diff])*u.B < 100*u.kB\n\n del cube\n\n # deleting the cube should remove the 64 MB from memory\n snap4 = tracemalloc.take_snapshot()\n diff = snap4.compare_to(snap3, 'lineno')\n assert diff[0].size_diff*u.B < -200**3*sz*u.B\n\n cube = SpectralCube.read(ntf.name, format='fits')\n\n # reading the cube from filename on disk should result in no increase in\n # memory use\n snap5 = tracemalloc.take_snapshot()\n diff = snap5.compare_to(snap4, 'lineno')\n assert diff[0].size_diff*u.B < 1*u.MB\n\n mask = cube.mask.include()\n\n snap6 = tracemalloc.take_snapshot()\n diff = snap6.compare_to(snap5, 'lineno')\n assert diff[0].size_diff*u.B >= mask.size*u.B\n\n filled_data = cube._get_filled_data(use_memmap=True)\n snap7 = tracemalloc.take_snapshot()\n diff = snap7.compare_to(snap6, 'lineno')\n assert diff[0].size_diff*u.B < 100*u.kB\n\n filled_data = cube._get_filled_data(use_memmap=False)\n snap8 = tracemalloc.take_snapshot()\n diff = snap8.compare_to(snap7, 'lineno')\n assert diff[0].size_diff*u.B > 10*u.MB\n\n del filled_data\n\n # cube is <1e8 bytes, so this is use_memmap=False\n filled_data = cube.filled_data[:]\n snap9 = tracemalloc.take_snapshot()\n diff = snap9.compare_to(snap6, 'lineno')\n assert diff[0].size_diff*u.B > 10*u.MB\n\n\n\n# python 2.7 doesn't have tracemalloc\n@pytest.mark.skipif('not tracemallocOK or (sys.version_info.major==3 and sys.version_info.minor<6) or not NPY_VERSION_CHECK')\ndef test_memory_usage_coordinates():\n \"\"\"\n Watch out for high memory usage on huge spatial files\n \"\"\"\n\n ntf = tempfile.NamedTemporaryFile()\n\n tracemalloc.start()\n\n snap1 = tracemalloc.take_snapshot()\n\n # create a \"flat\" cube\n cube,_ = utilities.generate_gaussian_cube(shape=[1,2000,2000])\n sz = _.dtype.itemsize\n\n snap1b = tracemalloc.take_snapshot()\n diff = snap1b.compare_to(snap1, 'lineno')\n diffvals = np.array([dd.size_diff for dd in diff])\n # at this point, the generated cube should still exist in memory\n assert diffvals.max()*u.B >= 2000**2*sz*u.B\n\n del _\n snap2 = tracemalloc.take_snapshot()\n diff = snap2.compare_to(snap1b, 'lineno')\n assert diff[0].size_diff*u.B < -0.3*u.MB\n\n print(cube)\n\n # printing the cube should not occupy any more memory\n # (it will allocate a few bytes for the cache, but should *not*\n # load the full 2000x2000 coordinate arrays for RA, Dec\n snap3 = tracemalloc.take_snapshot()\n diff = snap3.compare_to(snap2, 'lineno')\n assert sum([dd.size_diff for dd in diff])*u.B < 100*u.kB\n" ]
[ [ "numpy.array" ] ]
jkennedy-usgs/sgp-gsadjust
[ "929d650674b942d33168bcdaae7da07db175a1c4" ]
[ "gsadjust/data/adjustment.py" ]
[ "\"\"\"\r\ndata/adjustment.py\r\n===============\r\n\r\nGSadjust objects for Adjustment | AdjustmentOptions | AdjustmentResults: The first\r\ncontains instances of the latter two. Holds the input data, options, and results of\r\nthe network adjustment.\r\n\r\nThis software is preliminary, provisional, and is subject to revision. It is being\r\nprovided to meet the need for timely best science. The software has not received\r\nfinal approval by the U.S. Geological Survey (USGS). No warranty, expressed ore\r\nimplied, is made by the USGS or the U.S. Government as to the functionality of the\r\nsoftware and related material nor shall the fact of release constitute any such\r\nwarranty. The software is provided on the condition tha neither the USGS nor the U.S.\r\nGovernment shall be held liable for any damages resulting from the authorized or\r\nunauthorized use of the software. \"\"\"\r\nimport numpy as np\r\n\r\nclass AdjustmentResults:\r\n \"\"\"\r\n Object to store least-squares adjustment statistics.\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self.n_deltas, self.n_deltas_notused = 0, 0\r\n self.n_datums, self.n_datums_notused = 0, 0\r\n self.n_unknowns = 0\r\n self.max_dg_residual, self.min_dg_residual = 0, 0\r\n self.max_datum_residual, self.min_datum_residual = 0, 0\r\n self.avg_stdev = 0\r\n self.SDaposteriori = 0\r\n self.chi2, self.chi2c = 0, 0\r\n self.dof = 0\r\n self.cal_dic, self.netadj_drift_dic = {}, {}\r\n self.text = []\r\n\r\n def __bool__(self):\r\n if self.n_deltas == 0:\r\n return False\r\n else:\r\n return True\r\n\r\n def __str__(self):\r\n return_str = \"\"\r\n for attr in vars(self):\r\n if attr != \"text\":\r\n return_str += \"{}: {}\\n\".format(attr, getattr(self, attr))\r\n for line in self.text:\r\n return_str += line\r\n return return_str\r\n\r\n def get_report(self):\r\n \"\"\"Generate adjustment results.\r\n\r\n Used only by Adustment.results_string, where it's further appended with\r\n parameter results.\r\n\r\n Returns\r\n -------\r\n text : list\r\n List of strings for display on Adjust tab\r\n \"\"\"\r\n chi_result = \"accepted\" if self.chi2 < self.chi2c else \"rejected\"\r\n text = [\r\n f\"Number of unknowns: {self.n_unknowns:d}\",\r\n f\"Number of relative observations: {self.n_deltas:d}\",\r\n f\"Number of absolute observations: {self.n_datums:d}\",\r\n f\"Degrees of freedom (nobs-nunknowns): {self.dof:d}\",\r\n f\"SD a posteriori: {self.SDaposteriori:4f}\",\r\n f\"chi square value: {self.chi2:6.2f}\",\r\n f\"critical chi square value: {self.chi2c:6.2f}\",\r\n f\"Chi-test {chi_result}\",\r\n f\"Average standard deviation: {self.avg_stdev:.2f}\",\r\n f\"Maximum delta residual: {self.max_dg_residual:.2f}\",\r\n f\"Maximum absolute datum residual: {self.max_datum_residual:.2f}\",\r\n f\"Minimum absolute datum residual: {self.min_datum_residual:.2f}\",\r\n ]\r\n\r\n return text\r\n\r\n\r\nclass AdjustedStation:\r\n \"\"\"Object to store the network-adjusted gravity value at each station.\r\n\r\n Parameters\r\n ----------\r\n station : str\r\n Station name.\r\n g : float\r\n Adjusted gravity value.\r\n sd : float\r\n Standard deviation of the adjusted gravity value.\r\n\r\n Attributes\r\n ----------\r\n station : str\r\n Station name.\r\n g : float\r\n Adjusted gravity value.\r\n sd : float\r\n Standard deviation of the adjusted gravity value.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, station, g, sd):\r\n self.station = station\r\n self.g = g\r\n self.sd = sd\r\n\r\n def __str__(self):\r\n return \"{} {:0.2f} {:0.2f}\".format(self.station, self.g, self.sd)\r\n\r\n\r\nclass AdjustmentOptions:\r\n \"\"\"Object that holds options for least-squares adjustment.\r\n\r\n Options are set by gui.dialogs.AdjustOptions().\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self.use_sigma_prefactor = False\r\n self.sigma_prefactor = 1.0\r\n self.use_sigma_postfactor = False\r\n self.sigma_postfactor = 1.0\r\n self.use_sigma_add = False\r\n self.sigma_add = 0.0\r\n self.use_sigma_min = False\r\n self.sigma_min = 3.0\r\n self.alpha = 0.05\r\n self.cal_coeff = False\r\n self.adj_type = \"gravnet\"\r\n self.specify_cal_coeff = False\r\n self.meter_cal_dict = None\r\n\r\n def __str__(self):\r\n return_str = \"\"\r\n for attr in vars(self):\r\n return_str += \"{}: {}\\n\".format(attr, getattr(self, attr))\r\n return return_str\r\n\r\n\r\nclass Adjustment:\r\n \"\"\"Object that holds least-squares adjustment input matrices and results.\r\n\r\n There is one Adjustment object per Survey.\r\n\r\n Attributes\r\n __________\r\n A : ndarray\r\n model matrix (Nobs rel + NobsAbs) * Nunknowns\r\n P : ndarray\r\n Weight matrix (Nobs rel + NobsAbs) * (Nobs rel + NobsAbs)\r\n Obs observation vector (Nobs rel + NobsAbs)\r\n S StX=0\r\n X Unknowns\r\n r residuals (V)\r\n var Diagonal of the a posteriori covariance matrix\r\n VtPV\r\n dof degree of freedom (Nobs rel + NobsAbs - Nunknowns)\r\n \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"\r\n Initializes\r\n\r\n \"\"\"\r\n self.A = np.array([])\r\n self.P = np.array([])\r\n self.Obs = np.array([])\r\n self.S = np.array([])\r\n self.X = np.array([])\r\n self.r = np.array([])\r\n self.var = np.array([])\r\n self.VtPV = np.array([])\r\n self.SDaposteriori = 0\r\n self.dof = 0\r\n self.n_meters = 0\r\n self.meter_dic = dict()\r\n self.deltas = []\r\n self.datums = []\r\n self.g_dic = dict()\r\n self.sd_dic = dict()\r\n self.netadj_loop_keys = dict()\r\n self.sta_dic_ls = dict()\r\n self.adjustmentoptions = AdjustmentOptions()\r\n self.adjustmentresults = AdjustmentResults()\r\n\r\n def results_string(self):\r\n \"\"\"Generate results for display on Adjust tab.\r\n\r\n Returns\r\n -------\r\n text_out: str\r\n List of strings, one per row in the results box on the Adjust tab.\r\n\r\n \"\"\"\r\n try:\r\n if self.adjustmentresults.text: # Gravnet results\r\n return [x + \"\\n\" for x in self.adjustmentresults.text]\r\n elif self.adjustmentresults.n_unknowns > 0:\r\n text_out = self.adjustmentresults.get_report()\r\n if self.adjustmentoptions.cal_coeff:\r\n for k, v in self.adjustmentresults.cal_dic.items():\r\n text_out.append(\r\n f\"Calibration coefficient for meter {k}: {v[0]:.6f}\"\r\n f\" +/- {v[1]:.6f}\"\r\n )\r\n elif self.adjustmentoptions.specify_cal_coeff:\r\n for k, v in self.adjustmentoptions.meter_cal_dict.items():\r\n text_out.append(\r\n f\"Specified calibration coefficient for meter {k}: {v:.6f}\"\r\n )\r\n\r\n if self.netadj_loop_keys:\r\n text_out.append(\"Network adjustment drift coefficient(s):\")\r\n for loop in self.netadj_loop_keys.items():\r\n # this dict only has loops with netadj option\r\n text_out.append(\"Loop \" + loop[0] + \": \")\r\n for i in range(loop[1][1]):\r\n # degree of polynomial\r\n degree = self.X[\r\n len(self.sta_dic_ls) + self.n_meters + loop[1][0] + i\r\n ][0]\r\n if degree == 1:\r\n text_out.append(\r\n f\"Drift coefficient, degree {i + 1}: {degree:.3f}\"\r\n )\r\n else:\r\n text_out.append(\r\n f\"Drift coefficient, degree {i + 1}:\"\r\n f\" {degree:.3f} (µGal/day)\"\r\n )\r\n return text_out\r\n except (AttributeError, TypeError, ZeroDivisionError):\r\n return \"\"\r\n\r\n def python_lsq_inversion(self):\r\n \"\"\"Solve system of equations using numpy linalg.inv.\"\"\"\r\n At = np.transpose(self.A)\r\n N = At.dot(self.P).dot(self.A)\r\n # original PyGrav solution:\r\n # St = np.transpose(self.S)\r\n # self.X = np.linalg.inv(N+self.S.dot(St)).dot(At).dot(self.P).dot(self.Obs)\r\n self.X = np.linalg.inv(N).dot(At).dot(self.P).dot(self.Obs)\r\n self.r = self.A.dot(self.X) - self.Obs\r\n rt = np.transpose(self.r)\r\n self.VtPV = rt.dot(self.P).dot(self.r)\r\n var_post_norm = self.VtPV / self.dof\r\n self.SDaposteriori = np.sqrt(var_post_norm)\r\n cov_post = np.linalg.inv(N) * var_post_norm\r\n self.var = np.diagonal(cov_post)\r\n\r\n def lsq_statistics(self):\r\n \"\"\"Calculate and store chi^2, critical chi^2\"\"\"\r\n alpha = self.adjustmentoptions.alpha\r\n self.adjustmentresults.chi2 = self.VtPV[0][0]\r\n self.adjustmentresults.dof = self.dof\r\n self.adjustmentresults.SDaposteriori = np.sqrt(self.VtPV[0][0]/self.dof)\r\n t = np.sqrt(2 * np.log(1 / alpha))\r\n # I verified this produces the same values as scipy.stats.chi2.ppf\r\n chi_1_alpha = t - (2.515517 + 0.802853 * t + 0.010328 * t ** 2) / (\r\n 1 + 1.432788 * t + 0.189269 * t ** 2 + 0.001308 * t ** 3\r\n )\r\n dof = float(self.dof)\r\n self.adjustmentresults.chi2c = (\r\n dof * (chi_1_alpha * np.sqrt(2 / (9 * dof)) + 1 - 2.0 / (9 * dof)) ** 3\r\n )\r\n" ]
[ [ "numpy.log", "numpy.sqrt", "numpy.linalg.inv", "numpy.transpose", "numpy.array", "numpy.diagonal" ] ]
garyhowarth/deid2_dpsyn
[ "f8e9f30797f633254a3639378f8b318c1e2f655e" ]
[ "method/dpsyn.py" ]
[ "import copy\nimport multiprocessing as mp\nfrom typing import List, Tuple, Dict, KeysView\n\nimport numpy as np\nimport pandas as pd\nimport yaml\nfrom loguru import logger\nfrom numpy import linalg as LA\n\nfrom lib_dpsyn.consistent import Consistenter\nfrom lib_dpsyn.record_synthesizer import RecordSynthesizer\nfrom lib_dpsyn.view import View\nfrom method.synthesizer import Synthesizer\n\n\nclass DPSyn(Synthesizer):\n \"\"\"Note that it inherits the class Synthesizer,\n which already has the following attributes :\n (data: DataLoader, eps, delta, sensitivity) initialized\n \n \"\"\"\n synthesized_df = None\n\n # the magic value is set empirically and users may change in command lines\n update_iterations = 30\n\n attrs_view_dict = {}\n onehot_view_dict = {}\n\n attr_list = []\n domain_list = []\n attr_index_map = {}\n\n # despite phthon variables can be used without claiming its type, we import typing to ensure robustness\n Attrs = List[str]\n Domains = np.ndarray\n Marginals = Dict[Tuple[str], np.array]\n Clusters = Dict[Tuple[str], List[Tuple[str]]]\n d = None\n\n\n def obtain_consistent_marginals(self, priv_marginal_config, priv_split_method) -> Marginals:\n \"\"\"marginals are specified by a dict from attribute tuples to frequency (pandas) tables\n first obtain noisy marginals and make sure they are consistent\n\n \"\"\"\n\n # generate_all_pub_marginals() generates all the one and two way marginals of the public set which is implemented in DataLoader.py\n if self.data.pub_ref:\n pub_marginals = self.data.generate_all_pub_marginals()\n \n # get_noisy_marginals() is in synthesizer.py\n # which first calls generate_..._by_config(), and computes on priv_data to return marginal_sets, epss\n # (note that 'marginal_key' could be 'priv_all_one_way' or 'priv_all_two_way')\n # later it calls anonymize() which add noises to marginals\n # (what decides noises is 'priv_split_method') \n # priv_split_method[set_key]='lap' or....\n # Step 1: generate noisy marginals\n noisy_marginals = self.get_noisy_marginals(priv_marginal_config, priv_split_method)\n\n # since calculated on noisy marginals\n # we use mean function to estimate the number of synthesized records\n num_synthesize_records = np.mean([np.sum(x.values) for _, x in noisy_marginals.items()]).round().astype(np.int)\n print(\"------------------------> now we get the estimate of records' num by averaging from nosiy marginals:\", num_synthesize_records)\n \n \n \n # the list of all attributes' name(str) except the identifier attribute\n self.attr_list = self.data.obtain_attrs()\n # domain_list is an array recording the count of each attribute's candidate values\n self.domain_list = np.array([len(self.data.encode_schema[att]) for att in self.attr_list])\n \n # map the attribute str to its index in attr_list, for possible use\n # use enumerate to return Tuple(index, element) \n self.attr_index_map = {att: att_i for att_i, att in enumerate(self.attr_list)}\n\n\n # views are wrappers of marginals with additional functions for consistency\n # if there exist public dataset to refer to\n if self.data.pub_ref:\n pub_onehot_view_dict, pub_attr_view_dict = self.construct_views(pub_marginals)\n # Step 2: create some data structures\n noisy_onehot_view_dict, noisy_attr_view_dict = self.construct_views(noisy_marginals)\n \n # all_views is one-hot to view dict, views_dict is attribute to view dict\n # they have different format to satisfy the needs of consistenter and synthesiser\n # to fit in code when we do not have public things to utilize \n if not self.data.pub_ref:\n pub_onehot_view_dict = noisy_onehot_view_dict\n pub_attr_view_dict = noisy_attr_view_dict\n\n self.onehot_view_dict, self.attrs_view_dict = self.normalize_views(\n pub_onehot_view_dict,\n pub_attr_view_dict,\n noisy_attr_view_dict,\n self.attr_index_map,\n num_synthesize_records)\n\n # consist the noisy marginals to submit to some rules\n consistenter = Consistenter(self.onehot_view_dict, self.domain_list)\n consistenter.consist_views()\n\n # consistenter uses unnormalized counts;\n # after consistency, synthesizer uses normalized counts\n for _, view in self.onehot_view_dict.items():\n view.count /= sum(view.count)\n\n return noisy_marginals, num_synthesize_records\n\n\n # in experiment.py, tmp = synthesizer.synthesize(fixed_n=n)\n # in below function, we call synthesize_records()\n # it further utilize the lib function in record_synthesizer.py\n \n def synthesize(self, fixed_n=0) -> pd.DataFrame:\n \"\"\"synthesize a DataFrame in fixed_n size if denoted n!=0\n \n \"\"\"\n from experiment import MARGINAL_CONFIG\n with open(MARGINAL_CONFIG, 'r', encoding=\"utf-8\") as f:\n priv_marginal_config = yaml.load(f, Loader=yaml.FullLoader)\n priv_split_method = {} \n\n noisy_marginals, num_records = self.obtain_consistent_marginals(priv_marginal_config, priv_split_method)\n \n if fixed_n != 0:\n num_records = fixed_n\n # TODO: just based on the marginals to synthesize records\n # if in need, we can find clusters for synthesize; a cluster is a set of marginals closely connected\n # here we do not cluster and use all marginals as a single cluster\n clusters = self.cluster(self.attrs_view_dict)\n attrs = self.attr_list\n domains = self.domain_list\n print(\"------------------------> attributes: \")\n print(attrs)\n print(\"------------------------> domains: \")\n print(domains)\n print(\"------------------------> cluseters: \")\n print(clusters)\n print(\"********************* START SYNTHESIZING RECORDS ********************\")\n\n self.synthesize_records(attrs, domains, clusters, num_records)\n print(\"------------------------> synthetic dataframe before postprocessing: \")\n print(self.synthesized_df)\n return self.synthesized_df\n\n\n # we have a graph where nodes represent attributes and edges represent marginals,\n # it helps in terms of running time and accuracy if we do it cluster by cluster\n def synthesize_records(self, attrs: Attrs, domains: Domains, clusters: Clusters, num_synthesize_records: int):\n print(\"------------------------> num of synthesized records: \")\n print(num_synthesize_records)\n for cluster_attrs, list_marginal_attrs in clusters.items():\n logger.info(\"synthesizing for %s\" % (cluster_attrs,))\n\n # singleton_views = {attr: self.attr_view_dict[frozenset([attr])] for attr in attrs}\n singleton_views = {}\n for cur_attrs, view in self.attrs_view_dict.items():\n if len(cur_attrs) == 1:\n singleton_views[cur_attrs] = view\n\n synthesizer = RecordSynthesizer(attrs, domains, num_synthesize_records)\n synthesizer.initialize_records(list_marginal_attrs, singleton_views=singleton_views)\n attrs_index_map = {attrs: index for index, attrs in enumerate(list_marginal_attrs)}\n\n from experiment import UPDATE_ITERATIONS\n self.update_iterations = UPDATE_ITERATIONS\n\n for update_iteration in range(self.update_iterations):\n logger.info(\"update round: %d\" % (update_iteration,))\n\n synthesizer.update_alpha(update_iteration)\n sorted_error_attrs = synthesizer.update_order(update_iteration, self.attrs_view_dict,\n list_marginal_attrs)\n\n for attrs in sorted_error_attrs:\n attrs_i = attrs_index_map[attrs]\n synthesizer.update_records_prepare(self.attrs_view_dict[attrs])\n synthesizer.update_records(self.attrs_view_dict[attrs], attrs_i)\n if self.synthesized_df is None:\n self.synthesized_df = synthesizer.df\n else:\n self.synthesized_df.loc[:, cluster_attrs] = synthesizer.df.loc[:, cluster_attrs]\n\n\n @staticmethod\n def calculate_l1_errors(records, target_marginals, attrs_view_dict):\n l1_T_Ms = []\n l1_T_Ss = []\n l1_M_Ss = []\n\n for cur_attrs, target_marginal_pd in target_marginals.items():\n view = attrs_view_dict[cur_attrs]\n syn_marginal = view.count_records_general(records)\n target_marginal = target_marginal_pd.values.flatten()\n\n T = target_marginal / np.sum(target_marginal)\n M = view.count\n S = syn_marginal / np.sum(syn_marginal)\n\n l1_T_Ms.append(LA.norm(T - M, 1))\n l1_T_Ss.append(LA.norm(T - S, 1))\n l1_M_Ss.append(LA.norm(M - S, 1))\n\n return np.mean(l1_T_Ms), np.mean(l1_T_Ss), np.mean(l1_M_Ss)\n\n @staticmethod\n def normalize_views(pub_onehot_view_dict: Dict, pub_attr_view_dict, noisy_view_dict, attr_index_map, num_synthesize_records) -> Tuple[Dict, Dict]:\n pub_weight = 0.00\n noisy_weight = 1 - pub_weight\n\n views_dict = pub_attr_view_dict\n onehot_view_dict = pub_onehot_view_dict\n for view_att, view in noisy_view_dict.items():\n if view_att in views_dict:\n views_dict[view_att].count = pub_weight * pub_attr_view_dict[view_att].count + noisy_weight * view.count\n views_dict[view_att].weight_coeff = pub_weight * pub_attr_view_dict[\n view_att].weight_coeff + noisy_weight * view.weight_coeff\n else:\n views_dict[view_att] = view\n view_onehot = DPSyn.one_hot(view_att, attr_index_map)\n onehot_view_dict[tuple(view_onehot)] = view\n return onehot_view_dict, views_dict\n\n @staticmethod\n def obtain_singleton_views(attrs_view_dict):\n singleton_views = {}\n for cur_attrs, view in attrs_view_dict.items():\n # other use \n # puma and year won't be there because they only appear together (size=2)\n if len(cur_attrs) == 1:\n singleton_views[cur_attrs] = view\n return singleton_views\n\n\n def construct_views(self, marginals: Marginals) -> Tuple[Dict, Dict]:\n \"\"\"construct views for each marginal item,\n return 2 dictionaries, onehot2view and attr2view\n\n \"\"\"\n onehot_view_dict = {}\n attr_view_dict = {}\n\n for marginal_att, marginal_value in marginals.items():\n # since one_hot is @staticmethod, we can call it by DPSyn.one_hot\n # return value is an array marked \n view_onehot = DPSyn.one_hot(marginal_att, self.attr_index_map)\n\n # View() is in lib_dpsyn\\view.py \n # domain_list is an array recording the count of each attribute's candidate values\n view = View(view_onehot, self.domain_list)\n\n # we use flatten to create a one-dimension array which serves for when the marginal is two-way\n view.count = marginal_value.values.flatten()\n\n # we create two dictionaries to map ... to view\n onehot_view_dict[tuple(view_onehot)] = view\n attr_view_dict[marginal_att] = view\n\n # obviously if things go well, it should match\n if not len(view.count) == view.domain_size:\n raise Exception('no match')\n\n return onehot_view_dict, attr_view_dict\n\n\n def log_result(self, result):\n self.d.append(result)\n\n @staticmethod\n def build_attr_set(attrs: KeysView[Tuple[str]]) -> Tuple[str]:\n attrs_set = set()\n\n for attr in attrs:\n attrs_set.update(attr)\n\n return tuple(attrs_set)\n\n # simple clustering: just build the data structure; not doing any clustering\n def cluster(self, marginals: Marginals) -> Clusters:\n clusters = {}\n keys = []\n for marginal_attrs, _ in marginals.items():\n keys.append(marginal_attrs)\n\n clusters[DPSyn.build_attr_set(marginals.keys())] = keys\n return clusters\n\n @staticmethod\n def one_hot(cur_att, attr_index_map):\n # it marks the attributes included in cur_attr by one-hot way in a len=attr_index_map array\n # return value is an array marked \n cur_view_key = [0] * len(attr_index_map)\n for attr in cur_att:\n cur_view_key[attr_index_map[attr]] = 1\n return cur_view_key\n\n" ]
[ [ "numpy.mean", "numpy.sum", "numpy.linalg.norm" ] ]
mragungsetiaji/alsi
[ "c33f0e1ca1ee148ff3c95474dd4c36166ece583a" ]
[ "alsi/recommender_base.py" ]
[ "\nimport itertools\nfrom abc import ABCMeta, abstractmethod\nimport numpy as np\n\nclass RecommenderBase(object):\n\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def fit(self, item_users):\n pass\n\n @abstractmethod\n def recommend(self, userid, user_items,\n N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False):\n pass\n\n @abstractmethod\n def rank_items(self, userid, user_items, selected_items, recalculate_user=False):\n pass\n\n @abstractmethod\n def similar_users(self, userid, N=10):\n pass\n\n @abstractmethod\n def similar_items(self, itemid, N=10):\n pass\n\nclass MatrixFactorizationBase(RecommenderBase):\n \n def __init__(self):\n\n self.item_factors = None\n self.user_factors = None\n self._user_norms, self._item_norms = None, None\n\n def recommend(self, userid, user_items,\n N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False):\n user = self._user_factor(userid, user_items, recalculate_user)\n\n if filter_already_liked_items is True:\n liked = set(user_items[userid].indices)\n else:\n liked = set()\n scores = self.item_factors.dot(user)\n if filter_items:\n liked.update(filter_items)\n\n count = N + len(liked)\n if count < len(scores):\n ids = np.argpartition(scores, -count)[-count:]\n best = sorted(zip(ids, scores[ids]), key=lambda x: -x[1])\n else:\n best = sorted(enumerate(scores), key=lambda x: -x[1])\n return list(itertools.islice((rec for rec in best if rec[0] not in liked), N))\n\n def rank_items(self, userid, user_items, selected_items, recalculate_user=False):\n user = self._user_factor(userid, user_items, recalculate_user)\n\n if max(selected_items) >= user_items.shape[1] or min(selected_items) < 0:\n raise IndexError(\"Some of selected itemids are not in the model\")\n\n item_factors = self.item_factors[selected_items]\n scores = item_factors.dot(user)\n\n return sorted(zip(selected_items, scores), key=lambda x: -x[1])\n\n recommend.__doc__ = RecommenderBase.recommend.__doc__\n\n def _user_factor(self, userid, user_items, recalculate_user=False):\n if recalculate_user:\n return self.recalculate_user(userid, user_items)\n else:\n return self.user_factors[userid]\n\n def recalculate_user(self, userid, user_items):\n raise NotImplementedError(\"recalculate_user is not supported with this model\")\n\n def similar_users(self, userid, N=10):\n factor = self.user_factors[userid]\n factors = self.user_factors\n norms = self.user_norms\n\n return self._get_similarity_score(factor, factors, norms, N)\n\n similar_users.__doc__ = RecommenderBase.similar_users.__doc__\n\n def similar_items(self, itemid, N=10):\n factor = self.item_factors[itemid]\n factors = self.item_factors\n norms = self.item_norms\n\n return self._get_similarity_score(factor, factors, norms, N)\n\n similar_items.__doc__ = RecommenderBase.similar_items.__doc__\n\n def _get_similarity_score(self, factor, factors, norms, N):\n scores = factors.dot(factor) / norms\n best = np.argpartition(scores, -N)[-N:]\n return sorted(zip(best, scores[best]), key=lambda x: -x[1])\n\n @property\n def user_norms(self):\n if self._user_norms is None:\n self._user_norms = np.linalg.norm(self.user_factors, axis=-1)\n self._user_norms[self._user_norms == 0] = 1e-10\n return self._user_norms\n\n @property\n def item_norms(self):\n if self._item_norms is None:\n self._item_norms = np.linalg.norm(self.item_factors, axis=-1)\n self._item_norms[self._item_norms == 0] = 1e-10\n return self._item_norms\n" ]
[ [ "numpy.linalg.norm", "numpy.argpartition" ] ]
markveillette/data-driven-advection
[ "1535b792d8196f25837c51cda7a152ab405f6f81" ]
[ "datadrivenpdes/core/tensor_ops.py" ]
[ "# python3\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tensor operations.\"\"\"\nimport collections\nimport typing\nfrom typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union\n\nimport numpy as np\nimport tree\nfrom datadrivenpdes.core import grids\nfrom datadrivenpdes.core import states\nimport tensorflow as tf\n\n\ndef auto_nest(func):\n \"\"\"Automatically support nested tensors in the first argument.\"\"\"\n def wrapper(tensors, *args, **kwargs):\n return tree.map_structure(\n lambda x: func(x, *args, **kwargs), tensors)\n return wrapper\n\n\ndef _normalize_axis(axis: int, ndim: int) -> int:\n if not -ndim <= axis < ndim:\n raise ValueError('invalid axis {} for ndim {}'.format(axis, ndim))\n if axis < 0:\n axis += ndim\n return axis\n\n\ndef _roll_once(\n tensor: tf.Tensor,\n shift: int,\n axis: int,\n) -> tf.Tensor:\n \"\"\"Roll along a single dimension like tf.roll().\"\"\"\n if not shift:\n return tensor\n axis = _normalize_axis(axis, len(tensor.shape))\n slice_left = (slice(None),) * axis + (slice(-shift, None),)\n slice_right = (slice(None),) * axis + (slice(None, -shift),)\n return tf.concat([tensor[slice_left], tensor[slice_right]], axis=axis)\n\n\n@auto_nest\ndef roll(\n tensor: tf.Tensor,\n shift: Union[int, Sequence[int]],\n axis: Union[int, Sequence[int]],\n) -> tf.Tensor:\n \"\"\"Like tf.roll(), but runs on GPU as a well as CPU.\"\"\"\n if isinstance(axis, int):\n axis = [axis]\n if isinstance(shift, int):\n shift = [shift]\n result = tensor\n for axis_element, shift_element in zip(axis, shift):\n result = _roll_once(result, shift_element, axis_element)\n return result\n\n\n@auto_nest\ndef roll_2d(\n tensor: tf.Tensor,\n shifts: Tuple[int, int],\n axes: Tuple[int, int] = (-2, -1)\n) -> tf.Tensor:\n \"\"\"Roll by default along the last two axes.\"\"\"\n return roll(tensor, shifts, axes)\n\n\ndef _pad_periodic_by_axis(\n tensor: tf.Tensor, padding: Sequence[int], axis: int,\n) -> tf.Tensor:\n \"\"\"Periodic padding along one axis.\"\"\"\n ndim = len(tensor.shape)\n\n axis = _normalize_axis(axis, ndim)\n if len(padding) != 2:\n raise ValueError('padding must have length 2: {}'.format(padding))\n if any(pad < 0 for pad in padding):\n raise ValueError('padding must be positive: {}'.format(padding))\n pad_left, pad_right = padding\n\n slice_left = [slice(None)] * ndim\n slice_left[axis] = slice(-pad_left, None)\n slice_left = tuple(slice_left)\n slice_right = [slice(None)] * ndim\n slice_right[axis] = slice(None, pad_right)\n slice_right = tuple(slice_right)\n\n if pad_left and pad_right:\n tensors = [tensor[slice_left], tensor, tensor[slice_right]]\n return tf.concat(tensors, axis=axis)\n elif pad_left:\n tensors = [tensor[slice_left], tensor]\n return tf.concat(tensors, axis=axis)\n elif pad_right:\n tensors = [tensor, tensor[slice_right]]\n return tf.concat(tensors, axis=axis)\n else:\n return tensor\n\n\n@auto_nest\ndef pad_periodic(\n tensor: tf.Tensor, paddings: Sequence[Sequence[int]],\n) -> tf.Tensor:\n \"\"\"Periodic padding, with an API like tf.pad().\"\"\"\n result = tensor\n for axis, padding in enumerate(paddings):\n result = _pad_periodic_by_axis(result, padding, axis)\n return result\n\n\ndef paddings_for_conv2d(\n kernel_size: Sequence[int],\n shifts: Sequence[int] = (0, 0),\n) -> List[Tuple[int, int]]:\n \"\"\"Paddings for a conv2d valid convolution to return the original shape.\"\"\"\n if len(kernel_size) != 2 or len(shifts) != 2:\n raise ValueError('kernel_size and shifts must have length 2')\n\n paddings = [(0, 0)]\n for size, shift in zip(kernel_size, shifts):\n pad_left = (size - shift) // 2\n paddings.append((pad_left, size - pad_left - 1))\n paddings += [(0, 0)]\n return paddings\n\n\n@auto_nest\ndef pad_periodic_2d(\n tensor: tf.Tensor,\n kernel_size: Sequence[int],\n shifts: Sequence[int] = (0, 0),\n) -> tf.Tensor:\n \"\"\"Pad a tensor in preparation for a conv2d valid convolution.\"\"\"\n if len(tensor.shape) != 4:\n raise ValueError('tensor has wrong number of dimensions: {}'.format(tensor))\n\n paddings = paddings_for_conv2d(kernel_size, shifts)\n result = pad_periodic(tensor, paddings)\n return result\n\n\n@auto_nest\ndef extract_patches_2d(\n tensor: tf.Tensor,\n kernel_size: Sequence[int],\n shifts: Sequence[int] = (0, 0),\n) -> tf.Tensor:\n \"\"\"Create a tensor of patches for use with finite difference coefficients.\n\n Args:\n tensor: 2D or 3D tensor representing a grid variable.\n kernel_size: size of the stencil along the x and y directions.\n shifts: shifts of the stencil along the x and y directions.\n\n Returns:\n 4D Tensor composed of stencil shifts stacked along the last axis.\n \"\"\"\n if len(tensor.shape) == 2:\n added_batch = True\n tensor = tensor[tf.newaxis, ...]\n else:\n added_batch = False\n\n if len(tensor.shape) != 3:\n raise ValueError('tensor has wrong number of dimensions: {}'.format(tensor))\n\n paddings = paddings_for_conv2d(kernel_size, shifts)[:-1]\n padded = pad_periodic(tensor, paddings)\n\n size_x, size_y = kernel_size\n extracted = tf.compat.v1.extract_image_patches(padded[..., tf.newaxis],\n [1, size_x, size_y, 1],\n strides=[1, 1, 1, 1],\n rates=[1, 1, 1, 1],\n padding='VALID')\n\n if added_batch:\n result = tf.squeeze(extracted, axis=0)\n else:\n result = extracted\n\n return result\n\n\nTensorLike = Union[np.ndarray, tf.Tensor]\n\n\ndef regrid_mean(\n tensor: TensorLike,\n factor: int,\n offset: int = 0,\n axis: int = -1,\n) -> tf.Tensor:\n \"\"\"Resample data to a lower-resolution by averaging data point.\n\n Args:\n tensor: input tensor.\n factor: integer factor by which to reduce the size of the given axis.\n offset: integer offset at which to place blocks.\n axis: integer axis to resample over.\n\n Returns:\n Array with averaged data along axis.\n\n Raises:\n ValueError: if the original axis size is not evenly divided by factor.\n \"\"\"\n if offset:\n # TODO(shoyer): support this with roll()\n raise NotImplementedError('offset not supported yet')\n\n tensor = tf.convert_to_tensor(tensor)\n shape = tensor.shape.as_list()\n axis = _normalize_axis(axis, len(shape))\n multiple, residual = divmod(shape[axis], factor)\n if residual:\n raise ValueError('resample factor {} must divide size {}'\n .format(factor, shape[axis]))\n\n new_shape = shape[:axis] + [multiple, factor] + shape[axis+1:]\n new_shape = [-1 if size is None else size for size in new_shape]\n\n return tf.reduce_mean(tf.reshape(tensor, new_shape), axis=axis+1)\n\n\ndef regrid_subsample(\n tensor: TensorLike,\n factor: int,\n offset: int = 0,\n axis: int = -1) -> tf.Tensor:\n \"\"\"Resample data to a lower-resolution by subsampling data-points.\n\n Args:\n tensor: input tensor.\n factor: integer factor by which to reduce the size of the given axis.\n offset: integer offset at which to subsample.\n axis: integer axis to resample over.\n\n Returns:\n Array with subsampled data along axis.\n\n Raises:\n ValueError: if the original axis size is not evenly divided by factor.\n \"\"\"\n tensor = tf.convert_to_tensor(tensor)\n shape = tensor.shape.as_list()\n axis = _normalize_axis(axis, len(shape))\n residual = shape[axis] % factor\n if residual:\n raise ValueError('resample factor {} must divide size {}'\n .format(factor, shape[axis]))\n\n if offset < 0 or offset >= factor:\n raise ValueError('invalid offset {} not in [0, {})'.format(offset, factor))\n\n indexer = [slice(None)] * len(shape)\n indexer[axis] = slice(offset, None, factor)\n\n return tensor[tuple(indexer)]\n\n\ndef _regrid_tensor(\n tensor: tf.Tensor,\n definition: states.StateDefinition,\n factors: Tuple[int, ...],\n axes: Tuple[int, ...],\n) -> tf.Tensor:\n \"\"\"Regrid a Tensor along all its axes.\"\"\"\n result = tensor\n for factor, cell_offset, axis in zip(factors, definition.offset, axes):\n # TODO(shoyer): add a notion of the geometry (cell vs face variables)\n # directly into the data model in StateDefinition?\n if cell_offset == 0:\n result = regrid_mean(result, factor, offset=0, axis=axis)\n elif cell_offset == 1:\n offset = factor - 1\n result = regrid_subsample(result, factor, offset, axis)\n else:\n raise ValueError('unsupported offset: {}'.format(cell_offset))\n return result\n\n\n# pylint: disable=unused-argument\n@typing.overload\ndef regrid(\n tensor: TensorLike,\n definition: states.StateDefinition,\n source: grids.Grid,\n destination: grids.Grid\n) -> tf.Tensor:\n pass\n\n\n@typing.overload\ndef regrid( # pylint: disable=function-redefined\n tensor: Mapping[str, TensorLike],\n definition: Mapping[str, states.StateDefinition],\n source: grids.Grid,\n destination: grids.Grid\n) -> Dict[str, tf.Tensor]:\n pass\n# pylint: enable=unused-argument\n\n\ndef regrid(inputs, definitions, source, destination): # pylint: disable=function-redefined\n \"\"\"Regrid to lower resolution using an appropriate method.\n\n This function assumes that quantities at staggered grid locations should be\n regridded using subsampling instead of averages. This is appropriate for\n typical finite difference/volume discretizations.\n\n Args:\n inputs: state(s) to regrid.\n definitions: definition(s) of this tensor quantity.\n source: fine resolution Grid.\n destination: coarse resolution Grid.\n\n Returns:\n Tensor(s) representing the input state at lower resolution.\n\n Raises:\n ValueError: Grids sizes are not compatible for downsampling.\n \"\"\"\n factors, residuals = zip(*[\n divmod(current_size, new_size)\n for current_size, new_size in zip(source.shape, destination.shape)\n ])\n\n if any(residuals):\n raise ValueError('grids are not aligned: {} vs {}'\n .format(source, destination))\n\n axes = tuple(-(n + 1) for n in reversed(range(source.ndim)))\n\n if isinstance(inputs, collections.Mapping):\n result = {k: _regrid_tensor(inputs[k], definitions[k], factors, axes)\n for k in inputs}\n else:\n result = _regrid_tensor(inputs, definitions, factors, axes)\n return result # pytype: disable=bad-return-type\n\n\ndef regrid_masked_mean_2d(\n tensor: TensorLike,\n mask: TensorLike,\n source: grids.Grid,\n destination: grids.Grid,\n) -> tf.Tensor:\n \"\"\"Regrid using the mean of unmasked elements.\n\n The input tensor is regridded over the last two axes. Entirely masked regions\n are set to zero.\n\n Args:\n tensor: tensor to regrid.\n mask: valid elements to include in the mean.\n source: fine resolution Grid.\n destination: coarse resolution Grid.\n\n Returns:\n Averaged tensor.\n \"\"\"\n tensor = tf.convert_to_tensor(tensor)\n mask = tf.convert_to_tensor(mask)\n\n shape = tensor.shape.as_list()\n\n new_shape = shape[:-2]\n for current_size, new_size in zip(source.shape, destination.shape):\n factor, residual = divmod(current_size, new_size)\n if residual:\n raise ValueError('grids are not aligned')\n new_shape.extend([new_size, factor])\n\n new_shape = [-1 if size is None else size for size in new_shape]\n\n mask = tf.cast(mask, tensor.dtype)\n total = tf.reduce_sum(tf.reshape(tensor * mask, new_shape), axis=(-3, -1))\n count = tf.reduce_sum(tf.reshape(mask, new_shape), axis=(-3, -1))\n return total / tf.maximum(count, 1.0)\n\n\n@auto_nest\ndef moveaxis(tensor: tf.Tensor, source: int, destination: int) -> tf.Tensor:\n \"\"\"TensorFlow version of np.moveaxis.\"\"\"\n ndim = len(tensor.shape)\n source = _normalize_axis(source, ndim)\n destination = _normalize_axis(destination, ndim)\n order = [n for n in range(ndim) if n != source]\n order.insert(destination, source)\n return tf.transpose(tensor, order)\n\n\n@auto_nest\ndef swap_xy(tensor: tf.Tensor) -> tf.Tensor:\n \"\"\"Swap x and y dimensions on a tensor.\"\"\"\n return moveaxis(tensor, -2, -1)\n\n\n@auto_nest\ndef stack_all_contiguous_slices(\n tensor: tf.Tensor, slice_size: int, new_axis: int = 0,\n) -> tf.Tensor:\n \"\"\"Stack all contiguous slices along the first axis of a tensor.\"\"\"\n size = tensor.shape[0]\n return tf.stack([tensor[i : i+slice_size]\n for i in range(size - slice_size + 1)], axis=new_axis)\n\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.transpose", "tensorflow.maximum", "tensorflow.compat.v1.extract_image_patches", "tensorflow.cast", "tensorflow.squeeze", "tensorflow.reshape" ] ]
drewoldag/astropy
[ "2023292bc5f1d29e95dbef9e978cdb307ae1ba3d" ]
[ "astropy/coordinates/representation.py" ]
[ "\"\"\"\nIn this module, we define the coordinate representation classes, which are\nused to represent low-level cartesian, spherical, cylindrical, and other\ncoordinates.\n\"\"\"\n\nimport abc\nimport functools\nimport operator\nfrom collections import OrderedDict\nimport inspect\nimport warnings\n\nimport numpy as np\nimport astropy.units as u\n\nfrom .angles import Angle, Longitude, Latitude\nfrom .distances import Distance\nfrom astropy._erfa import ufunc as erfa_ufunc\nfrom astropy.utils import ShapedLikeNDArray, classproperty\nfrom astropy.utils.data_info import MixinInfo\nfrom astropy.utils.exceptions import DuplicateRepresentationWarning\n\n\n__all__ = [\"BaseRepresentationOrDifferential\", \"BaseRepresentation\",\n \"CartesianRepresentation\", \"SphericalRepresentation\",\n \"UnitSphericalRepresentation\", \"RadialRepresentation\",\n \"PhysicsSphericalRepresentation\", \"CylindricalRepresentation\",\n \"BaseDifferential\", \"CartesianDifferential\",\n \"BaseSphericalDifferential\", \"BaseSphericalCosLatDifferential\",\n \"SphericalDifferential\", \"SphericalCosLatDifferential\",\n \"UnitSphericalDifferential\", \"UnitSphericalCosLatDifferential\",\n \"RadialDifferential\", \"CylindricalDifferential\",\n \"PhysicsSphericalDifferential\"]\n\n# Module-level dict mapping representation string alias names to classes.\n# This is populated by the metaclass init so all representation and differential\n# classes get registered automatically.\nREPRESENTATION_CLASSES = {}\nDIFFERENTIAL_CLASSES = {}\n# set for tracking duplicates\nDUPLICATE_REPRESENTATIONS = set()\n\n# a hash for the content of the above two dicts, cached for speed.\n_REPRDIFF_HASH = None\n\n\ndef _fqn_class(cls):\n ''' Get the fully qualified name of a class '''\n return cls.__module__ + '.' + cls.__qualname__\n\n\ndef get_reprdiff_cls_hash():\n \"\"\"\n Returns a hash value that should be invariable if the\n `REPRESENTATION_CLASSES` and `DIFFERENTIAL_CLASSES` dictionaries have not\n changed.\n \"\"\"\n global _REPRDIFF_HASH\n if _REPRDIFF_HASH is None:\n _REPRDIFF_HASH = (hash(tuple(REPRESENTATION_CLASSES.items())) +\n hash(tuple(DIFFERENTIAL_CLASSES.items())))\n return _REPRDIFF_HASH\n\n\ndef _invalidate_reprdiff_cls_hash():\n global _REPRDIFF_HASH\n _REPRDIFF_HASH = None\n\n\ndef _array2string(values, prefix=''):\n # Work around version differences for array2string.\n kwargs = {'separator': ', ', 'prefix': prefix}\n kwargs['formatter'] = {}\n\n return np.array2string(values, **kwargs)\n\n\ndef _combine_xyz(x, y, z, xyz_axis=0):\n \"\"\"\n Combine components ``x``, ``y``, ``z`` into a single Quantity array.\n\n Parameters\n ----------\n x, y, z : `~astropy.units.Quantity`\n The individual x, y, and z components.\n xyz_axis : int, optional\n The axis in the final array along which the x, y, z components\n should be stored (default: 0).\n\n Returns\n -------\n xyz : `~astropy.units.Quantity`\n With dimension 3 along ``xyz_axis``, i.e., using the default of ``0``,\n the shape will be ``(3,) + x.shape``.\n \"\"\"\n # Get x, y, z to the same units (this is very fast for identical units)\n # since np.stack cannot deal with quantity.\n cls = x.__class__\n unit = x.unit\n x = x.value\n y = y.to_value(unit)\n z = z.to_value(unit)\n\n xyz = np.stack([x, y, z], axis=xyz_axis)\n return cls(xyz, unit=unit, copy=False)\n\n\nclass BaseRepresentationOrDifferentialInfo(MixinInfo):\n \"\"\"\n Container for meta information like name, description, format. This is\n required when the object is used as a mixin column within a table, but can\n be used as a general way to store meta information.\n \"\"\"\n attrs_from_parent = {'unit'} # Indicates unit is read-only\n _supports_indexing = False\n\n @staticmethod\n def default_format(val):\n # Create numpy dtype so that numpy formatting will work.\n components = val.components\n values = tuple(getattr(val, component).value for component in components)\n a = np.empty(getattr(val, 'shape', ()),\n [(component, value.dtype) for component, value\n in zip(components, values)])\n for component, value in zip(components, values):\n a[component] = value\n return str(a)\n\n @property\n def _represent_as_dict_attrs(self):\n return self._parent.components\n\n @property\n def unit(self):\n if self._parent is None:\n return None\n\n unit = self._parent._unitstr\n return unit[1:-1] if unit.startswith('(') else unit\n\n def new_like(self, reps, length, metadata_conflicts='warn', name=None):\n \"\"\"\n Return a new instance like ``reps`` with ``length`` rows.\n\n This is intended for creating an empty column object whose elements can\n be set in-place for table operations like join or vstack.\n\n Parameters\n ----------\n reps : list\n List of input representations or differentials.\n length : int\n Length of the output column object\n metadata_conflicts : str ('warn'|'error'|'silent')\n How to handle metadata conflicts\n name : str\n Output column name\n\n Returns\n -------\n col : Representation or Differential\n Empty instance of this class consistent with ``cols``\n\n \"\"\"\n\n # Get merged info attributes like shape, dtype, format, description, etc.\n attrs = self.merge_cols_attributes(reps, metadata_conflicts, name,\n ('meta', 'description'))\n # Make a new representation or differential with the desired length\n # using the _apply / __getitem__ machinery to effectively return\n # rep0[[0, 0, ..., 0, 0]]. This will have the right shape, and\n # include possible differentials.\n indexes = np.zeros(length, dtype=np.int64)\n out = reps[0][indexes]\n\n # Use __setitem__ machinery to check whether all representations\n # can represent themselves as this one without loss of information.\n for rep in reps[1:]:\n try:\n out[0] = rep[0]\n except Exception as err:\n raise ValueError(f'input representations are inconsistent: {err}')\n\n # Set (merged) info attributes.\n for attr in ('name', 'meta', 'description'):\n if attr in attrs:\n setattr(out.info, attr, attrs[attr])\n\n return out\n\n\nclass BaseRepresentationOrDifferential(ShapedLikeNDArray):\n \"\"\"3D coordinate representations and differentials.\n\n Parameters\n ----------\n comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass\n The components of the 3D point or differential. The names are the\n keys and the subclasses the values of the ``attr_classes`` attribute.\n copy : bool, optional\n If `True` (default), arrays will be copied; if `False`, they will be\n broadcast together but not use new memory.\n \"\"\"\n\n # Ensure multiplication/division with ndarray or Quantity doesn't lead to\n # object arrays.\n __array_priority__ = 50000\n\n info = BaseRepresentationOrDifferentialInfo()\n\n def __init__(self, *args, **kwargs):\n # make argument a list, so we can pop them off.\n args = list(args)\n components = self.components\n if (args and isinstance(args[0], self.__class__)\n and all(arg is None for arg in args[1:])):\n rep_or_diff = args[0]\n copy = kwargs.pop('copy', True)\n attrs = [getattr(rep_or_diff, component)\n for component in components]\n if 'info' in rep_or_diff.__dict__:\n self.info = rep_or_diff.info\n\n if kwargs:\n raise TypeError(f'unexpected keyword arguments for case '\n f'where class instance is passed in: {kwargs}')\n\n else:\n attrs = []\n for component in components:\n try:\n attr = args.pop(0) if args else kwargs.pop(component)\n except KeyError:\n raise TypeError(f'__init__() missing 1 required positional '\n f'argument: {component!r}')\n\n if attr is None:\n raise TypeError(f'__init__() missing 1 required positional '\n f'argument: {component!r} (or first '\n f'argument should be an instance of '\n f'{self.__class__.__name__}).')\n\n attrs.append(attr)\n\n copy = args.pop(0) if args else kwargs.pop('copy', True)\n\n if args:\n raise TypeError(f'unexpected arguments: {args}')\n\n if kwargs:\n for component in components:\n if component in kwargs:\n raise TypeError(f\"__init__() got multiple values for \"\n f\"argument {component!r}\")\n\n raise TypeError(f'unexpected keyword arguments: {kwargs}')\n\n # Pass attributes through the required initializing classes.\n attrs = [self.attr_classes[component](attr, copy=False)\n for component, attr in zip(components, attrs)]\n try:\n attrs = np.broadcast_arrays(*attrs, subok=True)\n except ValueError:\n if len(components) <= 2:\n c_str = ' and '.join(components)\n else:\n c_str = ', '.join(components[:2]) + ', and ' + components[2]\n raise ValueError(\"Input parameters {} cannot be broadcast\"\n .format(c_str))\n\n if copy:\n attrs = [attr.copy() for attr in attrs]\n\n # Set private attributes for the attributes. (If not defined explicitly\n # on the class, the metaclass will define properties to access these.)\n for component, attr in zip(components, attrs):\n setattr(self, '_' + component, attr)\n\n @classmethod\n def get_name(cls):\n \"\"\"Name of the representation or differential.\n\n In lower case, with any trailing 'representation' or 'differential'\n removed. (E.g., 'spherical' for\n `~astropy.coordinates.SphericalRepresentation` or\n `~astropy.coordinates.SphericalDifferential`.)\n \"\"\"\n name = cls.__name__.lower()\n\n if name.endswith('representation'):\n name = name[:-14]\n elif name.endswith('differential'):\n name = name[:-12]\n\n return name\n\n # The two methods that any subclass has to define.\n @classmethod\n @abc.abstractmethod\n def from_cartesian(cls, other):\n \"\"\"Create a representation of this class from a supplied Cartesian one.\n\n Parameters\n ----------\n other : `CartesianRepresentation`\n The representation to turn into this class\n\n Returns\n -------\n representation : object of this class\n A new representation of this class's type.\n \"\"\"\n # Note: the above docstring gets overridden for differentials.\n raise NotImplementedError()\n\n @abc.abstractmethod\n def to_cartesian(self):\n \"\"\"Convert the representation to its Cartesian form.\n\n Note that any differentials get dropped.\n\n Returns\n -------\n cartrepr : `CartesianRepresentation`\n The representation in Cartesian form.\n \"\"\"\n # Note: the above docstring gets overridden for differentials.\n raise NotImplementedError()\n\n @property\n def components(self):\n \"\"\"A tuple with the in-order names of the coordinate components.\"\"\"\n return tuple(self.attr_classes)\n\n def __eq__(self, value):\n \"\"\"Equality operator\n\n This implements strict equality and requires that the representation\n classes are identical and that the representation data are exactly equal.\n \"\"\"\n if self.__class__ is not value.__class__:\n raise TypeError(f'cannot compare: objects must have same class: '\n f'{self.__class__.__name__} vs. '\n f'{value.__class__.__name__}')\n\n try:\n np.broadcast(self, value)\n except ValueError as exc:\n raise ValueError(f'cannot compare: {exc}') from exc\n\n out = True\n for comp in self.components:\n out &= (getattr(self, '_' + comp) == getattr(value, '_' + comp))\n\n return out\n\n def __ne__(self, value):\n return np.logical_not(self == value)\n\n def _apply(self, method, *args, **kwargs):\n \"\"\"Create a new representation or differential with ``method`` applied\n to the component data.\n\n In typical usage, the method is any of the shape-changing methods for\n `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those\n picking particular elements (``__getitem__``, ``take``, etc.), which\n are all defined in `~astropy.utils.shapes.ShapedLikeNDArray`. It will be\n applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for\n `~astropy.coordinates.CartesianRepresentation`), with the results used\n to create a new instance.\n\n Internally, it is also used to apply functions to the components\n (in particular, `~numpy.broadcast_to`).\n\n Parameters\n ----------\n method : str or callable\n If str, it is the name of a method that is applied to the internal\n ``components``. If callable, the function is applied.\n args : tuple\n Any positional arguments for ``method``.\n kwargs : dict\n Any keyword arguments for ``method``.\n \"\"\"\n if callable(method):\n apply_method = lambda array: method(array, *args, **kwargs)\n else:\n apply_method = operator.methodcaller(method, *args, **kwargs)\n\n new = super().__new__(self.__class__)\n for component in self.components:\n setattr(new, '_' + component,\n apply_method(getattr(self, component)))\n\n # Copy other 'info' attr only if it has actually been defined.\n # See PR #3898 for further explanation and justification, along\n # with Quantity.__array_finalize__\n if 'info' in self.__dict__:\n new.info = self.info\n\n return new\n\n def __setitem__(self, item, value):\n if value.__class__ is not self.__class__:\n raise TypeError(f'can only set from object of same class: '\n f'{self.__class__.__name__} vs. '\n f'{value.__class__.__name__}')\n\n for component in self.components:\n getattr(self, '_' + component)[item] = getattr(value, '_' + component)\n\n @property\n def shape(self):\n \"\"\"The shape of the instance and underlying arrays.\n\n Like `~numpy.ndarray.shape`, can be set to a new shape by assigning a\n tuple. Note that if different instances share some but not all\n underlying data, setting the shape of one instance can make the other\n instance unusable. Hence, it is strongly recommended to get new,\n reshaped instances with the ``reshape`` method.\n\n Raises\n ------\n AttributeError\n If the shape of any of the components cannot be changed without the\n arrays being copied. For these cases, use the ``reshape`` method\n (which copies any arrays that cannot be reshaped in-place).\n \"\"\"\n return getattr(self, self.components[0]).shape\n\n @shape.setter\n def shape(self, shape):\n # We keep track of arrays that were already reshaped since we may have\n # to return those to their original shape if a later shape-setting\n # fails. (This can happen since coordinates are broadcast together.)\n reshaped = []\n oldshape = self.shape\n for component in self.components:\n val = getattr(self, component)\n if val.size > 1:\n try:\n val.shape = shape\n except AttributeError:\n for val2 in reshaped:\n val2.shape = oldshape\n raise\n else:\n reshaped.append(val)\n\n # Required to support multiplication and division, and defined by the base\n # representation and differential classes.\n @abc.abstractmethod\n def _scale_operation(self, op, *args):\n raise NotImplementedError()\n\n def __mul__(self, other):\n return self._scale_operation(operator.mul, other)\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __truediv__(self, other):\n return self._scale_operation(operator.truediv, other)\n\n def __div__(self, other): # pragma: py2\n return self._scale_operation(operator.truediv, other)\n\n def __neg__(self):\n return self._scale_operation(operator.neg)\n\n # Follow numpy convention and make an independent copy.\n def __pos__(self):\n return self.copy()\n\n # Required to support addition and subtraction, and defined by the base\n # representation and differential classes.\n @abc.abstractmethod\n def _combine_operation(self, op, other, reverse=False):\n raise NotImplementedError()\n\n def __add__(self, other):\n return self._combine_operation(operator.add, other)\n\n def __radd__(self, other):\n return self._combine_operation(operator.add, other, reverse=True)\n\n def __sub__(self, other):\n return self._combine_operation(operator.sub, other)\n\n def __rsub__(self, other):\n return self._combine_operation(operator.sub, other, reverse=True)\n\n # The following are used for repr and str\n @property\n def _values(self):\n \"\"\"Turn the coordinates into a record array with the coordinate values.\n\n The record array fields will have the component names.\n \"\"\"\n coo_items = [(c, getattr(self, c)) for c in self.components]\n result = np.empty(self.shape, [(c, coo.dtype) for c, coo in coo_items])\n for c, coo in coo_items:\n result[c] = coo.value\n return result\n\n @property\n def _units(self):\n \"\"\"Return a dictionary with the units of the coordinate components.\"\"\"\n return dict([(component, getattr(self, component).unit)\n for component in self.components])\n\n @property\n def _unitstr(self):\n units_set = set(self._units.values())\n if len(units_set) == 1:\n unitstr = units_set.pop().to_string()\n else:\n unitstr = '({})'.format(\n ', '.join([self._units[component].to_string()\n for component in self.components]))\n return unitstr\n\n def __str__(self):\n return '{} {:s}'.format(_array2string(self._values), self._unitstr)\n\n def __repr__(self):\n prefixstr = ' '\n arrstr = _array2string(self._values, prefix=prefixstr)\n\n diffstr = ''\n if getattr(self, 'differentials', None):\n diffstr = '\\n (has differentials w.r.t.: {})'.format(\n ', '.join([repr(key) for key in self.differentials.keys()]))\n\n unitstr = ('in ' + self._unitstr) if self._unitstr else '[dimensionless]'\n return '<{} ({}) {:s}\\n{}{}{}>'.format(\n self.__class__.__name__, ', '.join(self.components),\n unitstr, prefixstr, arrstr, diffstr)\n\n\ndef _make_getter(component):\n \"\"\"Make an attribute getter for use in a property.\n\n Parameters\n ----------\n component : str\n The name of the component that should be accessed. This assumes the\n actual value is stored in an attribute of that name prefixed by '_'.\n \"\"\"\n # This has to be done in a function to ensure the reference to component\n # is not lost/redirected.\n component = '_' + component\n\n def get_component(self):\n return getattr(self, component)\n return get_component\n\n\n# Need to also subclass ABCMeta rather than type, so that this meta class can\n# be combined with a ShapedLikeNDArray subclass (which is an ABC). Without it:\n# \"TypeError: metaclass conflict: the metaclass of a derived class must be a\n# (non-strict) subclass of the metaclasses of all its bases\"\nclass MetaBaseRepresentation(abc.ABCMeta):\n def __init__(cls, name, bases, dct):\n super().__init__(name, bases, dct)\n\n # Register representation name (except for BaseRepresentation)\n if cls.__name__ == 'BaseRepresentation':\n return\n\n if 'attr_classes' not in dct:\n raise NotImplementedError('Representations must have an '\n '\"attr_classes\" class attribute.')\n\n repr_name = cls.get_name()\n # first time a duplicate is added\n # remove first entry and add both using their qualnames\n if repr_name in REPRESENTATION_CLASSES:\n DUPLICATE_REPRESENTATIONS.add(repr_name)\n\n fqn_cls = _fqn_class(cls)\n existing = REPRESENTATION_CLASSES[repr_name]\n fqn_existing = _fqn_class(existing)\n\n if fqn_cls == fqn_existing:\n raise ValueError(f'Representation \"{fqn_cls}\" already defined')\n\n msg = (\n 'Representation \"{}\" already defined, removing it to avoid confusion.'\n 'Use qualnames \"{}\" and \"{}\" or class instaces directly'\n ).format(repr_name, fqn_cls, fqn_existing)\n warnings.warn(msg, DuplicateRepresentationWarning)\n\n del REPRESENTATION_CLASSES[repr_name]\n REPRESENTATION_CLASSES[fqn_existing] = existing\n repr_name = fqn_cls\n # further definitions with the same name, just add qualname\n elif repr_name in DUPLICATE_REPRESENTATIONS:\n warnings.warn('Representation \"{}\" already defined, using qualname \"{}\".')\n repr_name = _fqn_class(cls)\n if repr_name in REPRESENTATION_CLASSES:\n raise ValueError(\n f'Representation \"{repr_name}\" already defined'\n )\n\n REPRESENTATION_CLASSES[repr_name] = cls\n _invalidate_reprdiff_cls_hash()\n\n # define getters for any component that does not yet have one.\n for component in cls.attr_classes:\n if not hasattr(cls, component):\n setattr(cls, component,\n property(_make_getter(component),\n doc=(\"The '{}' component of the points(s).\"\n .format(component))))\n\n\nclass RepresentationInfo(BaseRepresentationOrDifferentialInfo):\n\n @property\n def _represent_as_dict_attrs(self):\n attrs = super()._represent_as_dict_attrs\n if self._parent._differentials:\n attrs += ('differentials',)\n return attrs\n\n def _represent_as_dict(self, attrs=None):\n out = super()._represent_as_dict(attrs)\n for key, value in out.pop('differentials', {}).items():\n out[f'differentials.{key}'] = value\n return out\n\n def _construct_from_dict(self, map):\n differentials = {}\n for key in list(map.keys()):\n if key.startswith('differentials.'):\n differentials[key[14:]] = map.pop(key)\n map['differentials'] = differentials\n return super()._construct_from_dict(map)\n\n\nclass BaseRepresentation(BaseRepresentationOrDifferential,\n metaclass=MetaBaseRepresentation):\n \"\"\"Base for representing a point in a 3D coordinate system.\n\n Parameters\n ----------\n comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass\n The components of the 3D points. The names are the keys and the\n subclasses the values of the ``attr_classes`` attribute.\n differentials : dict, `~astropy.coordinates.BaseDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single `~astropy.coordinates.BaseDifferential`\n subclass instance, or a dictionary with keys set to a string\n representation of the SI unit with which the differential (derivative)\n is taken. For example, for a velocity differential on a positional\n representation, the key would be ``'s'`` for seconds, indicating that\n the derivative is a time derivative.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n\n Notes\n -----\n All representation classes should subclass this base representation class,\n and define an ``attr_classes`` attribute, an `~collections.OrderedDict`\n which maps component names to the class that creates them. They must also\n define a ``to_cartesian`` method and a ``from_cartesian`` class method. By\n default, transformations are done via the cartesian system, but classes\n that want to define a smarter transformation path can overload the\n ``represent_as`` method. If one wants to use an associated differential\n class, one should also define ``unit_vectors`` and ``scale_factors``\n methods (see those methods for details).\n \"\"\"\n\n info = RepresentationInfo()\n\n def __init__(self, *args, differentials=None, **kwargs):\n # Handle any differentials passed in.\n super().__init__(*args, **kwargs)\n if (differentials is None\n and args and isinstance(args[0], self.__class__)):\n differentials = args[0]._differentials\n self._differentials = self._validate_differentials(differentials)\n\n def _validate_differentials(self, differentials):\n \"\"\"\n Validate that the provided differentials are appropriate for this\n representation and recast/reshape as necessary and then return.\n\n Note that this does *not* set the differentials on\n ``self._differentials``, but rather leaves that for the caller.\n \"\"\"\n\n # Now handle the actual validation of any specified differential classes\n if differentials is None:\n differentials = dict()\n\n elif isinstance(differentials, BaseDifferential):\n # We can't handle auto-determining the key for this combo\n if (isinstance(differentials, RadialDifferential) and\n isinstance(self, UnitSphericalRepresentation)):\n raise ValueError(\"To attach a RadialDifferential to a \"\n \"UnitSphericalRepresentation, you must supply \"\n \"a dictionary with an appropriate key.\")\n\n key = differentials._get_deriv_key(self)\n differentials = {key: differentials}\n\n for key in differentials:\n try:\n diff = differentials[key]\n except TypeError:\n raise TypeError(\"'differentials' argument must be a \"\n \"dictionary-like object\")\n\n diff._check_base(self)\n\n if (isinstance(diff, RadialDifferential) and\n isinstance(self, UnitSphericalRepresentation)):\n # We trust the passing of a key for a RadialDifferential\n # attached to a UnitSphericalRepresentation because it will not\n # have a paired component name (UnitSphericalRepresentation has\n # no .distance) to automatically determine the expected key\n pass\n\n else:\n expected_key = diff._get_deriv_key(self)\n if key != expected_key:\n raise ValueError(\"For differential object '{}', expected \"\n \"unit key = '{}' but received key = '{}'\"\n .format(repr(diff), expected_key, key))\n\n # For now, we are very rigid: differentials must have the same shape\n # as the representation. This makes it easier to handle __getitem__\n # and any other shape-changing operations on representations that\n # have associated differentials\n if diff.shape != self.shape:\n # TODO: message of IncompatibleShapeError is not customizable,\n # so use a valueerror instead?\n raise ValueError(\"Shape of differentials must be the same \"\n \"as the shape of the representation ({} vs \"\n \"{})\".format(diff.shape, self.shape))\n\n return differentials\n\n def _raise_if_has_differentials(self, op_name):\n \"\"\"\n Used to raise a consistent exception for any operation that is not\n supported when a representation has differentials attached.\n \"\"\"\n if self.differentials:\n raise TypeError(\"Operation '{}' is not supported when \"\n \"differentials are attached to a {}.\"\n .format(op_name, self.__class__.__name__))\n\n @property\n def _compatible_differentials(self):\n return [DIFFERENTIAL_CLASSES[self.get_name()]]\n\n @property\n def differentials(self):\n \"\"\"A dictionary of differential class instances.\n\n The keys of this dictionary must be a string representation of the SI\n unit with which the differential (derivative) is taken. For example, for\n a velocity differential on a positional representation, the key would be\n ``'s'`` for seconds, indicating that the derivative is a time\n derivative.\n \"\"\"\n return self._differentials\n\n # We do not make unit_vectors and scale_factors abstract methods, since\n # they are only necessary if one also defines an associated Differential.\n # Also, doing so would break pre-differential representation subclasses.\n def unit_vectors(self):\n r\"\"\"Cartesian unit vectors in the direction of each component.\n\n Given unit vectors :math:`\\hat{e}_c` and scale factors :math:`f_c`,\n a change in one component of :math:`\\delta c` corresponds to a change\n in representation of :math:`\\delta c \\times f_c \\times \\hat{e}_c`.\n\n Returns\n -------\n unit_vectors : dict of `CartesianRepresentation`\n The keys are the component names.\n \"\"\"\n raise NotImplementedError(\"{} has not implemented unit vectors\"\n .format(type(self)))\n\n def scale_factors(self):\n r\"\"\"Scale factors for each component's direction.\n\n Given unit vectors :math:`\\hat{e}_c` and scale factors :math:`f_c`,\n a change in one component of :math:`\\delta c` corresponds to a change\n in representation of :math:`\\delta c \\times f_c \\times \\hat{e}_c`.\n\n Returns\n -------\n scale_factors : dict of `~astropy.units.Quantity`\n The keys are the component names.\n \"\"\"\n raise NotImplementedError(\"{} has not implemented scale factors.\"\n .format(type(self)))\n\n def _re_represent_differentials(self, new_rep, differential_class):\n \"\"\"Re-represent the differentials to the specified classes.\n\n This returns a new dictionary with the same keys but with the\n attached differentials converted to the new differential classes.\n \"\"\"\n if differential_class is None:\n return dict()\n\n if not self.differentials and differential_class:\n raise ValueError(\"No differentials associated with this \"\n \"representation!\")\n\n elif (len(self.differentials) == 1 and\n inspect.isclass(differential_class) and\n issubclass(differential_class, BaseDifferential)):\n # TODO: is there a better way to do this?\n differential_class = {\n list(self.differentials.keys())[0]: differential_class\n }\n\n elif differential_class.keys() != self.differentials.keys():\n raise ValueError(\"Desired differential classes must be passed in \"\n \"as a dictionary with keys equal to a string \"\n \"representation of the unit of the derivative \"\n \"for each differential stored with this \"\n \"representation object ({0})\"\n .format(self.differentials))\n\n new_diffs = dict()\n for k in self.differentials:\n diff = self.differentials[k]\n try:\n new_diffs[k] = diff.represent_as(differential_class[k],\n base=self)\n except Exception:\n if (differential_class[k] not in\n new_rep._compatible_differentials):\n raise TypeError(\"Desired differential class {} is not \"\n \"compatible with the desired \"\n \"representation class {}\"\n .format(differential_class[k],\n new_rep.__class__))\n else:\n raise\n\n return new_diffs\n\n def represent_as(self, other_class, differential_class=None):\n \"\"\"Convert coordinates to another representation.\n\n If the instance is of the requested class, it is returned unmodified.\n By default, conversion is done via cartesian coordinates.\n\n Parameters\n ----------\n other_class : `~astropy.coordinates.BaseRepresentation` subclass\n The type of representation to turn the coordinates into.\n differential_class : dict of `~astropy.coordinates.BaseDifferential`, optional\n Classes in which the differentials should be represented.\n Can be a single class if only a single differential is attached,\n otherwise it should be a `dict` keyed by the same keys as the\n differentials.\n \"\"\"\n if other_class is self.__class__ and not differential_class:\n return self.without_differentials()\n\n else:\n if isinstance(other_class, str):\n raise ValueError(\"Input to a representation's represent_as \"\n \"must be a class, not a string. For \"\n \"strings, use frame objects\")\n\n if other_class is not self.__class__:\n # The default is to convert via cartesian coordinates\n new_rep = other_class.from_cartesian(self.to_cartesian())\n else:\n new_rep = self\n\n new_rep._differentials = self._re_represent_differentials(\n new_rep, differential_class)\n\n return new_rep\n\n def with_differentials(self, differentials):\n \"\"\"\n Create a new representation with the same positions as this\n representation, but with these new differentials.\n\n Differential keys that already exist in this object's differential dict\n are overwritten.\n\n Parameters\n ----------\n differentials : Sequence of `~astropy.coordinates.BaseDifferential`\n The differentials for the new representation to have.\n\n Returns\n -------\n newrepr\n A copy of this representation, but with the ``differentials`` as\n its differentials.\n \"\"\"\n if not differentials:\n return self\n\n args = [getattr(self, component) for component in self.components]\n\n # We shallow copy the differentials dictionary so we don't update the\n # current object's dictionary when adding new keys\n new_rep = self.__class__(*args, differentials=self.differentials.copy(),\n copy=False)\n new_rep._differentials.update(\n new_rep._validate_differentials(differentials))\n\n return new_rep\n\n def without_differentials(self):\n \"\"\"Return a copy of the representation without attached differentials.\n\n Returns\n -------\n newrepr\n A shallow copy of this representation, without any differentials.\n If no differentials were present, no copy is made.\n \"\"\"\n\n if not self._differentials:\n return self\n\n args = [getattr(self, component) for component in self.components]\n return self.__class__(*args, copy=False)\n\n @classmethod\n def from_representation(cls, representation):\n \"\"\"Create a new instance of this representation from another one.\n\n Parameters\n ----------\n representation : `~astropy.coordinates.BaseRepresentation` instance\n The presentation that should be converted to this class.\n \"\"\"\n return representation.represent_as(cls)\n\n def __eq__(self, value):\n \"\"\"Equality operator for BaseRepresentation\n\n This implements strict equality and requires that the representation\n classes are identical, the differentials are identical, and that the\n representation data are exactly equal.\n \"\"\"\n # BaseRepresentationOrDifferental (checks classes and compares components)\n out = super().__eq__(value)\n\n # super() checks that the class is identical so can this even happen?\n # (same class, different differentials ?)\n if self._differentials.keys() != value._differentials.keys():\n raise ValueError(f'cannot compare: objects must have same differentials')\n\n for self_diff, value_diff in zip(self._differentials.values(),\n value._differentials.values()):\n out &= (self_diff == value_diff)\n\n return out\n\n def __ne__(self, value):\n return np.logical_not(self == value)\n\n def _apply(self, method, *args, **kwargs):\n \"\"\"Create a new representation with ``method`` applied to the component\n data.\n\n This is not a simple inherit from ``BaseRepresentationOrDifferential``\n because we need to call ``._apply()`` on any associated differential\n classes.\n\n See docstring for `BaseRepresentationOrDifferential._apply`.\n\n Parameters\n ----------\n method : str or callable\n If str, it is the name of a method that is applied to the internal\n ``components``. If callable, the function is applied.\n args : tuple\n Any positional arguments for ``method``.\n kwargs : dict\n Any keyword arguments for ``method``.\n\n \"\"\"\n rep = super()._apply(method, *args, **kwargs)\n\n rep._differentials = dict(\n [(k, diff._apply(method, *args, **kwargs))\n for k, diff in self._differentials.items()])\n return rep\n\n def __setitem__(self, item, value):\n if not isinstance(value, BaseRepresentation):\n raise TypeError(f'value must be a representation instance, '\n f'not {type(value)}.')\n\n if not (isinstance(value, self.__class__)\n or len(value.attr_classes) == len(self.attr_classes)):\n raise ValueError(\n f'value must be representable as {self.__class__.__name__} '\n f'without loss of information.')\n\n diff_classes = {}\n if self._differentials:\n if self._differentials.keys() != value._differentials.keys():\n raise ValueError('value must have the same differentials.')\n\n for key, self_diff in self._differentials.items():\n diff_classes[key] = self_diff_cls = self_diff.__class__\n value_diff_cls = value._differentials[key].__class__\n if not (isinstance(value_diff_cls, self_diff_cls)\n or (len(value_diff_cls.attr_classes)\n == len(self_diff_cls.attr_classes))):\n raise ValueError(\n f'value differential {key!r} must be representable as '\n f'{self_diff.__class__.__name__} without loss of information.')\n\n value = value.represent_as(self.__class__, diff_classes)\n super().__setitem__(item, value)\n for key, differential in self._differentials.items():\n differential[item] = value._differentials[key]\n\n def _scale_operation(self, op, *args):\n \"\"\"Scale all non-angular components, leaving angular ones unchanged.\n\n Parameters\n ----------\n op : `~operator` callable\n Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc.\n *args\n Any arguments required for the operator (typically, what is to\n be multiplied with, divided by).\n \"\"\"\n\n self._raise_if_has_differentials(op.__name__)\n\n results = []\n for component, cls in self.attr_classes.items():\n value = getattr(self, component)\n if issubclass(cls, Angle):\n results.append(value)\n else:\n results.append(op(value, *args))\n\n # try/except catches anything that cannot initialize the class, such\n # as operations that returned NotImplemented or a representation\n # instead of a quantity (as would happen for, e.g., rep * rep).\n try:\n return self.__class__(*results)\n except Exception:\n return NotImplemented\n\n def _combine_operation(self, op, other, reverse=False):\n \"\"\"Combine two representation.\n\n By default, operate on the cartesian representations of both.\n\n Parameters\n ----------\n op : `~operator` callable\n Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.\n other : `~astropy.coordinates.BaseRepresentation` instance\n The other representation.\n reverse : bool\n Whether the operands should be reversed (e.g., as we got here via\n ``self.__rsub__`` because ``self`` is a subclass of ``other``).\n \"\"\"\n self._raise_if_has_differentials(op.__name__)\n\n result = self.to_cartesian()._combine_operation(op, other, reverse)\n if result is NotImplemented:\n return NotImplemented\n else:\n return self.from_cartesian(result)\n\n # We need to override this setter to support differentials\n @BaseRepresentationOrDifferential.shape.setter\n def shape(self, shape):\n orig_shape = self.shape\n\n # See: https://stackoverflow.com/questions/3336767/ for an example\n BaseRepresentationOrDifferential.shape.fset(self, shape)\n\n # also try to perform shape-setting on any associated differentials\n try:\n for k in self.differentials:\n self.differentials[k].shape = shape\n except Exception:\n BaseRepresentationOrDifferential.shape.fset(self, orig_shape)\n for k in self.differentials:\n self.differentials[k].shape = orig_shape\n\n raise\n\n def norm(self):\n \"\"\"Vector norm.\n\n The norm is the standard Frobenius norm, i.e., the square root of the\n sum of the squares of all components with non-angular units.\n\n Note that any associated differentials will be dropped during this\n operation.\n\n Returns\n -------\n norm : `astropy.units.Quantity`\n Vector norm, with the same shape as the representation.\n \"\"\"\n return np.sqrt(functools.reduce(\n operator.add, (getattr(self, component)**2\n for component, cls in self.attr_classes.items()\n if not issubclass(cls, Angle))))\n\n def mean(self, *args, **kwargs):\n \"\"\"Vector mean.\n\n Averaging is done by converting the representation to cartesian, and\n taking the mean of the x, y, and z components. The result is converted\n back to the same representation as the input.\n\n Refer to `~numpy.mean` for full documentation of the arguments, noting\n that ``axis`` is the entry in the ``shape`` of the representation, and\n that the ``out`` argument cannot be used.\n\n Returns\n -------\n mean : representation\n Vector mean, in the same representation as that of the input.\n \"\"\"\n self._raise_if_has_differentials('mean')\n return self.from_cartesian(self.to_cartesian().mean(*args, **kwargs))\n\n def sum(self, *args, **kwargs):\n \"\"\"Vector sum.\n\n Adding is done by converting the representation to cartesian, and\n summing the x, y, and z components. The result is converted back to the\n same representation as the input.\n\n Refer to `~numpy.sum` for full documentation of the arguments, noting\n that ``axis`` is the entry in the ``shape`` of the representation, and\n that the ``out`` argument cannot be used.\n\n Returns\n -------\n sum : representation\n Vector sum, in the same representation as that of the input.\n \"\"\"\n self._raise_if_has_differentials('sum')\n return self.from_cartesian(self.to_cartesian().sum(*args, **kwargs))\n\n def dot(self, other):\n \"\"\"Dot product of two representations.\n\n The calculation is done by converting both ``self`` and ``other``\n to `~astropy.coordinates.CartesianRepresentation`.\n\n Note that any associated differentials will be dropped during this\n operation.\n\n Parameters\n ----------\n other : `~astropy.coordinates.BaseRepresentation`\n The representation to take the dot product with.\n\n Returns\n -------\n dot_product : `~astropy.units.Quantity`\n The sum of the product of the x, y, and z components of the\n cartesian representations of ``self`` and ``other``.\n \"\"\"\n return self.to_cartesian().dot(other)\n\n def cross(self, other):\n \"\"\"Vector cross product of two representations.\n\n The calculation is done by converting both ``self`` and ``other``\n to `~astropy.coordinates.CartesianRepresentation`, and converting the\n result back to the type of representation of ``self``.\n\n Parameters\n ----------\n other : representation\n The representation to take the cross product with.\n\n Returns\n -------\n cross_product : representation\n With vectors perpendicular to both ``self`` and ``other``, in the\n same type of representation as ``self``.\n \"\"\"\n self._raise_if_has_differentials('cross')\n return self.from_cartesian(self.to_cartesian().cross(other))\n\n\nclass CartesianRepresentation(BaseRepresentation):\n \"\"\"\n Representation of points in 3D cartesian coordinates.\n\n Parameters\n ----------\n x, y, z : `~astropy.units.Quantity` or array\n The x, y, and z coordinates of the point(s). If ``x``, ``y``, and ``z``\n have different shapes, they should be broadcastable. If not quantity,\n ``unit`` should be set. If only ``x`` is given, it is assumed that it\n contains an array with the 3 coordinates stored along ``xyz_axis``.\n unit : `~astropy.units.Unit` or str\n If given, the coordinates will be converted to this unit (or taken to\n be in this unit if not given.\n xyz_axis : int, optional\n The axis along which the coordinates are stored when a single array is\n provided rather than distinct ``x``, ``y``, and ``z`` (default: 0).\n\n differentials : dict, `CartesianDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single\n `CartesianDifferential` instance, or a dictionary of\n `CartesianDifferential` s with keys set to a string representation of\n the SI unit with which the differential (derivative) is taken. For\n example, for a velocity differential on a positional representation, the\n key would be ``'s'`` for seconds, indicating that the derivative is a\n time derivative.\n\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n\n attr_classes = OrderedDict([('x', u.Quantity),\n ('y', u.Quantity),\n ('z', u.Quantity)])\n\n _xyz = None\n\n def __init__(self, x, y=None, z=None, unit=None, xyz_axis=None,\n differentials=None, copy=True):\n\n if y is None and z is None:\n if isinstance(x, np.ndarray) and x.dtype.kind not in 'OV':\n # Short-cut for 3-D array input.\n x = u.Quantity(x, unit, copy=copy, subok=True)\n # Keep a link to the array with all three coordinates\n # so that we can return it quickly if needed in get_xyz.\n self._xyz = x\n if xyz_axis:\n x = np.moveaxis(x, xyz_axis, 0)\n self._xyz_axis = xyz_axis\n else:\n self._xyz_axis = 0\n\n self._x, self._y, self._z = x\n self._differentials = self._validate_differentials(differentials)\n return\n\n elif (isinstance(x, CartesianRepresentation)\n and unit is None and xyz_axis is None):\n if differentials is None:\n differentials = x._differentials\n\n return super().__init__(x, differentials=differentials,\n copy=copy)\n\n else:\n x, y, z = x\n\n if xyz_axis is not None:\n raise ValueError(\"xyz_axis should only be set if x, y, and z are \"\n \"in a single array passed in through x, \"\n \"i.e., y and z should not be not given.\")\n\n if y is None or z is None:\n raise ValueError(\"x, y, and z are required to instantiate {}\"\n .format(self.__class__.__name__))\n\n if unit is not None:\n x = u.Quantity(x, unit, copy=copy, subok=True)\n y = u.Quantity(y, unit, copy=copy, subok=True)\n z = u.Quantity(z, unit, copy=copy, subok=True)\n copy = False\n\n super().__init__(x, y, z, copy=copy, differentials=differentials)\n if not (self._x.unit.is_equivalent(self._y.unit) and\n self._x.unit.is_equivalent(self._z.unit)):\n raise u.UnitsError(\"x, y, and z should have matching physical types\")\n\n def unit_vectors(self):\n l = np.broadcast_to(1.*u.one, self.shape, subok=True)\n o = np.broadcast_to(0.*u.one, self.shape, subok=True)\n return OrderedDict(\n (('x', CartesianRepresentation(l, o, o, copy=False)),\n ('y', CartesianRepresentation(o, l, o, copy=False)),\n ('z', CartesianRepresentation(o, o, l, copy=False))))\n\n def scale_factors(self):\n l = np.broadcast_to(1.*u.one, self.shape, subok=True)\n return OrderedDict((('x', l), ('y', l), ('z', l)))\n\n def get_xyz(self, xyz_axis=0):\n \"\"\"Return a vector array of the x, y, and z coordinates.\n\n Parameters\n ----------\n xyz_axis : int, optional\n The axis in the final array along which the x, y, z components\n should be stored (default: 0).\n\n Returns\n -------\n xyz : `~astropy.units.Quantity`\n With dimension 3 along ``xyz_axis``. Note that, if possible,\n this will be a view.\n \"\"\"\n if self._xyz is not None:\n if self._xyz_axis == xyz_axis:\n return self._xyz\n else:\n return np.moveaxis(self._xyz, self._xyz_axis, xyz_axis)\n\n # Create combined array. TO DO: keep it in _xyz for repeated use?\n # But then in-place changes have to cancel it. Likely best to\n # also update components.\n return _combine_xyz(self._x, self._y, self._z, xyz_axis=xyz_axis)\n\n xyz = property(get_xyz)\n\n @classmethod\n def from_cartesian(cls, other):\n return other\n\n def to_cartesian(self):\n return self\n\n def transform(self, matrix):\n \"\"\"\n Transform the cartesian coordinates using a 3x3 matrix.\n\n This returns a new representation and does not modify the original one.\n Any differentials attached to this representation will also be\n transformed.\n\n Parameters\n ----------\n matrix : `~numpy.ndarray`\n A 3x3 transformation matrix, such as a rotation matrix.\n\n\n Examples\n --------\n\n We can start off by creating a cartesian representation object:\n\n >>> from astropy import units as u\n >>> from astropy.coordinates import CartesianRepresentation\n >>> rep = CartesianRepresentation([1, 2] * u.pc,\n ... [2, 3] * u.pc,\n ... [3, 4] * u.pc)\n\n We now create a rotation matrix around the z axis:\n\n >>> from astropy.coordinates.matrix_utilities import rotation_matrix\n >>> rotation = rotation_matrix(30 * u.deg, axis='z')\n\n Finally, we can apply this transformation:\n\n >>> rep_new = rep.transform(rotation)\n >>> rep_new.xyz # doctest: +FLOAT_CMP\n <Quantity [[ 1.8660254 , 3.23205081],\n [ 1.23205081, 1.59807621],\n [ 3. , 4. ]] pc>\n \"\"\"\n # erfa rxp: Multiply a p-vector by an r-matrix.\n p = erfa_ufunc.rxp(matrix, self.get_xyz(xyz_axis=-1))\n # Handle differentials attached to this representation\n if self.differentials:\n # TODO: speed this up going via d.d_xyz.\n new_diffs = dict(\n (k, d.from_cartesian(d.to_cartesian().transform(matrix)))\n for k, d in self.differentials.items())\n else:\n new_diffs = None\n\n return self.__class__(p, xyz_axis=-1, copy=False, differentials=new_diffs)\n\n def _combine_operation(self, op, other, reverse=False):\n self._raise_if_has_differentials(op.__name__)\n\n try:\n other_c = other.to_cartesian()\n except Exception:\n return NotImplemented\n\n first, second = ((self, other_c) if not reverse else\n (other_c, self))\n return self.__class__(*(op(getattr(first, component),\n getattr(second, component))\n for component in first.components))\n\n def norm(self):\n \"\"\"Vector norm.\n\n The norm is the standard Frobenius norm, i.e., the square root of the\n sum of the squares of all components with non-angular units.\n\n Note that any associated differentials will be dropped during this\n operation.\n\n Returns\n -------\n norm : `astropy.units.Quantity`\n Vector norm, with the same shape as the representation.\n \"\"\"\n # erfa pm: Modulus of p-vector.\n return erfa_ufunc.pm(self.get_xyz(xyz_axis=-1))\n\n def mean(self, *args, **kwargs):\n \"\"\"Vector mean.\n\n Returns a new CartesianRepresentation instance with the means of the\n x, y, and z components.\n\n Refer to `~numpy.mean` for full documentation of the arguments, noting\n that ``axis`` is the entry in the ``shape`` of the representation, and\n that the ``out`` argument cannot be used.\n \"\"\"\n self._raise_if_has_differentials('mean')\n return self._apply('mean', *args, **kwargs)\n\n def sum(self, *args, **kwargs):\n \"\"\"Vector sum.\n\n Returns a new CartesianRepresentation instance with the sums of the\n x, y, and z components.\n\n Refer to `~numpy.sum` for full documentation of the arguments, noting\n that ``axis`` is the entry in the ``shape`` of the representation, and\n that the ``out`` argument cannot be used.\n \"\"\"\n self._raise_if_has_differentials('sum')\n return self._apply('sum', *args, **kwargs)\n\n def dot(self, other):\n \"\"\"Dot product of two representations.\n\n Note that any associated differentials will be dropped during this\n operation.\n\n Parameters\n ----------\n other : representation\n If not already cartesian, it is converted.\n\n Returns\n -------\n dot_product : `~astropy.units.Quantity`\n The sum of the product of the x, y, and z components of ``self``\n and ``other``.\n \"\"\"\n try:\n other_c = other.to_cartesian()\n except Exception:\n raise TypeError(\"cannot only take dot product with another \"\n \"representation, not a {} instance.\"\n .format(type(other)))\n # erfa pdp: p-vector inner (=scalar=dot) product.\n return erfa_ufunc.pdp(self.get_xyz(xyz_axis=-1),\n other_c.get_xyz(xyz_axis=-1))\n\n def cross(self, other):\n \"\"\"Cross product of two representations.\n\n Parameters\n ----------\n other : representation\n If not already cartesian, it is converted.\n\n Returns\n -------\n cross_product : `~astropy.coordinates.CartesianRepresentation`\n With vectors perpendicular to both ``self`` and ``other``.\n \"\"\"\n self._raise_if_has_differentials('cross')\n try:\n other_c = other.to_cartesian()\n except Exception:\n raise TypeError(\"cannot only take cross product with another \"\n \"representation, not a {} instance.\"\n .format(type(other)))\n # erfa pxp: p-vector outer (=vector=cross) product.\n sxo = erfa_ufunc.pxp(self.get_xyz(xyz_axis=-1),\n other_c.get_xyz(xyz_axis=-1))\n return self.__class__(sxo, xyz_axis=-1)\n\n\nclass UnitSphericalRepresentation(BaseRepresentation):\n \"\"\"\n Representation of points on a unit sphere.\n\n Parameters\n ----------\n lon, lat : `~astropy.units.Quantity` or str\n The longitude and latitude of the point(s), in angular units. The\n latitude should be between -90 and 90 degrees, and the longitude will\n be wrapped to an angle between 0 and 360 degrees. These can also be\n instances of `~astropy.coordinates.Angle`,\n `~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`.\n\n differentials : dict, `~astropy.coordinates.BaseDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single `~astropy.coordinates.BaseDifferential`\n instance (see `._compatible_differentials` for valid types), or a\n dictionary of of differential instances with keys set to a string\n representation of the SI unit with which the differential (derivative)\n is taken. For example, for a velocity differential on a positional\n representation, the key would be ``'s'`` for seconds, indicating that\n the derivative is a time derivative.\n\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n\n attr_classes = OrderedDict([('lon', Longitude),\n ('lat', Latitude)])\n\n @classproperty\n def _dimensional_representation(cls):\n return SphericalRepresentation\n\n def __init__(self, lon, lat=None, differentials=None, copy=True):\n super().__init__(lon, lat, differentials=differentials, copy=copy)\n\n @property\n def _compatible_differentials(self):\n return [UnitSphericalDifferential, UnitSphericalCosLatDifferential,\n SphericalDifferential, SphericalCosLatDifferential,\n RadialDifferential]\n\n # Could let the metaclass define these automatically, but good to have\n # a bit clearer docstrings.\n @property\n def lon(self):\n \"\"\"\n The longitude of the point(s).\n \"\"\"\n return self._lon\n\n @property\n def lat(self):\n \"\"\"\n The latitude of the point(s).\n \"\"\"\n return self._lat\n\n def unit_vectors(self):\n sinlon, coslon = np.sin(self.lon), np.cos(self.lon)\n sinlat, coslat = np.sin(self.lat), np.cos(self.lat)\n return OrderedDict(\n (('lon', CartesianRepresentation(-sinlon, coslon, 0., copy=False)),\n ('lat', CartesianRepresentation(-sinlat*coslon, -sinlat*sinlon,\n coslat, copy=False))))\n\n def scale_factors(self, omit_coslat=False):\n sf_lat = np.broadcast_to(1./u.radian, self.shape, subok=True)\n sf_lon = sf_lat if omit_coslat else np.cos(self.lat) / u.radian\n return OrderedDict((('lon', sf_lon),\n ('lat', sf_lat)))\n\n def to_cartesian(self):\n \"\"\"\n Converts spherical polar coordinates to 3D rectangular cartesian\n coordinates.\n \"\"\"\n # NUMPY_LT_1_16 cannot create a vector automatically\n p = u.Quantity(np.empty(self.shape + (3,)), u.dimensionless_unscaled,\n copy=False)\n # erfa s2c: Convert [unit]spherical coordinates to Cartesian.\n p = erfa_ufunc.s2c(self.lon, self.lat, p)\n return CartesianRepresentation(p, xyz_axis=-1, copy=False)\n\n @classmethod\n def from_cartesian(cls, cart):\n \"\"\"\n Converts 3D rectangular cartesian coordinates to spherical polar\n coordinates.\n \"\"\"\n p = cart.get_xyz(xyz_axis=-1)\n # erfa c2s: P-vector to [unit]spherical coordinates.\n return cls(*erfa_ufunc.c2s(p), copy=False)\n\n def represent_as(self, other_class, differential_class=None):\n # Take a short cut if the other class is a spherical representation\n\n # TODO: this could be optimized to shortcut even if a differential_class\n # is passed in, using the ._re_represent_differentials() method\n if inspect.isclass(other_class) and not differential_class:\n if issubclass(other_class, PhysicsSphericalRepresentation):\n return other_class(phi=self.lon, theta=90 * u.deg - self.lat, r=1.0,\n copy=False)\n elif issubclass(other_class, SphericalRepresentation):\n return other_class(lon=self.lon, lat=self.lat, distance=1.0,\n copy=False)\n\n return super().represent_as(other_class, differential_class)\n\n def __mul__(self, other):\n self._raise_if_has_differentials('multiplication')\n return self._dimensional_representation(lon=self.lon, lat=self.lat,\n distance=1. * other)\n\n def __truediv__(self, other):\n self._raise_if_has_differentials('division')\n return self._dimensional_representation(lon=self.lon, lat=self.lat,\n distance=1. / other)\n\n def __neg__(self):\n self._raise_if_has_differentials('negation')\n return self.__class__(self.lon + 180. * u.deg, -self.lat, copy=False)\n\n def norm(self):\n \"\"\"Vector norm.\n\n The norm is the standard Frobenius norm, i.e., the square root of the\n sum of the squares of all components with non-angular units, which is\n always unity for vectors on the unit sphere.\n\n Returns\n -------\n norm : `~astropy.units.Quantity`\n Dimensionless ones, with the same shape as the representation.\n \"\"\"\n return u.Quantity(np.ones(self.shape), u.dimensionless_unscaled,\n copy=False)\n\n def _combine_operation(self, op, other, reverse=False):\n self._raise_if_has_differentials(op.__name__)\n\n result = self.to_cartesian()._combine_operation(op, other, reverse)\n if result is NotImplemented:\n return NotImplemented\n else:\n return self._dimensional_representation.from_cartesian(result)\n\n def mean(self, *args, **kwargs):\n \"\"\"Vector mean.\n\n The representation is converted to cartesian, the means of the x, y,\n and z components are calculated, and the result is converted to a\n `~astropy.coordinates.SphericalRepresentation`.\n\n Refer to `~numpy.mean` for full documentation of the arguments, noting\n that ``axis`` is the entry in the ``shape`` of the representation, and\n that the ``out`` argument cannot be used.\n \"\"\"\n self._raise_if_has_differentials('mean')\n return self._dimensional_representation.from_cartesian(\n self.to_cartesian().mean(*args, **kwargs))\n\n def sum(self, *args, **kwargs):\n \"\"\"Vector sum.\n\n The representation is converted to cartesian, the sums of the x, y,\n and z components are calculated, and the result is converted to a\n `~astropy.coordinates.SphericalRepresentation`.\n\n Refer to `~numpy.sum` for full documentation of the arguments, noting\n that ``axis`` is the entry in the ``shape`` of the representation, and\n that the ``out`` argument cannot be used.\n \"\"\"\n self._raise_if_has_differentials('sum')\n return self._dimensional_representation.from_cartesian(\n self.to_cartesian().sum(*args, **kwargs))\n\n def cross(self, other):\n \"\"\"Cross product of two representations.\n\n The calculation is done by converting both ``self`` and ``other``\n to `~astropy.coordinates.CartesianRepresentation`, and converting the\n result back to `~astropy.coordinates.SphericalRepresentation`.\n\n Parameters\n ----------\n other : representation\n The representation to take the cross product with.\n\n Returns\n -------\n cross_product : `~astropy.coordinates.SphericalRepresentation`\n With vectors perpendicular to both ``self`` and ``other``.\n \"\"\"\n self._raise_if_has_differentials('cross')\n return self._dimensional_representation.from_cartesian(\n self.to_cartesian().cross(other))\n\n\nclass RadialRepresentation(BaseRepresentation):\n \"\"\"\n Representation of the distance of points from the origin.\n\n Note that this is mostly intended as an internal helper representation.\n It can do little else but being used as a scale in multiplication.\n\n Parameters\n ----------\n distance : `~astropy.units.Quantity`\n The distance of the point(s) from the origin.\n\n differentials : dict, `~astropy.coordinates.BaseDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single `~astropy.coordinates.BaseDifferential`\n instance (see `._compatible_differentials` for valid types), or a\n dictionary of of differential instances with keys set to a string\n representation of the SI unit with which the differential (derivative)\n is taken. For example, for a velocity differential on a positional\n representation, the key would be ``'s'`` for seconds, indicating that\n the derivative is a time derivative.\n\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n\n attr_classes = OrderedDict([('distance', u.Quantity)])\n\n def __init__(self, distance, differentials=None, copy=True):\n super().__init__(distance, differentials=differentials, copy=copy)\n\n @property\n def distance(self):\n \"\"\"\n The distance from the origin to the point(s).\n \"\"\"\n return self._distance\n\n def unit_vectors(self):\n \"\"\"Cartesian unit vectors are undefined for radial representation.\"\"\"\n raise NotImplementedError('Cartesian unit vectors are undefined for '\n '{} instances'.format(self.__class__))\n\n def scale_factors(self):\n l = np.broadcast_to(1.*u.one, self.shape, subok=True)\n return OrderedDict((('distance', l),))\n\n def to_cartesian(self):\n \"\"\"Cannot convert radial representation to cartesian.\"\"\"\n raise NotImplementedError('cannot convert {} instance to cartesian.'\n .format(self.__class__))\n\n @classmethod\n def from_cartesian(cls, cart):\n \"\"\"\n Converts 3D rectangular cartesian coordinates to radial coordinate.\n \"\"\"\n return cls(distance=cart.norm(), copy=False)\n\n def _scale_operation(self, op, *args):\n self._raise_if_has_differentials(op.__name__)\n return op(self.distance, *args)\n\n def norm(self):\n \"\"\"Vector norm.\n\n Just the distance itself.\n\n Returns\n -------\n norm : `~astropy.units.Quantity`\n Dimensionless ones, with the same shape as the representation.\n \"\"\"\n return self.distance\n\n def _combine_operation(self, op, other, reverse=False):\n return NotImplemented\n\n\nclass SphericalRepresentation(BaseRepresentation):\n \"\"\"\n Representation of points in 3D spherical coordinates.\n\n Parameters\n ----------\n lon, lat : `~astropy.units.Quantity`\n The longitude and latitude of the point(s), in angular units. The\n latitude should be between -90 and 90 degrees, and the longitude will\n be wrapped to an angle between 0 and 360 degrees. These can also be\n instances of `~astropy.coordinates.Angle`,\n `~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`.\n\n distance : `~astropy.units.Quantity`\n The distance to the point(s). If the distance is a length, it is\n passed to the :class:`~astropy.coordinates.Distance` class, otherwise\n it is passed to the :class:`~astropy.units.Quantity` class.\n\n differentials : dict, `~astropy.coordinates.BaseDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single `~astropy.coordinates.BaseDifferential`\n instance (see `._compatible_differentials` for valid types), or a\n dictionary of of differential instances with keys set to a string\n representation of the SI unit with which the differential (derivative)\n is taken. For example, for a velocity differential on a positional\n representation, the key would be ``'s'`` for seconds, indicating that\n the derivative is a time derivative.\n\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n\n attr_classes = OrderedDict([('lon', Longitude),\n ('lat', Latitude),\n ('distance', u.Quantity)])\n _unit_representation = UnitSphericalRepresentation\n\n def __init__(self, lon, lat=None, distance=None, differentials=None,\n copy=True):\n super().__init__(lon, lat, distance, copy=copy,\n differentials=differentials)\n if self._distance.unit.physical_type == 'length':\n try:\n self._distance = Distance(self._distance, copy=False)\n except ValueError as e:\n if e.args[0].startswith('Distance must be >= 0'):\n raise ValueError(\"Distance must be >= 0. To allow negative \"\n \"distance values, you must explicitly pass\"\n \" in a `Distance` object with the the \"\n \"argument 'allow_negative=True'.\")\n else:\n raise\n\n @property\n def _compatible_differentials(self):\n return [UnitSphericalDifferential, UnitSphericalCosLatDifferential,\n SphericalDifferential, SphericalCosLatDifferential,\n RadialDifferential]\n\n @property\n def lon(self):\n \"\"\"\n The longitude of the point(s).\n \"\"\"\n return self._lon\n\n @property\n def lat(self):\n \"\"\"\n The latitude of the point(s).\n \"\"\"\n return self._lat\n\n @property\n def distance(self):\n \"\"\"\n The distance from the origin to the point(s).\n \"\"\"\n return self._distance\n\n def unit_vectors(self):\n sinlon, coslon = np.sin(self.lon), np.cos(self.lon)\n sinlat, coslat = np.sin(self.lat), np.cos(self.lat)\n return OrderedDict(\n (('lon', CartesianRepresentation(-sinlon, coslon, 0., copy=False)),\n ('lat', CartesianRepresentation(-sinlat*coslon, -sinlat*sinlon,\n coslat, copy=False)),\n ('distance', CartesianRepresentation(coslat*coslon, coslat*sinlon,\n sinlat, copy=False))))\n\n def scale_factors(self, omit_coslat=False):\n sf_lat = self.distance / u.radian\n sf_lon = sf_lat if omit_coslat else sf_lat * np.cos(self.lat)\n sf_distance = np.broadcast_to(1.*u.one, self.shape, subok=True)\n return OrderedDict((('lon', sf_lon),\n ('lat', sf_lat),\n ('distance', sf_distance)))\n\n def represent_as(self, other_class, differential_class=None):\n # Take a short cut if the other class is a spherical representation\n\n # TODO: this could be optimized to shortcut even if a differential_class\n # is passed in, using the ._re_represent_differentials() method\n if inspect.isclass(other_class) and not differential_class:\n if issubclass(other_class, PhysicsSphericalRepresentation):\n return other_class(phi=self.lon, theta=90 * u.deg - self.lat,\n r=self.distance, copy=False)\n elif issubclass(other_class, UnitSphericalRepresentation):\n return other_class(lon=self.lon, lat=self.lat, copy=False)\n\n return super().represent_as(other_class, differential_class)\n\n def to_cartesian(self):\n \"\"\"\n Converts spherical polar coordinates to 3D rectangular cartesian\n coordinates.\n \"\"\"\n\n # We need to convert Distance to Quantity to allow negative values.\n if isinstance(self.distance, Distance):\n d = self.distance.view(u.Quantity)\n else:\n d = self.distance\n\n # NUMPY_LT_1_16 cannot create a vector automatically\n p = u.Quantity(np.empty(self.shape + (3,)), d.unit, copy=False)\n # erfa s2p: Convert spherical polar coordinates to p-vector.\n p = erfa_ufunc.s2p(self.lon, self.lat, d, p)\n\n return CartesianRepresentation(p, xyz_axis=-1, copy=False)\n\n @classmethod\n def from_cartesian(cls, cart):\n \"\"\"\n Converts 3D rectangular cartesian coordinates to spherical polar\n coordinates.\n \"\"\"\n p = cart.get_xyz(xyz_axis=-1)\n # erfa p2s: P-vector to spherical polar coordinates.\n return cls(*erfa_ufunc.p2s(p), copy=False)\n\n def norm(self):\n \"\"\"Vector norm.\n\n The norm is the standard Frobenius norm, i.e., the square root of the\n sum of the squares of all components with non-angular units. For\n spherical coordinates, this is just the absolute value of the distance.\n\n Returns\n -------\n norm : `astropy.units.Quantity`\n Vector norm, with the same shape as the representation.\n \"\"\"\n return np.abs(self.distance)\n\n def __neg__(self):\n self._raise_if_has_differentials('negation')\n return self.__class__(self.lon + 180. * u.deg, -self.lat, self.distance,\n copy=False)\n\n\nclass PhysicsSphericalRepresentation(BaseRepresentation):\n \"\"\"\n Representation of points in 3D spherical coordinates (using the physics\n convention of using ``phi`` and ``theta`` for azimuth and inclination\n from the pole).\n\n Parameters\n ----------\n phi, theta : `~astropy.units.Quantity` or str\n The azimuth and inclination of the point(s), in angular units. The\n inclination should be between 0 and 180 degrees, and the azimuth will\n be wrapped to an angle between 0 and 360 degrees. These can also be\n instances of `~astropy.coordinates.Angle`. If ``copy`` is False, `phi`\n will be changed inplace if it is not between 0 and 360 degrees.\n\n r : `~astropy.units.Quantity`\n The distance to the point(s). If the distance is a length, it is\n passed to the :class:`~astropy.coordinates.Distance` class, otherwise\n it is passed to the :class:`~astropy.units.Quantity` class.\n\n differentials : dict, `PhysicsSphericalDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single\n `PhysicsSphericalDifferential` instance, or a dictionary of of\n differential instances with keys set to a string representation of the\n SI unit with which the differential (derivative) is taken. For example,\n for a velocity differential on a positional representation, the key\n would be ``'s'`` for seconds, indicating that the derivative is a time\n derivative.\n\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n\n attr_classes = OrderedDict([('phi', Angle),\n ('theta', Angle),\n ('r', u.Quantity)])\n\n def __init__(self, phi, theta=None, r=None, differentials=None, copy=True):\n super().__init__(phi, theta, r, copy=copy, differentials=differentials)\n\n # Wrap/validate phi/theta\n if copy:\n self._phi = self._phi.wrap_at(360 * u.deg)\n else:\n # necessary because the above version of `wrap_at` has to be a copy\n self._phi.wrap_at(360 * u.deg, inplace=True)\n\n if np.any(self._theta < 0.*u.deg) or np.any(self._theta > 180.*u.deg):\n raise ValueError('Inclination angle(s) must be within '\n '0 deg <= angle <= 180 deg, '\n 'got {}'.format(theta.to(u.degree)))\n\n if self._r.unit.physical_type == 'length':\n self._r = self._r.view(Distance)\n\n @property\n def phi(self):\n \"\"\"\n The azimuth of the point(s).\n \"\"\"\n return self._phi\n\n @property\n def theta(self):\n \"\"\"\n The elevation of the point(s).\n \"\"\"\n return self._theta\n\n @property\n def r(self):\n \"\"\"\n The distance from the origin to the point(s).\n \"\"\"\n return self._r\n\n def unit_vectors(self):\n sinphi, cosphi = np.sin(self.phi), np.cos(self.phi)\n sintheta, costheta = np.sin(self.theta), np.cos(self.theta)\n return OrderedDict(\n (('phi', CartesianRepresentation(-sinphi, cosphi, 0., copy=False)),\n ('theta', CartesianRepresentation(costheta*cosphi,\n costheta*sinphi,\n -sintheta, copy=False)),\n ('r', CartesianRepresentation(sintheta*cosphi, sintheta*sinphi,\n costheta, copy=False))))\n\n def scale_factors(self):\n r = self.r / u.radian\n sintheta = np.sin(self.theta)\n l = np.broadcast_to(1.*u.one, self.shape, subok=True)\n return OrderedDict((('phi', r * sintheta),\n ('theta', r),\n ('r', l)))\n\n def represent_as(self, other_class, differential_class=None):\n # Take a short cut if the other class is a spherical representation\n\n # TODO: this could be optimized to shortcut even if a differential_class\n # is passed in, using the ._re_represent_differentials() method\n if inspect.isclass(other_class) and not differential_class:\n if issubclass(other_class, SphericalRepresentation):\n return other_class(lon=self.phi, lat=90 * u.deg - self.theta,\n distance=self.r)\n elif issubclass(other_class, UnitSphericalRepresentation):\n return other_class(lon=self.phi, lat=90 * u.deg - self.theta)\n\n return super().represent_as(other_class, differential_class)\n\n def to_cartesian(self):\n \"\"\"\n Converts spherical polar coordinates to 3D rectangular cartesian\n coordinates.\n \"\"\"\n\n # We need to convert Distance to Quantity to allow negative values.\n if isinstance(self.r, Distance):\n d = self.r.view(u.Quantity)\n else:\n d = self.r\n\n x = d * np.sin(self.theta) * np.cos(self.phi)\n y = d * np.sin(self.theta) * np.sin(self.phi)\n z = d * np.cos(self.theta)\n\n return CartesianRepresentation(x=x, y=y, z=z, copy=False)\n\n @classmethod\n def from_cartesian(cls, cart):\n \"\"\"\n Converts 3D rectangular cartesian coordinates to spherical polar\n coordinates.\n \"\"\"\n\n s = np.hypot(cart.x, cart.y)\n r = np.hypot(s, cart.z)\n\n phi = np.arctan2(cart.y, cart.x)\n theta = np.arctan2(s, cart.z)\n\n return cls(phi=phi, theta=theta, r=r, copy=False)\n\n def norm(self):\n \"\"\"Vector norm.\n\n The norm is the standard Frobenius norm, i.e., the square root of the\n sum of the squares of all components with non-angular units. For\n spherical coordinates, this is just the absolute value of the radius.\n\n Returns\n -------\n norm : `astropy.units.Quantity`\n Vector norm, with the same shape as the representation.\n \"\"\"\n return np.abs(self.r)\n\n\nclass CylindricalRepresentation(BaseRepresentation):\n \"\"\"\n Representation of points in 3D cylindrical coordinates.\n\n Parameters\n ----------\n rho : `~astropy.units.Quantity`\n The distance from the z axis to the point(s).\n\n phi : `~astropy.units.Quantity` or str\n The azimuth of the point(s), in angular units, which will be wrapped\n to an angle between 0 and 360 degrees. This can also be instances of\n `~astropy.coordinates.Angle`,\n\n z : `~astropy.units.Quantity`\n The z coordinate(s) of the point(s)\n\n differentials : dict, `CylindricalDifferential`, optional\n Any differential classes that should be associated with this\n representation. The input must either be a single\n `CylindricalDifferential` instance, or a dictionary of of differential\n instances with keys set to a string representation of the SI unit with\n which the differential (derivative) is taken. For example, for a\n velocity differential on a positional representation, the key would be\n ``'s'`` for seconds, indicating that the derivative is a time\n derivative.\n\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n\n attr_classes = OrderedDict([('rho', u.Quantity),\n ('phi', Angle),\n ('z', u.Quantity)])\n\n def __init__(self, rho, phi=None, z=None, differentials=None, copy=True):\n super().__init__(rho, phi, z, copy=copy, differentials=differentials)\n\n if not self._rho.unit.is_equivalent(self._z.unit):\n raise u.UnitsError(\"rho and z should have matching physical types\")\n\n @property\n def rho(self):\n \"\"\"\n The distance of the point(s) from the z-axis.\n \"\"\"\n return self._rho\n\n @property\n def phi(self):\n \"\"\"\n The azimuth of the point(s).\n \"\"\"\n return self._phi\n\n @property\n def z(self):\n \"\"\"\n The height of the point(s).\n \"\"\"\n return self._z\n\n def unit_vectors(self):\n sinphi, cosphi = np.sin(self.phi), np.cos(self.phi)\n l = np.broadcast_to(1., self.shape)\n return OrderedDict(\n (('rho', CartesianRepresentation(cosphi, sinphi, 0, copy=False)),\n ('phi', CartesianRepresentation(-sinphi, cosphi, 0, copy=False)),\n ('z', CartesianRepresentation(0, 0, l, unit=u.one, copy=False))))\n\n def scale_factors(self):\n rho = self.rho / u.radian\n l = np.broadcast_to(1.*u.one, self.shape, subok=True)\n return OrderedDict((('rho', l),\n ('phi', rho),\n ('z', l)))\n\n @classmethod\n def from_cartesian(cls, cart):\n \"\"\"\n Converts 3D rectangular cartesian coordinates to cylindrical polar\n coordinates.\n \"\"\"\n\n rho = np.hypot(cart.x, cart.y)\n phi = np.arctan2(cart.y, cart.x)\n z = cart.z\n\n return cls(rho=rho, phi=phi, z=z, copy=False)\n\n def to_cartesian(self):\n \"\"\"\n Converts cylindrical polar coordinates to 3D rectangular cartesian\n coordinates.\n \"\"\"\n x = self.rho * np.cos(self.phi)\n y = self.rho * np.sin(self.phi)\n z = self.z\n\n return CartesianRepresentation(x=x, y=y, z=z, copy=False)\n\n\nclass MetaBaseDifferential(abc.ABCMeta):\n \"\"\"Set default ``attr_classes`` and component getters on a Differential.\n\n For these, the components are those of the base representation prefixed\n by 'd_', and the class is `~astropy.units.Quantity`.\n \"\"\"\n def __init__(cls, name, bases, dct):\n super().__init__(name, bases, dct)\n\n # Don't do anything for base helper classes.\n if cls.__name__ in ('BaseDifferential', 'BaseSphericalDifferential',\n 'BaseSphericalCosLatDifferential'):\n return\n\n if 'base_representation' not in dct:\n raise NotImplementedError('Differential representations must have a'\n '\"base_representation\" class attribute.')\n\n # If not defined explicitly, create attr_classes.\n if not hasattr(cls, 'attr_classes'):\n base_attr_classes = cls.base_representation.attr_classes\n cls.attr_classes = OrderedDict([('d_' + c, u.Quantity)\n for c in base_attr_classes])\n\n repr_name = cls.get_name()\n if repr_name in DIFFERENTIAL_CLASSES:\n raise ValueError(\"Differential class {} already defined\"\n .format(repr_name))\n\n DIFFERENTIAL_CLASSES[repr_name] = cls\n _invalidate_reprdiff_cls_hash()\n\n # If not defined explicitly, create properties for the components.\n for component in cls.attr_classes:\n if not hasattr(cls, component):\n setattr(cls, component,\n property(_make_getter(component),\n doc=(\"Component '{}' of the Differential.\"\n .format(component))))\n\n\nclass BaseDifferential(BaseRepresentationOrDifferential,\n metaclass=MetaBaseDifferential):\n r\"\"\"A base class representing differentials of representations.\n\n These represent differences or derivatives along each component.\n E.g., for physics spherical coordinates, these would be\n :math:`\\delta r, \\delta \\theta, \\delta \\phi`.\n\n Parameters\n ----------\n d_comp1, d_comp2, d_comp3 : `~astropy.units.Quantity` or subclass\n The components of the 3D differentials. The names are the keys and the\n subclasses the values of the ``attr_classes`` attribute.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n\n Notes\n -----\n All differential representation classes should subclass this base class,\n and define an ``base_representation`` attribute with the class of the\n regular `~astropy.coordinates.BaseRepresentation` for which differential\n coordinates are provided. This will set up a default ``attr_classes``\n instance with names equal to the base component names prefixed by ``d_``,\n and all classes set to `~astropy.units.Quantity`, plus properties to access\n those, and a default ``__init__`` for initialization.\n \"\"\"\n\n @classmethod\n def _check_base(cls, base):\n if cls not in base._compatible_differentials:\n raise TypeError(\"Differential class {} is not compatible with the \"\n \"base (representation) class {}\"\n .format(cls, base.__class__))\n\n def _get_deriv_key(self, base):\n \"\"\"Given a base (representation instance), determine the unit of the\n derivative by removing the representation unit from the component units\n of this differential.\n \"\"\"\n\n # This check is just a last resort so we don't return a strange unit key\n # from accidentally passing in the wrong base.\n self._check_base(base)\n\n for name in base.components:\n comp = getattr(base, name)\n d_comp = getattr(self, f'd_{name}', None)\n if d_comp is not None:\n d_unit = comp.unit / d_comp.unit\n\n # This is quite a bit faster than using to_system() or going\n # through Quantity()\n d_unit_si = d_unit.decompose(u.si.bases)\n d_unit_si._scale = 1 # remove the scale from the unit\n\n return str(d_unit_si)\n\n else:\n raise RuntimeError(\"Invalid representation-differential units! This\"\n \" likely happened because either the \"\n \"representation or the associated differential \"\n \"have non-standard units. Check that the input \"\n \"positional data have positional units, and the \"\n \"input velocity data have velocity units, or \"\n \"are both dimensionless.\")\n\n @classmethod\n def _get_base_vectors(cls, base):\n \"\"\"Get unit vectors and scale factors from base.\n\n Parameters\n ----------\n base : instance of ``self.base_representation``\n The points for which the unit vectors and scale factors should be\n retrieved.\n\n Returns\n -------\n unit_vectors : dict of `CartesianRepresentation`\n In the directions of the coordinates of base.\n scale_factors : dict of `~astropy.units.Quantity`\n Scale factors for each of the coordinates\n\n Raises\n ------\n TypeError : if the base is not of the correct type\n \"\"\"\n cls._check_base(base)\n return base.unit_vectors(), base.scale_factors()\n\n def to_cartesian(self, base):\n \"\"\"Convert the differential to 3D rectangular cartesian coordinates.\n\n Parameters\n ----------\n base : instance of ``self.base_representation``\n The points for which the differentials are to be converted: each of\n the components is multiplied by its unit vectors and scale factors.\n\n Returns\n -------\n This object as a `CartesianDifferential`\n \"\"\"\n base_e, base_sf = self._get_base_vectors(base)\n return functools.reduce(\n operator.add, (getattr(self, d_c) * base_sf[c] * base_e[c]\n for d_c, c in zip(self.components, base.components)))\n\n @classmethod\n def from_cartesian(cls, other, base):\n \"\"\"Convert the differential from 3D rectangular cartesian coordinates to\n the desired class.\n\n Parameters\n ----------\n other :\n The object to convert into this differential.\n base : instance of ``self.base_representation``\n The points for which the differentials are to be converted: each of\n the components is multiplied by its unit vectors and scale factors.\n\n Returns\n -------\n A new differential object that is this class' type.\n \"\"\"\n base_e, base_sf = cls._get_base_vectors(base)\n return cls(*(other.dot(e / base_sf[component])\n for component, e in base_e.items()), copy=False)\n\n def represent_as(self, other_class, base):\n \"\"\"Convert coordinates to another representation.\n\n If the instance is of the requested class, it is returned unmodified.\n By default, conversion is done via cartesian coordinates.\n\n Parameters\n ----------\n other_class : `~astropy.coordinates.BaseRepresentation` subclass\n The type of representation to turn the coordinates into.\n base : instance of ``self.base_representation``, optional\n Base relative to which the differentials are defined. If the other\n class is a differential representation, the base will be converted\n to its ``base_representation``.\n \"\"\"\n if other_class is self.__class__:\n return self\n\n # The default is to convert via cartesian coordinates.\n self_cartesian = self.to_cartesian(base)\n if issubclass(other_class, BaseDifferential):\n base = base.represent_as(other_class.base_representation)\n return other_class.from_cartesian(self_cartesian, base)\n else:\n return other_class.from_cartesian(self_cartesian)\n\n @classmethod\n def from_representation(cls, representation, base):\n \"\"\"Create a new instance of this representation from another one.\n\n Parameters\n ----------\n representation : `~astropy.coordinates.BaseRepresentation` instance\n The presentation that should be converted to this class.\n base : instance of ``cls.base_representation``\n The base relative to which the differentials will be defined. If\n the representation is a differential itself, the base will be\n converted to its ``base_representation`` to help convert it.\n \"\"\"\n if isinstance(representation, BaseDifferential):\n cartesian = representation.to_cartesian(\n base.represent_as(representation.base_representation))\n else:\n cartesian = representation.to_cartesian()\n\n return cls.from_cartesian(cartesian, base)\n\n def _scale_operation(self, op, *args):\n \"\"\"Scale all components.\n\n Parameters\n ----------\n op : `~operator` callable\n Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc.\n *args\n Any arguments required for the operator (typically, what is to\n be multiplied with, divided by).\n \"\"\"\n scaled_attrs = [op(getattr(self, c), *args) for c in self.components]\n return self.__class__(*scaled_attrs, copy=False)\n\n def _combine_operation(self, op, other, reverse=False):\n \"\"\"Combine two differentials, or a differential with a representation.\n\n If ``other`` is of the same differential type as ``self``, the\n components will simply be combined. If ``other`` is a representation,\n it will be used as a base for which to evaluate the differential,\n and the result is a new representation.\n\n Parameters\n ----------\n op : `~operator` callable\n Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.\n other : `~astropy.coordinates.BaseRepresentation` instance\n The other differential or representation.\n reverse : bool\n Whether the operands should be reversed (e.g., as we got here via\n ``self.__rsub__`` because ``self`` is a subclass of ``other``).\n \"\"\"\n if isinstance(self, type(other)):\n first, second = (self, other) if not reverse else (other, self)\n return self.__class__(*[op(getattr(first, c), getattr(second, c))\n for c in self.components])\n else:\n try:\n self_cartesian = self.to_cartesian(other)\n except TypeError:\n return NotImplemented\n\n return other._combine_operation(op, self_cartesian, not reverse)\n\n def __sub__(self, other):\n # avoid \"differential - representation\".\n if isinstance(other, BaseRepresentation):\n return NotImplemented\n return super().__sub__(other)\n\n def norm(self, base=None):\n \"\"\"Vector norm.\n\n The norm is the standard Frobenius norm, i.e., the square root of the\n sum of the squares of all components with non-angular units.\n\n Parameters\n ----------\n base : instance of ``self.base_representation``\n Base relative to which the differentials are defined. This is\n required to calculate the physical size of the differential for\n all but cartesian differentials.\n\n Returns\n -------\n norm : `astropy.units.Quantity`\n Vector norm, with the same shape as the representation.\n \"\"\"\n return self.to_cartesian(base).norm()\n\n\nclass CartesianDifferential(BaseDifferential):\n \"\"\"Differentials in of points in 3D cartesian coordinates.\n\n Parameters\n ----------\n d_x, d_y, d_z : `~astropy.units.Quantity` or array\n The x, y, and z coordinates of the differentials. If ``d_x``, ``d_y``,\n and ``d_z`` have different shapes, they should be broadcastable. If not\n quantities, ``unit`` should be set. If only ``d_x`` is given, it is\n assumed that it contains an array with the 3 coordinates stored along\n ``xyz_axis``.\n unit : `~astropy.units.Unit` or str\n If given, the differentials will be converted to this unit (or taken to\n be in this unit if not given.\n xyz_axis : int, optional\n The axis along which the coordinates are stored when a single array is\n provided instead of distinct ``d_x``, ``d_y``, and ``d_z`` (default: 0).\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = CartesianRepresentation\n _d_xyz = None\n\n def __init__(self, d_x, d_y=None, d_z=None, unit=None, xyz_axis=None,\n copy=True):\n\n if d_y is None and d_z is None:\n if isinstance(d_x, np.ndarray) and d_x.dtype.kind not in 'OV':\n # Short-cut for 3-D array input.\n d_x = u.Quantity(d_x, unit, copy=copy, subok=True)\n # Keep a link to the array with all three coordinates\n # so that we can return it quickly if needed in get_xyz.\n self._d_xyz = d_x\n if xyz_axis:\n d_x = np.moveaxis(d_x, xyz_axis, 0)\n self._xyz_axis = xyz_axis\n else:\n self._xyz_axis = 0\n\n self._d_x, self._d_y, self._d_z = d_x\n return\n\n else:\n d_x, d_y, d_z = d_x\n\n if xyz_axis is not None:\n raise ValueError(\"xyz_axis should only be set if d_x, d_y, and d_z \"\n \"are in a single array passed in through d_x, \"\n \"i.e., d_y and d_z should not be not given.\")\n\n if d_y is None or d_z is None:\n raise ValueError(\"d_x, d_y, and d_z are required to instantiate {}\"\n .format(self.__class__.__name__))\n\n if unit is not None:\n d_x = u.Quantity(d_x, unit, copy=copy, subok=True)\n d_y = u.Quantity(d_y, unit, copy=copy, subok=True)\n d_z = u.Quantity(d_z, unit, copy=copy, subok=True)\n copy = False\n\n super().__init__(d_x, d_y, d_z, copy=copy)\n if not (self._d_x.unit.is_equivalent(self._d_y.unit) and\n self._d_x.unit.is_equivalent(self._d_z.unit)):\n raise u.UnitsError('d_x, d_y and d_z should have equivalent units.')\n\n def to_cartesian(self, base=None):\n return CartesianRepresentation(*[getattr(self, c) for c\n in self.components])\n\n @classmethod\n def from_cartesian(cls, other, base=None):\n return cls(*[getattr(other, c) for c in other.components])\n\n def get_d_xyz(self, xyz_axis=0):\n \"\"\"Return a vector array of the x, y, and z coordinates.\n\n Parameters\n ----------\n xyz_axis : int, optional\n The axis in the final array along which the x, y, z components\n should be stored (default: 0).\n\n Returns\n -------\n d_xyz : `~astropy.units.Quantity`\n With dimension 3 along ``xyz_axis``. Note that, if possible,\n this will be a view.\n \"\"\"\n if self._d_xyz is not None:\n if self._xyz_axis == xyz_axis:\n return self._d_xyz\n else:\n return np.moveaxis(self._d_xyz, self._xyz_axis, xyz_axis)\n\n # Create combined array. TO DO: keep it in _d_xyz for repeated use?\n # But then in-place changes have to cancel it. Likely best to\n # also update components.\n return _combine_xyz(self._d_x, self._d_y, self._d_z, xyz_axis=xyz_axis)\n\n d_xyz = property(get_d_xyz)\n\n\nclass BaseSphericalDifferential(BaseDifferential):\n def _d_lon_coslat(self, base):\n \"\"\"Convert longitude differential d_lon to d_lon_coslat.\n\n Parameters\n ----------\n base : instance of ``cls.base_representation``\n The base from which the latitude will be taken.\n \"\"\"\n self._check_base(base)\n return self.d_lon * np.cos(base.lat)\n\n @classmethod\n def _get_d_lon(cls, d_lon_coslat, base):\n \"\"\"Convert longitude differential d_lon_coslat to d_lon.\n\n Parameters\n ----------\n d_lon_coslat : `~astropy.units.Quantity`\n Longitude differential that includes ``cos(lat)``.\n base : instance of ``cls.base_representation``\n The base from which the latitude will be taken.\n \"\"\"\n cls._check_base(base)\n return d_lon_coslat / np.cos(base.lat)\n\n def _combine_operation(self, op, other, reverse=False):\n \"\"\"Combine two differentials, or a differential with a representation.\n\n If ``other`` is of the same differential type as ``self``, the\n components will simply be combined. If both are different parts of\n a `~astropy.coordinates.SphericalDifferential` (e.g., a\n `~astropy.coordinates.UnitSphericalDifferential` and a\n `~astropy.coordinates.RadialDifferential`), they will combined\n appropriately.\n\n If ``other`` is a representation, it will be used as a base for which\n to evaluate the differential, and the result is a new representation.\n\n Parameters\n ----------\n op : `~operator` callable\n Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.\n other : `~astropy.coordinates.BaseRepresentation` instance\n The other differential or representation.\n reverse : bool\n Whether the operands should be reversed (e.g., as we got here via\n ``self.__rsub__`` because ``self`` is a subclass of ``other``).\n \"\"\"\n if (isinstance(other, BaseSphericalDifferential) and\n not isinstance(self, type(other)) or\n isinstance(other, RadialDifferential)):\n all_components = set(self.components) | set(other.components)\n first, second = (self, other) if not reverse else (other, self)\n result_args = {c: op(getattr(first, c, 0.), getattr(second, c, 0.))\n for c in all_components}\n return SphericalDifferential(**result_args)\n\n return super()._combine_operation(op, other, reverse)\n\n\nclass UnitSphericalDifferential(BaseSphericalDifferential):\n \"\"\"Differential(s) of points on a unit sphere.\n\n Parameters\n ----------\n d_lon, d_lat : `~astropy.units.Quantity`\n The longitude and latitude of the differentials.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = UnitSphericalRepresentation\n\n @classproperty\n def _dimensional_differential(cls):\n return SphericalDifferential\n\n def __init__(self, d_lon, d_lat=None, copy=True):\n super().__init__(d_lon, d_lat, copy=copy)\n if not self._d_lon.unit.is_equivalent(self._d_lat.unit):\n raise u.UnitsError('d_lon and d_lat should have equivalent units.')\n\n def to_cartesian(self, base):\n if isinstance(base, SphericalRepresentation):\n scale = base.distance\n elif isinstance(base, PhysicsSphericalRepresentation):\n scale = base.r\n else:\n return super().to_cartesian(base)\n\n base = base.represent_as(UnitSphericalRepresentation)\n return scale * super().to_cartesian(base)\n\n def represent_as(self, other_class, base=None):\n # Only have enough information to represent other unit-spherical.\n if issubclass(other_class, UnitSphericalCosLatDifferential):\n return other_class(self._d_lon_coslat(base), self.d_lat)\n\n return super().represent_as(other_class, base)\n\n @classmethod\n def from_representation(cls, representation, base=None):\n # All spherical differentials can be done without going to Cartesian,\n # though CosLat needs base for the latitude.\n if isinstance(representation, SphericalDifferential):\n return cls(representation.d_lon, representation.d_lat)\n elif isinstance(representation, (SphericalCosLatDifferential,\n UnitSphericalCosLatDifferential)):\n d_lon = cls._get_d_lon(representation.d_lon_coslat, base)\n return cls(d_lon, representation.d_lat)\n elif isinstance(representation, PhysicsSphericalDifferential):\n return cls(representation.d_phi, -representation.d_theta)\n\n return super().from_representation(representation, base)\n\n\nclass SphericalDifferential(BaseSphericalDifferential):\n \"\"\"Differential(s) of points in 3D spherical coordinates.\n\n Parameters\n ----------\n d_lon, d_lat : `~astropy.units.Quantity`\n The differential longitude and latitude.\n d_distance : `~astropy.units.Quantity`\n The differential distance.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = SphericalRepresentation\n _unit_differential = UnitSphericalDifferential\n\n def __init__(self, d_lon, d_lat=None, d_distance=None, copy=True):\n super().__init__(d_lon, d_lat, d_distance, copy=copy)\n if not self._d_lon.unit.is_equivalent(self._d_lat.unit):\n raise u.UnitsError('d_lon and d_lat should have equivalent units.')\n\n def represent_as(self, other_class, base=None):\n # All spherical differentials can be done without going to Cartesian,\n # though CosLat needs base for the latitude.\n if issubclass(other_class, UnitSphericalDifferential):\n return other_class(self.d_lon, self.d_lat)\n elif issubclass(other_class, RadialDifferential):\n return other_class(self.d_distance)\n elif issubclass(other_class, SphericalCosLatDifferential):\n return other_class(self._d_lon_coslat(base), self.d_lat,\n self.d_distance)\n elif issubclass(other_class, UnitSphericalCosLatDifferential):\n return other_class(self._d_lon_coslat(base), self.d_lat)\n elif issubclass(other_class, PhysicsSphericalDifferential):\n return other_class(self.d_lon, -self.d_lat, self.d_distance)\n else:\n return super().represent_as(other_class, base)\n\n @classmethod\n def from_representation(cls, representation, base=None):\n # Other spherical differentials can be done without going to Cartesian,\n # though CosLat needs base for the latitude.\n if isinstance(representation, SphericalCosLatDifferential):\n d_lon = cls._get_d_lon(representation.d_lon_coslat, base)\n return cls(d_lon, representation.d_lat, representation.d_distance)\n elif isinstance(representation, PhysicsSphericalDifferential):\n return cls(representation.d_phi, -representation.d_theta,\n representation.d_r)\n\n return super().from_representation(representation, base)\n\n\nclass BaseSphericalCosLatDifferential(BaseDifferential):\n \"\"\"Differentials from points on a spherical base representation.\n\n With cos(lat) assumed to be included in the longitude differential.\n \"\"\"\n @classmethod\n def _get_base_vectors(cls, base):\n \"\"\"Get unit vectors and scale factors from (unit)spherical base.\n\n Parameters\n ----------\n base : instance of ``self.base_representation``\n The points for which the unit vectors and scale factors should be\n retrieved.\n\n Returns\n -------\n unit_vectors : dict of `CartesianRepresentation`\n In the directions of the coordinates of base.\n scale_factors : dict of `~astropy.units.Quantity`\n Scale factors for each of the coordinates. The scale factor for\n longitude does not include the cos(lat) factor.\n\n Raises\n ------\n TypeError : if the base is not of the correct type\n \"\"\"\n cls._check_base(base)\n return base.unit_vectors(), base.scale_factors(omit_coslat=True)\n\n def _d_lon(self, base):\n \"\"\"Convert longitude differential with cos(lat) to one without.\n\n Parameters\n ----------\n base : instance of ``cls.base_representation``\n The base from which the latitude will be taken.\n \"\"\"\n self._check_base(base)\n return self.d_lon_coslat / np.cos(base.lat)\n\n @classmethod\n def _get_d_lon_coslat(cls, d_lon, base):\n \"\"\"Convert longitude differential d_lon to d_lon_coslat.\n\n Parameters\n ----------\n d_lon : `~astropy.units.Quantity`\n Value of the longitude differential without ``cos(lat)``.\n base : instance of ``cls.base_representation``\n The base from which the latitude will be taken.\n \"\"\"\n cls._check_base(base)\n return d_lon * np.cos(base.lat)\n\n def _combine_operation(self, op, other, reverse=False):\n \"\"\"Combine two differentials, or a differential with a representation.\n\n If ``other`` is of the same differential type as ``self``, the\n components will simply be combined. If both are different parts of\n a `~astropy.coordinates.SphericalDifferential` (e.g., a\n `~astropy.coordinates.UnitSphericalDifferential` and a\n `~astropy.coordinates.RadialDifferential`), they will combined\n appropriately.\n\n If ``other`` is a representation, it will be used as a base for which\n to evaluate the differential, and the result is a new representation.\n\n Parameters\n ----------\n op : `~operator` callable\n Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.\n other : `~astropy.coordinates.BaseRepresentation` instance\n The other differential or representation.\n reverse : bool\n Whether the operands should be reversed (e.g., as we got here via\n ``self.__rsub__`` because ``self`` is a subclass of ``other``).\n \"\"\"\n if (isinstance(other, BaseSphericalCosLatDifferential) and\n not isinstance(self, type(other)) or\n isinstance(other, RadialDifferential)):\n all_components = set(self.components) | set(other.components)\n first, second = (self, other) if not reverse else (other, self)\n result_args = {c: op(getattr(first, c, 0.), getattr(second, c, 0.))\n for c in all_components}\n return SphericalCosLatDifferential(**result_args)\n\n return super()._combine_operation(op, other, reverse)\n\n\nclass UnitSphericalCosLatDifferential(BaseSphericalCosLatDifferential):\n \"\"\"Differential(s) of points on a unit sphere.\n\n Parameters\n ----------\n d_lon_coslat, d_lat : `~astropy.units.Quantity`\n The longitude and latitude of the differentials.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = UnitSphericalRepresentation\n attr_classes = OrderedDict([('d_lon_coslat', u.Quantity),\n ('d_lat', u.Quantity)])\n\n @classproperty\n def _dimensional_differential(cls):\n return SphericalCosLatDifferential\n\n def __init__(self, d_lon_coslat, d_lat=None, copy=True):\n super().__init__(d_lon_coslat, d_lat, copy=copy)\n if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit):\n raise u.UnitsError('d_lon_coslat and d_lat should have equivalent '\n 'units.')\n\n def to_cartesian(self, base):\n if isinstance(base, SphericalRepresentation):\n scale = base.distance\n elif isinstance(base, PhysicsSphericalRepresentation):\n scale = base.r\n else:\n return super().to_cartesian(base)\n\n base = base.represent_as(UnitSphericalRepresentation)\n return scale * super().to_cartesian(base)\n\n def represent_as(self, other_class, base=None):\n # Only have enough information to represent other unit-spherical.\n if issubclass(other_class, UnitSphericalDifferential):\n return other_class(self._d_lon(base), self.d_lat)\n\n return super().represent_as(other_class, base)\n\n @classmethod\n def from_representation(cls, representation, base=None):\n # All spherical differentials can be done without going to Cartesian,\n # though w/o CosLat needs base for the latitude.\n if isinstance(representation, SphericalCosLatDifferential):\n return cls(representation.d_lon_coslat, representation.d_lat)\n elif isinstance(representation, (SphericalDifferential,\n UnitSphericalDifferential)):\n d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base)\n return cls(d_lon_coslat, representation.d_lat)\n elif isinstance(representation, PhysicsSphericalDifferential):\n d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base)\n return cls(d_lon_coslat, -representation.d_theta)\n\n return super().from_representation(representation, base)\n\n\nclass SphericalCosLatDifferential(BaseSphericalCosLatDifferential):\n \"\"\"Differential(s) of points in 3D spherical coordinates.\n\n Parameters\n ----------\n d_lon_coslat, d_lat : `~astropy.units.Quantity`\n The differential longitude (with cos(lat) included) and latitude.\n d_distance : `~astropy.units.Quantity`\n The differential distance.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = SphericalRepresentation\n _unit_differential = UnitSphericalCosLatDifferential\n attr_classes = OrderedDict([('d_lon_coslat', u.Quantity),\n ('d_lat', u.Quantity),\n ('d_distance', u.Quantity)])\n\n def __init__(self, d_lon_coslat, d_lat=None, d_distance=None, copy=True):\n super().__init__(d_lon_coslat, d_lat, d_distance, copy=copy)\n if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit):\n raise u.UnitsError('d_lon_coslat and d_lat should have equivalent '\n 'units.')\n\n def represent_as(self, other_class, base=None):\n # All spherical differentials can be done without going to Cartesian,\n # though some need base for the latitude to remove cos(lat).\n if issubclass(other_class, UnitSphericalCosLatDifferential):\n return other_class(self.d_lon_coslat, self.d_lat)\n elif issubclass(other_class, RadialDifferential):\n return other_class(self.d_distance)\n elif issubclass(other_class, SphericalDifferential):\n return other_class(self._d_lon(base), self.d_lat, self.d_distance)\n elif issubclass(other_class, UnitSphericalDifferential):\n return other_class(self._d_lon(base), self.d_lat)\n elif issubclass(other_class, PhysicsSphericalDifferential):\n return other_class(self._d_lon(base), -self.d_lat, self.d_distance)\n\n return super().represent_as(other_class, base)\n\n @classmethod\n def from_representation(cls, representation, base=None):\n # Other spherical differentials can be done without going to Cartesian,\n # though we need base for the latitude to remove coslat.\n if isinstance(representation, SphericalDifferential):\n d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base)\n return cls(d_lon_coslat, representation.d_lat,\n representation.d_distance)\n elif isinstance(representation, PhysicsSphericalDifferential):\n d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base)\n return cls(d_lon_coslat, -representation.d_theta,\n representation.d_r)\n\n return super().from_representation(representation, base)\n\n\nclass RadialDifferential(BaseDifferential):\n \"\"\"Differential(s) of radial distances.\n\n Parameters\n ----------\n d_distance : `~astropy.units.Quantity`\n The differential distance.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = RadialRepresentation\n\n def to_cartesian(self, base):\n return self.d_distance * base.represent_as(\n UnitSphericalRepresentation).to_cartesian()\n\n @classmethod\n def from_cartesian(cls, other, base):\n return cls(other.dot(base.represent_as(UnitSphericalRepresentation)),\n copy=False)\n\n @classmethod\n def from_representation(cls, representation, base=None):\n if isinstance(representation, (SphericalDifferential,\n SphericalCosLatDifferential)):\n return cls(representation.d_distance)\n elif isinstance(representation, PhysicsSphericalDifferential):\n return cls(representation.d_r)\n else:\n return super().from_representation(representation, base)\n\n def _combine_operation(self, op, other, reverse=False):\n if isinstance(other, self.base_representation):\n if reverse:\n first, second = other.distance, self.d_distance\n else:\n first, second = self.d_distance, other.distance\n return other.__class__(op(first, second), copy=False)\n elif isinstance(other, (BaseSphericalDifferential,\n BaseSphericalCosLatDifferential)):\n all_components = set(self.components) | set(other.components)\n first, second = (self, other) if not reverse else (other, self)\n result_args = {c: op(getattr(first, c, 0.), getattr(second, c, 0.))\n for c in all_components}\n return SphericalDifferential(**result_args)\n\n else:\n return super()._combine_operation(op, other, reverse)\n\n\nclass PhysicsSphericalDifferential(BaseDifferential):\n \"\"\"Differential(s) of 3D spherical coordinates using physics convention.\n\n Parameters\n ----------\n d_phi, d_theta : `~astropy.units.Quantity`\n The differential azimuth and inclination.\n d_r : `~astropy.units.Quantity`\n The differential radial distance.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = PhysicsSphericalRepresentation\n\n def __init__(self, d_phi, d_theta=None, d_r=None, copy=True):\n super().__init__(d_phi, d_theta, d_r, copy=copy)\n if not self._d_phi.unit.is_equivalent(self._d_theta.unit):\n raise u.UnitsError('d_phi and d_theta should have equivalent '\n 'units.')\n\n def represent_as(self, other_class, base=None):\n # All spherical differentials can be done without going to Cartesian,\n # though CosLat needs base for the latitude. For those, explicitly\n # do the equivalent of self._d_lon_coslat in SphericalDifferential.\n if issubclass(other_class, SphericalDifferential):\n return other_class(self.d_phi, -self.d_theta, self.d_r)\n elif issubclass(other_class, UnitSphericalDifferential):\n return other_class(self.d_phi, -self.d_theta)\n elif issubclass(other_class, SphericalCosLatDifferential):\n self._check_base(base)\n d_lon_coslat = self.d_phi * np.sin(base.theta)\n return other_class(d_lon_coslat, -self.d_theta, self.d_r)\n elif issubclass(other_class, UnitSphericalCosLatDifferential):\n self._check_base(base)\n d_lon_coslat = self.d_phi * np.sin(base.theta)\n return other_class(d_lon_coslat, -self.d_theta)\n elif issubclass(other_class, RadialDifferential):\n return other_class(self.d_r)\n\n return super().represent_as(other_class, base)\n\n @classmethod\n def from_representation(cls, representation, base=None):\n # Other spherical differentials can be done without going to Cartesian,\n # though we need base for the latitude to remove coslat. For that case,\n # do the equivalent of cls._d_lon in SphericalDifferential.\n if isinstance(representation, SphericalDifferential):\n return cls(representation.d_lon, -representation.d_lat,\n representation.d_distance)\n elif isinstance(representation, SphericalCosLatDifferential):\n cls._check_base(base)\n d_phi = representation.d_lon_coslat / np.sin(base.theta)\n return cls(d_phi, -representation.d_lat, representation.d_distance)\n\n return super().from_representation(representation, base)\n\n\nclass CylindricalDifferential(BaseDifferential):\n \"\"\"Differential(s) of points in cylindrical coordinates.\n\n Parameters\n ----------\n d_rho : `~astropy.units.Quantity`\n The differential cylindrical radius.\n d_phi : `~astropy.units.Quantity`\n The differential azimuth.\n d_z : `~astropy.units.Quantity`\n The differential height.\n copy : bool, optional\n If `True` (default), arrays will be copied. If `False`, arrays will\n be references, though possibly broadcast to ensure matching shapes.\n \"\"\"\n base_representation = CylindricalRepresentation\n\n def __init__(self, d_rho, d_phi=None, d_z=None, copy=False):\n super().__init__(d_rho, d_phi, d_z, copy=copy)\n if not self._d_rho.unit.is_equivalent(self._d_z.unit):\n raise u.UnitsError(\"d_rho and d_z should have equivalent units.\")\n" ]
[ [ "numpy.logical_not", "numpy.abs", "numpy.cos", "numpy.stack", "numpy.sin", "numpy.arctan2", "numpy.broadcast", "numpy.ones", "numpy.broadcast_to", "numpy.any", "numpy.broadcast_arrays", "numpy.moveaxis", "numpy.array2string", "numpy.hypot", "numpy.zeros", "numpy.empty" ] ]
salukadev/FDM-Mini-Project
[ "300f13bac438d15aaa09bac466c9063db0885a7a" ]
[ "app/dashboard/layout.py" ]
[ "from dash import dcc\nfrom dash import html\nimport dash_bootstrap_components as dbc\nfrom ..Plots import alzheimer_clusterringPlot as ac\nimport plotly.graph_objs as go\n\nimport plotly.express as px\nimport pandas as pd\nimport os\n# navbar = \nfig2 = ac.alzheimer_clusterPlot()\nfig2.update_layout({\n\"plot_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"paper_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"font_color\":\"white\",\n\"legend_font_color\" : \"white\"\n})\n\n\n#data retrieval alzheimer\nalzheimerlength = pd.read_csv(\"app/datasets/alzheimer.csv\")\nalzheimerdatalength = len(alzheimerlength)\n\ndementedPatients = alzheimerlength[alzheimerlength['Group'].str.contains('Demented')]\ndementedPatients = len(dementedPatients)\n\nnoncritical = alzheimerlength[alzheimerlength['Group'].str.contains('Converted')]\nnoncritical = len(noncritical)\n\n#data retrieval covid 19\ncovidlength = pd.read_csv(\"app/datasets/covid-19 symptoms dataset.csv\")\ncovidDatalength = len(covidlength)\n\n# covidPatients = covidlength[covidlength['infectionProb'].str.contains(1)]\n\n\n#pie chart plot \npieChartFig = px.pie(alzheimerlength, values='MMSE', names='Group')\npieChartFig.update_layout({\n\"plot_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"paper_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"font_color\":\"white\",\n\"legend_font_color\" : \"white\"\n})\n\npieChartFig2 = px.pie(alzheimerlength, names='M/F', color='M/F', color_discrete_sequence=px.colors.sequential.RdBu)\npieChartFig2.update_layout({\n\"plot_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"paper_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"font_color\":\"white\",\n\"legend_font_color\" : \"white\"\n})\n\npieChartFig3 = px.pie(alzheimerlength, names='CDR', color_discrete_sequence=px.colors.sequential.RdBu)\npieChartFig3.update_layout({\n\"plot_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"paper_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"font_color\":\"white\",\n\"legend_font_color\" : \"white\"\n})\n\n#covid plots\na = ['Total cases', 'Confirmed cases', 'Non-critical cases']\nfigc1 = go.Figure([go.Bar(x=a, y=[2575, 1005, 1570])])\nfigc1.update_layout({\n\"plot_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"paper_bgcolor\": \"rgba(0, 0, 0, 0)\",\n\"font_color\":\"white\",\n\"legend_font_color\" : \"white\",\n# \"coloraxis\" : \"red\"\n})\n\nfigc2 = px.pie(covidlength, names='bodyPain', color='bodyPain', color_discrete_sequence=px.colors.sequential.RdBu)\nfigc3 = px.pie(covidlength, names='fever', color='fever', color_discrete_sequence=px.colors.sequential.RdBu)\n\ndf = px.data.iris()\nfig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',\n color='species')\n\nlayout = html.Div(id='main', children=[\n dbc.NavbarSimple(\n children=[\n dbc.NavItem(dbc.NavLink(\"Page 1\", href=\"#\")),\n dbc.DropdownMenu(\n children=[\n dbc.DropdownMenuItem(\"More pages\", header=True),\n dbc.DropdownMenuItem(\"Page 2\", href=\"#\"),\n dbc.DropdownMenuItem(\"Page 3\", href=\"#\"),\n ],\n nav=True,\n in_navbar=True,\n label=\"More\",\n ),\n ],\n brand=\"AI Doc Dasboard\",\n brand_href=\"#\",\n color=\"black\",\n dark=True,\n ),\n\n html.Div(\n [\n html.H4(\"Alzheimer\", className=\"card-title\",style={\"color\": \"white\", \"margin\": \"10px\"}), \n dbc.Row(\n [\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Total visits\", className=\"card-title\"),\n html.H1(alzheimerdatalength, className=\"card-subtitle\"),\n # html.P(\n # \"Some quick example text to build on the card title and make \"\n # \"up the bulk of the card's content.\",\n # className=\"card-text\",\n # )\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\",\"color\": \"white\" ,\"background-color\":\"#2a2a72\", \"border-radius\":\"20px\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Confirmed cases\", className=\"card-title\"),\n html.H1(dementedPatients, className=\"card-subtitle\"),\n # html.P(\n # \"Some quick example text to build on the card title and make \"\n # \"up the bulk of the card's content.\",\n # className=\"card-text\",\n # ),\n # dbc.CardLink(\"Card link\", href=\"#\"),\n # dbc.CardLink(\"External link\", href=\"https://google.com\"),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\": \"white\" ,\"background-color\":\"red\", \"border-radius\":\"20px\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Non- Critical\", className=\"card-title\"),\n html.H1(noncritical, className=\"card-subtitle\"),\n # html.P(\n # \"Some quick example text to build on the card title and make \"\n # \"up the bulk of the card's content.\",\n # className=\"card-text\",\n # ),\n # dbc.CardLink(\"Card link\", href=\"#\"),\n # dbc.CardLink(\"External link\", href=\"https://google.com\"),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\": \"white\" ,\"background-color\":\"green\", \"border-radius\":\"20px\"},\n )\n )),\n ]\n ),\n\n\n dbc.Row(dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"\", className=\"card-title\"),\n html.P(\n \"Alzheimer's is the most common cause of dementia, a general term for memory loss and other cognitive abilities serious enough to interfere with daily life. Alzheimer's disease accounts for 60-80% of dementia cases.Alzheimer's is not a normal part of aging. The greatest known risk factor is increasing age, and the majority of people with Alzheimer's are 65 and older. Alzheimer’s disease is considered to be younger-onset Alzheimer’s if it affects a person under 65. Younger-onset can also be referred to as early-onset Alzheimer’s. People with younger-onset Alzheimer’s can be in the early, middle or late stage of the disease.\",\n className=\"card-text\",\n ),\n html.Center([\n html.H2(\"Alzheimer types Plot\", className=\"card-subtitle\"),\n dcc.Graph(id='plot2', figure = fig2 )\n ])\n\n \n # dbc.CardLink(\"Card link\", href=\"#\"),\n # dbc.CardLink(\"External link\", href=\"https://google.com\"),\n # dcc.Dropdown(\n # id='my-dropdown',\n # options=[\n # {'label': 'Coke', 'value': 'COKE'},\n # {'label': 'Tesla', 'value': 'TSLA'},\n # {'label': 'Apple', 'value': 'AAPL'}\n # ],\n # value='COKE'\n # ),\n # dcc.Graph(id='my-graph'),\n # dcc.Store(id='user-store'),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"black\"},\n )\n ))),\n\n\n dbc.Row(\n [\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Patient Types\", className=\"card-title\"),\n html.H6(\"(Alzheimers)\", className=\"card-subtitle\"),\n html.P(\n \"The following denotes the distribution of patients in the dataset\",\n className=\"card-text\",\n ),\n dbc.CardLink(\"Read more...\", href=\"#\"),\n \n dcc.Graph(id='plot3', figure = pieChartFig ),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"#323232\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Gender Proportion\", className=\"card-title\"),\n html.H6(\"(Alzheimers)\", className=\"card-subtitle\"),\n html.P(\n \"The following shows the gender proportion of Alzerimers patients\",\n className=\"card-text\",\n ),\n dbc.CardLink(\"Read more...\", href=\"#\"),\n dcc.Graph(id='plot4', figure = pieChartFig2 ),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"#323232\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Clinical Dimentia Rating\", className=\"card-title\"),\n html.H6(\"(Alzheimers)\", className=\"card-subtitle\"),\n html.P(\n \"CDR score affect mainly to predict the alzheimers patients\",\n className=\"card-text\",\n ),\n dbc.CardLink(\"Read more...\", href=\"#\"),\n dcc.Graph(id='plot5', figure = pieChartFig3 , style={\"plot_bgcolor\":\"rgba(0,0,0,0)\"}),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"#323232\"},\n )\n )),\n ]\n )\n ]),\n html.Div(\n [\n html.H4(\"COVID-19\", className=\"card-title\",style={\"color\": \"white\", \"margin\": \"10px\"}), \n dbc.Row(\n [\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Total visits\", className=\"card-title\"),\n html.H1(covidDatalength, className=\"card-subtitle\"),\n # html.P(\n # \"Some quick example text to build on the card title and make \"\n # \"up the bulk of the card's content.\",\n # className=\"card-text\",\n # )\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\",\"color\": \"white\" ,\"background-color\":\"#2a2a72\", \"border-radius\":\"20px\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Confirmed cases\", className=\"card-title\"),\n html.H1(\"1005\", className=\"card-subtitle\"),\n # html.P(\n # \"Some quick example text to build on the card title and make \"\n # \"up the bulk of the card's content.\",\n # className=\"card-text\",\n # ),\n # dbc.CardLink(\"Card link\", href=\"#\"),\n # dbc.CardLink(\"External link\", href=\"https://google.com\"),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\": \"white\" ,\"background-color\":\"red\", \"border-radius\":\"20px\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Non- Critical\", className=\"card-title\"),\n html.H1(\"1570\", className=\"card-subtitle\"),\n # html.P(\n # \"Some quick example text to build on the card title and make \"\n # \"up the bulk of the card's content.\",\n # className=\"card-text\",\n # ),\n # dbc.CardLink(\"Card link\", href=\"#\"),\n # dbc.CardLink(\"External link\", href=\"https://google.com\"),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\": \"white\" ,\"background-color\":\"green\", \"border-radius\":\"20px\"},\n )\n )),\n ]\n ),\n\n dbc.Row(dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Covid 19 data analysis\", className=\"card-title\"),\n html.H6(\"\", className=\"card-subtitle\"),\n html.P(\n \"Coronavirus disease 2019 (COVID-19), also known as COVID and the coronavirus, is a contagious disease caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2). The first known case was identified in Wuhan, China, in December 2019.The disease has since spread worldwide, leading to an ongoing pandemic. Symptoms of COVID-19 are variable, but often include fever, cough, headache, fatigue, breathing difficulties, and loss of smell and taste. Symptoms may begin one to fourteen days after exposure to the virus. At least a third of people who are infected do not develop noticeable symptoms. Of those people who develop symptoms noticeable enough to be classed as patients, most (81%) develop mild to moderate symptoms (up to mild pneumonia), while 14% develop severe symptoms\",\n className=\"card-text\",\n ),\n html.Center([\n dcc.Graph(id='plot6', figure = figc1 , style={\"plot_bgcolor\":\"rgba(0,0,0,0)\"}),\n ])\n\n \n # dbc.CardLink(\"Card link\", href=\"#\"),\n # dbc.CardLink(\"External link\", href=\"https://google.com\"),\n # dcc.Dropdown(\n # id='my-dropdown',\n # options=[\n # {'label': 'Coke', 'value': 'COKE'},\n # {'label': 'Tesla', 'value': 'TSLA'},\n # {'label': 'Apple', 'value': 'AAPL'}\n # ],\n # value='COKE'\n # ),\n # dcc.Graph(id='my-graph'),\n # dcc.Store(id='user-store'),\n ]\n ),\n style={\"width\": \"500\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"black\"},\n )\n ))),\n\n dbc.Row(\n [\n \n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Gender Variations\", className=\"card-title\"),\n html.H6(\"(COVID-19)\", className=\"card-subtitle\"),\n html.P(\n \"The following shows the gender diversity among covid patients.\",\n className=\"card-text\",\n ),\n dbc.CardLink(\"Read more...\", href=\"#\"),\n \n dcc.Graph(id='plot7', figure = figc2 , style={\"plot_bgcolor\":\"rgba(0,0,0,0)\"}),\n ]\n ),\n style={\"width\": \"200\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"#323232\"},\n )\n )),\n dbc.Col(html.Div(\n dbc.Card(\n dbc.CardBody(\n [\n html.H4(\"Fever level variation\", className=\"card-title\"),\n html.H6(\"(COVID-19)\", className=\"card-subtitle\"),\n html.P(\n \"Fever level of among covid patients is displayed below with respective tho the tempurature in Farenheit\",\n className=\"card-text\",\n ),\n dbc.CardLink(\"Read more...\", href=\"#\"),\n dcc.Graph(id='plot8', figure = figc3 , style={\"plot_bgcolor\":\"rgba(0,0,0,0)\"}),\n ]\n ),\n style={\"width\": \"200\", \"margin\": \"10px\", \"color\" : \"white\" ,\"background-color\":\"#323232\"},\n )\n )),\n\n\n ]\n ),\n ]\n)\n\n\n # html.H1(id='username'),\n # html.H1('Dashboard'),\n # dcc.Dropdown(\n # id='my-dropdown',\n # options=[\n # {'label': 'Coke', 'value': 'COKE'},\n # {'label': 'Tesla', 'value': 'TSLA'},\n # {'label': 'Apple', 'value': 'AAPL'}\n # ],\n # value='COKE'\n # ),\n # dcc.Graph(id='my-graph'),\n # dcc.Store(id='user-store'),\n], style={'width': '500', \"background-color\": \"black\", \"padding\" : \"20px\"})\n" ]
[ [ "pandas.read_csv" ] ]
GabCaz/Fixed-Income
[ "340538ec55f721527c5b3080fb5b438df9f7ce62" ]
[ "black_prices.py" ]
[ "'''\nFile to compute Black values for securities where a closed-form solution exists (caplets, caps...)\n'''\nimport numpy as np\nfrom utils import count_days\nfrom scipy.stats import norm\n\ndef hull_white_caplet(sigma, kappa, discount_factor, discount_factor_prev, d_settlement, strike, d_prev, d_mat, nominal=1):\n '''\n :param sigma: Hull-White sigma parameter\n :param kappa: Hull-White kappa parameter\n :param discount_factor: discount factor at the time of the caplet pays\n :param discount_factor_prev: discount factor at the d_prev time\n :param d_settlement:\n :param strike:\n :param d_prev: This is the previous, actual payment date\n :param d_mat: This is the actual payment date for the maturity\n :param nominal:\n :return: the caplet val as calculate by the Hull-White model with parameters (kappa, sigma) and given market data\n '''\n t_i_prev = count_days(d_prev, d_settlement, 'actual') / 360\n t_i = count_days(d_mat, d_settlement, 'actual') / 360\n # equilavent to delta in Veronesi (amount of time the caplet is active for). Denoted tau_i in course notes.\n delta = count_days(d_prev, d_mat, method='actual') / 360\n sig_p = sigma * np.sqrt((1 - np.exp(-2 * kappa * t_i_prev)) / (2 * kappa)) * \\\n np.abs((1 - np.exp(-kappa * t_i)) / kappa)\n h_i = (1 / sig_p) * (np.log(discount_factor * (1 + strike * delta) / discount_factor_prev)) + sig_p / 2\n caplet_val = nominal * (discount_factor_prev * norm.cdf(-h_i + sig_p) - (1 + strike * delta) * discount_factor * norm.cdf(-h_i))\n return caplet_val\n\ndef black_caplet(black_vol, discount_factor, strike, forward_libor, d_settlement, d_prev, d_expir, d_mat, nominal=1):\n '''\n :param black_vol: Black quoted (implied) vol for this caplet\n :param discount_factor: discount factor applicable\n :param strike:\n :param forward_libor:\n :param d_settlement: settlement date of the contract\n :param d_mat: maturity date of the caplet (denoted T_{i + 1} in Veronesi)\n :param d_prev: in the context of a cap, this is the previous date of payment. This serves to determine the length\n of the caplet (\"delta\" in Veronesi, page 686 - 688)\n :param d_expir: the expiry date (accrual expiry date)\n :param nominal:\n :return:\n '''\n # equivalent to delta in Veronesi (amount of time the caplet is active for). Denoted tau_i in course notes.\n delta = count_days(d_prev, d_mat, method='actual') / 360\n # this helps determine the volatility (where the expiry date used, d_expir, is the accrual date from the contract)\n t_prev_expiry = count_days(d_settlement, d_expir, method='actual') / 365\n vol_t = black_vol * np.sqrt(t_prev_expiry) # total volatility until the rate is fixed\n d_1 = (1 / vol_t) * np.log(forward_libor / strike) + 0.5 * vol_t\n d_2 = d_1 - vol_t\n caplet_price = nominal * (discount_factor * delta * (forward_libor * norm.cdf(d_1) - strike * norm.cdf(d_2)))\n # print(\"Delta: {}. T_Prev: {}. Vol_t: {}\".format(delta, t_prev_expiry, vol_t))\n return caplet_price\n\n#TODO\n# def forward_libor(d_fix, d_eff, d_mat):\n# '''\n# :param d_fix: fixing date (when the benchmark number is published)\n# :param d_eff: effective date of the underlying deposit (start date of the rate accrual). Typically some business\n# days after the fixing date based on the libor currency’s central bank business calendar in addition to the\n# London (EN) business day calendar\n# :param d_mat: maturity date of the underlying deposit, ie end date of the rate accrual. This is typically the effe\n# ctive date plus the libor tenor, or the next good business date.\n# :return:\n# '''" ]
[ [ "numpy.exp", "numpy.log", "scipy.stats.norm.cdf", "numpy.sqrt" ] ]
haohaoxiao/Deep-Reinforcement-Learning-Hands-On-Second-Edition
[ "1cbdff216fdc5cec02cc0da8664b788941f025c1" ]
[ "Chapter23/lib/mcts.py" ]
[ "\"\"\"\nMonte-Carlo Tree Search\n\"\"\"\nimport math as m\nimport numpy as np\n\nfrom lib import game, model\n\nimport torch.nn.functional as F\n\n\nclass MCTS:\n \"\"\"\n Class keeps statistics for every state encountered during the search\n \"\"\"\n def __init__(self, c_puct=1.0):\n self.c_puct = c_puct\n # count of visits, state_int -> [N(s, a)]\n self.visit_count = {}\n # total value of the state's act, state_int -> [W(s, a)]\n self.value = {}\n # average value of actions, state_int -> [Q(s, a)]\n self.value_avg = {}\n # prior probability of actions, state_int -> [P(s,a)]\n self.probs = {}\n\n def clear(self):\n self.visit_count.clear()\n self.value.clear()\n self.value_avg.clear()\n self.probs.clear()\n\n def __len__(self):\n return len(self.value)\n\n def find_leaf(self, state_int, player):\n \"\"\"\n Traverse the tree until the end of game or leaf node\n :param state_int: root node state\n :param player: player to move\n :return: tuple of (value, leaf_state, player, states, actions)\n 1. value: None if leaf node, otherwise equals to the game outcome for the player at leaf\n 2. leaf_state: state_int of the last state\n 3. player: player at the leaf node\n 4. states: list of states traversed\n 5. list of actions taken\n \"\"\"\n states = []\n actions = []\n cur_state = state_int\n cur_player = player\n value = None\n\n while not self.is_leaf(cur_state):\n states.append(cur_state)\n\n counts = self.visit_count[cur_state]\n total_sqrt = m.sqrt(sum(counts))\n probs = self.probs[cur_state]\n values_avg = self.value_avg[cur_state]\n\n # choose action to take, in the root node add the Dirichlet noise to the probs\n if cur_state == state_int:\n noises = np.random.dirichlet(\n [0.03] * game.GAME_COLS)\n probs = [\n 0.75 * prob + 0.25 * noise\n for prob, noise in zip(probs, noises)\n ]\n score = [\n value + self.c_puct*prob*total_sqrt/(1+count)\n for value, prob, count in\n zip(values_avg, probs, counts)\n ]\n invalid_actions = set(range(game.GAME_COLS)) - \\\n set(game.possible_moves(cur_state))\n for invalid in invalid_actions:\n score[invalid] = -np.inf\n action = int(np.argmax(score))\n actions.append(action)\n cur_state, won = game.move(\n cur_state, action, cur_player)\n if won:\n # if somebody won the game, the value of the final state is -1 (as it is on opponent's turn)\n value = -1.0\n cur_player = 1-cur_player\n # check for the draw\n moves_count = len(game.possible_moves(cur_state))\n if value is None and moves_count == 0:\n value = 0.0\n\n return value, cur_state, cur_player, states, actions\n\n def is_leaf(self, state_int):\n return state_int not in self.probs\n\n def search_batch(self, count, batch_size, state_int,\n player, net, device=\"cpu\"):\n for _ in range(count):\n self.search_minibatch(batch_size, state_int,\n player, net, device)\n\n def search_minibatch(self, count, state_int, player,\n net, device=\"cpu\"):\n \"\"\"\n Perform several MCTS searches.\n \"\"\"\n backup_queue = []\n expand_states = []\n expand_players = []\n expand_queue = []\n planned = set()\n for _ in range(count):\n value, leaf_state, leaf_player, states, actions = \\\n self.find_leaf(state_int, player)\n if value is not None:\n backup_queue.append((value, states, actions))\n else:\n if leaf_state not in planned:\n planned.add(leaf_state)\n leaf_state_lists = game.decode_binary(\n leaf_state)\n expand_states.append(leaf_state_lists)\n expand_players.append(leaf_player)\n expand_queue.append((leaf_state, states,\n actions))\n\n # do expansion of nodes\n if expand_queue:\n batch_v = model.state_lists_to_batch(\n expand_states, expand_players, device)\n logits_v, values_v = net(batch_v)\n probs_v = F.softmax(logits_v, dim=1)\n values = values_v.data.cpu().numpy()[:, 0]\n probs = probs_v.data.cpu().numpy()\n\n # create the nodes\n for (leaf_state, states, actions), value, prob in \\\n zip(expand_queue, values, probs):\n self.visit_count[leaf_state] = [0]*game.GAME_COLS\n self.value[leaf_state] = [0.0]*game.GAME_COLS\n self.value_avg[leaf_state] = [0.0]*game.GAME_COLS\n self.probs[leaf_state] = prob\n backup_queue.append((value, states, actions))\n\n # perform backup of the searches\n for value, states, actions in backup_queue:\n # leaf state is not stored in states and actions, so the value of the leaf will be the value of the opponent\n cur_value = -value\n for state_int, action in zip(states[::-1],\n actions[::-1]):\n self.visit_count[state_int][action] += 1\n self.value[state_int][action] += cur_value\n self.value_avg[state_int][action] = \\\n self.value[state_int][action] / \\\n self.visit_count[state_int][action]\n cur_value = -cur_value\n\n def get_policy_value(self, state_int, tau=1):\n \"\"\"\n Extract policy and action-values by the state\n :param state_int: state of the board\n :return: (probs, values)\n \"\"\"\n counts = self.visit_count[state_int]\n if tau == 0:\n probs = [0.0] * game.GAME_COLS\n probs[np.argmax(counts)] = 1.0\n else:\n counts = [count ** (1.0 / tau) for count in counts]\n total = sum(counts)\n probs = [count / total for count in counts]\n values = self.value_avg[state_int]\n return probs, values\n" ]
[ [ "torch.nn.functional.softmax", "numpy.argmax", "numpy.random.dirichlet" ] ]
cnwangfeng/algorithm-reference-library
[ "9605eb01652fbfcb9ff003cc12b44c84093b7fb1", "9605eb01652fbfcb9ff003cc12b44c84093b7fb1" ]
[ "processing_components/skymodel/operations.py", "processing_components/visibility/operations.py" ]
[ "\"\"\"Function to manage skymodels.\n\n\"\"\"\n\nimport logging\n\nimport matplotlib.pyplot as plt\nimport numpy\nfrom astropy.wcs.utils import skycoord_to_pixel\n\nfrom data_models.memory_data_models import SkyModel, GainTable\nfrom processing_library.image.operations import copy_image\nfrom ..calibration.operations import copy_gaintable\nfrom ..image.operations import smooth_image\nfrom ..skycomponent.base import copy_skycomponent\nfrom ..skycomponent.operations import filter_skycomponents_by_flux, insert_skycomponent, image_voronoi_iter\n\nlog = logging.getLogger(__name__)\n\n\ndef copy_skymodel(sm):\n \"\"\" Copy a sky model\n \n \"\"\"\n if sm.components is not None:\n newcomps = [copy_skycomponent(comp) for comp in sm.components]\n else:\n newcomps = None\n \n if sm.image is not None:\n newimage = copy_image(sm.image)\n else:\n newimage = None\n \n if sm.mask is not None:\n newmask = copy_image(sm.mask)\n else:\n newmask = None\n \n if sm.gaintable is not None:\n newgt = copy_gaintable(sm.gaintable)\n else:\n newgt = None\n \n return SkyModel(components=newcomps, image=newimage, gaintable=newgt, mask=newmask,\n fixed=sm.fixed)\n\n\ndef partition_skymodel_by_flux(sc, model, flux_threshold=-numpy.inf):\n \"\"\"Partition skymodel according to flux\n \n :param sc:\n :param model:\n :param flux_threshold:\n :return:\n \"\"\"\n brightsc = filter_skycomponents_by_flux(sc, flux_min=flux_threshold)\n weaksc = filter_skycomponents_by_flux(sc, flux_max=flux_threshold)\n log.info('Converted %d components into %d bright components and one image containing %d components'\n % (len(sc), len(brightsc), len(weaksc)))\n im = copy_image(model)\n im = insert_skycomponent(im, weaksc)\n return SkyModel(components=[copy_skycomponent(comp) for comp in brightsc],\n image=copy_image(im), mask=None,\n fixed=False)\n\n\ndef show_skymodel(sms, psf_width=1.75, cm='Greys', vmax=None, vmin=None):\n sp = 1\n \n for ism, sm in enumerate(sms):\n plt.clf()\n plt.subplot(121, projection=sms[ism].image.wcs.sub([1, 2]))\n sp += 1\n \n smodel = copy_image(sms[ism].image)\n smodel = insert_skycomponent(smodel, sms[ism].components)\n smodel = smooth_image(smodel, psf_width)\n \n if vmax is None:\n vmax = numpy.max(smodel.data[0, 0, ...])\n if vmin is None:\n vmin = numpy.min(smodel.data[0, 0, ...])\n \n plt.imshow(smodel.data[0, 0, ...], origin='lower', cmap=cm, vmax=vmax, vmin=vmin)\n plt.xlabel(sms[ism].image.wcs.wcs.ctype[0])\n plt.ylabel(sms[ism].image.wcs.wcs.ctype[1])\n \n plt.title('SkyModel%d' % ism)\n \n components = sms[ism].components\n if components is not None:\n for sc in components:\n x, y = skycoord_to_pixel(sc.direction, sms[ism].image.wcs, 0, 'wcs')\n plt.plot(x, y, marker='+', color='red')\n \n gaintable = sms[ism].gaintable\n if gaintable is not None:\n plt.subplot(122)\n sp += 1\n phase = numpy.angle(sm.gaintable.gain[:, :, 0, 0, 0])\n phase -= phase[:, 0][:, numpy.newaxis]\n plt.imshow(phase, origin='lower')\n plt.xlabel('Dish/Station')\n plt.ylabel('Integration')\n plt.show()\n\n\ndef initialize_skymodel_voronoi(model, comps, gt=None):\n \"\"\"Create a skymodel by Voronoi partitioning of the components, fill with components\n \n :param model: Model image\n :param comps: Skycomponents\n :param gt: Gaintable\n :return:\n \"\"\"\n skymodel_images = list()\n for i, mask in enumerate(image_voronoi_iter(model, comps)):\n im = copy_image(model)\n im.data *= mask.data\n if gt is not None:\n newgt = copy_gaintable(gt)\n newgt.phasecentre = comps[i].direction\n else:\n newgt=None\n \n skymodel_images.append(SkyModel(image=im, components=None, gaintable=newgt, mask=mask))\n \n return skymodel_images\n\n\ndef calculate_skymodel_equivalent_image(sm):\n \"\"\"Calculate an equivalent image for a skymodel\n \n :param sm:\n :return:\n \"\"\"\n combined_model = copy_image(sm[0].image)\n combined_model.data[...] = 0.0\n for th in sm:\n if th.image is not None:\n if th.mask is not None:\n combined_model.data += th.mask.data * th.image.data\n else:\n combined_model.data += th.image.data\n \n return combined_model\n\n\ndef update_skymodel_from_image(sm, im, damping=0.5):\n \"\"\"Update a skymodel for an image\n\n :param sm:\n :param im:\n :return:\n \"\"\"\n for i, th in enumerate(sm):\n newim = copy_image(im)\n if th.mask is not None:\n newim.data *= th.mask.data\n th.image.data += damping * newim.data\n \n return sm\n\n\ndef update_skymodel_from_gaintables(sm, gt_list, calibration_context='T', damping=0.5):\n \"\"\"Update a skymodel from a list of gaintables\n\n :param sm:\n :param im:\n :return:\n \"\"\"\n assert len(sm) == len(gt_list)\n \n for i, th in enumerate(sm):\n assert isinstance(th.gaintable, GainTable), th.gaintable\n delta = numpy.exp(damping*1j*gt_list[i][calibration_context].gain)\n th.gaintable.data['gain'] *= numpy.exp(damping*1j*numpy.angle(gt_list[i][calibration_context].gain))\n \n return sm\n\n\ndef expand_skymodel_by_skycomponents(sm, **kwargs):\n \"\"\" Expand a sky model so that all components and the image are in separate skymodels\n \n The mask and gaintable are taken to apply for all new skymodels.\n \n :param sm: SkyModel\n :return: List of SkyModels\n \"\"\"\n result = [SkyModel(components=[comp],\n image=None,\n gaintable=copy_gaintable(sm.gaintable),\n mask=copy_image(sm.mask),\n fixed=sm.fixed) for comp in sm.components]\n if sm.image is not None:\n result.append(SkyModel(components=None,\n image=copy_image(sm.image),\n gaintable=copy_gaintable(sm.gaintable),\n mask=copy_image(sm.mask),\n fixed=sm.fixed))\n return result\n", "\"\"\" Visibility operations\n\n\"\"\"\n\nimport logging\nfrom typing import Union\n\nimport warnings\nimport numpy\nfrom astropy.coordinates import SkyCoord\n\nfrom data_models.memory_data_models import BlockVisibility, Visibility, QA\n\nfrom processing_library.imaging.imaging_params import get_frequency_map\nfrom processing_library.util.coordinate_support import skycoord_to_lmn, simulate_point\n\nfrom ..visibility.base import copy_visibility\n\nfrom data_models.polarisation import convert_linear_to_stokes, convert_circular_to_stokesI, convert_linear_to_stokesI, \\\n convert_circular_to_stokes, PolarisationFrame\n\nlog = logging.getLogger(__name__)\n\n\ndef append_visibility(vis: Union[Visibility, BlockVisibility], othervis: Union[Visibility, BlockVisibility]) \\\n -> Union[Visibility, BlockVisibility]:\n \"\"\"Append othervis to vis\n \n :param vis:\n :param othervis:\n :return: Visibility vis + othervis\n \"\"\"\n \n if vis is None:\n return othervis\n \n assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis\n assert vis.polarisation_frame == othervis.polarisation_frame\n assert abs(vis.phasecentre.ra.value - othervis.phasecentre.ra.value) < 1e-15\n assert abs(vis.phasecentre.dec.value - othervis.phasecentre.dec.value) < 1e-15\n assert vis.phasecentre.separation(othervis.phasecentre).value < 1e-15\n vis.data = numpy.hstack((vis.data, othervis.data))\n return vis\n\n\ndef sort_visibility(vis, order=None):\n \"\"\" Sort a visibility on a given column\n \n :param vis:\n :param order: Array of string of column to be used for sortin\n :return:\n \"\"\"\n if order is None:\n order = ['index']\n vis.data = numpy.sort(vis.data, order=order)\n return vis\n\n\ndef concatenate_visibility(vis_list, sort=True):\n \"\"\"Concatenate a list of visibilities, with an optional sort back to index order\n\n :param vis_list:\n :return: Visibility\n \"\"\"\n if isinstance(vis_list, Visibility) or isinstance(vis_list, BlockVisibility):\n return vis_list\n \n assert len(vis_list) > 0\n \n vis = None\n for v in vis_list:\n if vis is None:\n vis = v\n else:\n assert v.polarisation_frame == vis.polarisation_frame\n assert v.phasecentre.separation(vis.phasecentre).value < 1e-15\n vis.data = numpy.hstack((vis.data, v.data))\n \n assert vis is not None\n \n if sort:\n vis = sort_visibility(vis, ['index'])\n \n return vis\n\n\ndef sum_visibility(vis: Visibility, direction: SkyCoord) -> numpy.array:\n \"\"\" Direct Fourier summation in a given direction\n\n :param vis: Visibility to be summed\n :param direction: Direction of summation\n :return: flux[nch,npol], weight[nch,pol]\n \"\"\"\n # TODO: Convert to Visibility or remove?\n \n assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis\n \n svis = copy_visibility(vis)\n \n l, m, n = skycoord_to_lmn(direction, svis.phasecentre)\n phasor = numpy.conjugate(simulate_point(svis.uvw, l, m))\n \n # Need to put correct mapping here\n _, frequency = get_frequency_map(svis, None)\n \n frequency = list(frequency)\n \n nchan = max(frequency) + 1\n npol = svis.polarisation_frame.npol\n \n flux = numpy.zeros([nchan, npol])\n weight = numpy.zeros([nchan, npol])\n \n coords = svis.vis, svis.weight, phasor, list(frequency)\n for v, wt, p, ic in zip(*coords):\n for pol in range(npol):\n flux[ic, pol] += numpy.real(wt[pol] * v[pol] * p)\n weight[ic, pol] += wt[pol]\n \n flux[weight > 0.0] = flux[weight > 0.0] / weight[weight > 0.0]\n flux[weight <= 0.0] = 0.0\n return flux, weight\n\n\ndef subtract_visibility(vis, model_vis, inplace=False):\n \"\"\" Subtract model_vis from vis, returning new visibility\n \n :param vis:\n :param model_vis:\n :return:\n \"\"\"\n if isinstance(vis, Visibility):\n assert isinstance(model_vis, Visibility), model_vis\n elif isinstance(vis, BlockVisibility):\n assert isinstance(model_vis, BlockVisibility), model_vis\n else:\n raise RuntimeError(\"Types of vis and model visibility are invalid\")\n \n assert vis.vis.shape == model_vis.vis.shape, \"Observed %s and model visibilities %s have different shapes\"\\\n % (vis.vis.shape, model_vis.vis.shape)\n \n if inplace:\n vis.data['vis'] = vis.data['vis'] - model_vis.data['vis']\n return vis\n else:\n residual_vis = copy_visibility(vis)\n residual_vis.data['vis'] = residual_vis.data['vis'] - model_vis.data['vis']\n return residual_vis\n\n\ndef qa_visibility(vis: Union[Visibility, BlockVisibility], context=None) -> QA:\n \"\"\"Assess the quality of Visibility\n\n :param context:\n :param vis: Visibility to be assessed\n :return: QA\n \"\"\"\n assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis\n \n avis = numpy.abs(vis.vis)\n data = {'maxabs': numpy.max(avis),\n 'minabs': numpy.min(avis),\n 'rms': numpy.std(avis),\n 'medianabs': numpy.median(avis)}\n qa = QA(origin='qa_visibility',\n data=data,\n context=context)\n return qa\n\n\ndef remove_continuum_blockvisibility(vis: BlockVisibility, degree=1, mask=None) -> BlockVisibility:\n \"\"\" Fit and remove continuum visibility\n\n Fit a polynomial in frequency of the specified degree where mask is True\n \n :param vis:\n :param degree: Degree of polynomial\n :param mask:\n :return:\n \"\"\"\n assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis\n \n if mask is not None:\n assert numpy.sum(mask) > 2 * degree, \"Insufficient channels for fit\"\n \n nchan = len(vis.frequency)\n x = (vis.frequency - vis.frequency[nchan // 2]) / (vis.frequency[0] - vis.frequency[nchan // 2])\n for row in range(vis.nvis):\n for ant2 in range(vis.nants):\n for ant1 in range(vis.nants):\n for pol in range(vis.polarisation_frame.npol):\n wt = numpy.sqrt(vis.data['weight'][row, ant2, ant1, :, pol])\n if mask is not None:\n wt[mask] = 0.0\n fit = numpy.polyfit(x, vis.data['vis'][row, ant2, ant1, :, pol], w=wt, deg=degree)\n prediction = numpy.polyval(fit, x)\n vis.data['vis'][row, ant2, ant1, :, pol] -= prediction\n return vis\n\n\ndef divide_visibility(vis: BlockVisibility, modelvis: BlockVisibility):\n \"\"\" Divide visibility by model forming visibility for equivalent point source\n\n This is a useful intermediate product for calibration. Variation of the visibility in time and\n frequency due to the model structure is removed and the data can be averaged to a limit determined\n by the instrumental stability. The weight is adjusted to compensate for the division.\n \n Zero divisions are avoided and the corresponding weight set to zero.\n\n :param vis:\n :param modelvis:\n :return:\n \"\"\"\n assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis\n \n # Different for scalar and vector/matrix cases\n isscalar = vis.polarisation_frame.npol == 1\n \n if isscalar:\n # Scalar case is straightforward\n x = numpy.zeros_like(vis.vis)\n xwt = numpy.abs(modelvis.vis) ** 2 * vis.weight\n mask = xwt > 0.0\n x[mask] = vis.vis[mask] / modelvis.vis[mask]\n else:\n nrows, nants, _, nchan, npol = vis.vis.shape\n nrec = 2\n assert nrec * nrec == npol\n xshape = (nrows, nants, nants, nchan, nrec, nrec)\n x = numpy.zeros(xshape, dtype='complex')\n xwt = numpy.zeros(xshape)\n # TODO: Remove filter when fixed to use ndarray\n warnings.simplefilter(\"ignore\", category=PendingDeprecationWarning)\n\n for row in range(nrows):\n for ant1 in range(nants):\n for ant2 in range(ant1 + 1, nants):\n for chan in range(nchan):\n ovis = numpy.matrix(vis.vis[row, ant2, ant1, chan].reshape([2, 2]))\n mvis = numpy.matrix(modelvis.vis[row, ant2, ant1, chan].reshape([2, 2]))\n wt = numpy.matrix(vis.weight[row, ant2, ant1, chan].reshape([2, 2]))\n x[row, ant2, ant1, chan] = numpy.matmul(numpy.linalg.inv(mvis), ovis)\n xwt[row, ant2, ant1, chan] = numpy.dot(mvis, numpy.multiply(wt, mvis.H)).real\n x = x.reshape((nrows, nants, nants, nchan, nrec * nrec))\n xwt = xwt.reshape((nrows, nants, nants, nchan, nrec * nrec))\n \n pointsource_vis = BlockVisibility(data=None, frequency=vis.frequency, channel_bandwidth=vis.channel_bandwidth,\n phasecentre=vis.phasecentre, configuration=vis.configuration,\n uvw=vis.uvw, time=vis.time, integration_time=vis.integration_time, vis=x,\n weight=xwt)\n return pointsource_vis\n\n\ndef integrate_visibility_by_channel(vis: BlockVisibility) -> BlockVisibility:\n \"\"\" Integrate visibility across channels, returning new visibility\n \n :param vis:\n :return: BlockVisibility\n \"\"\"\n \n assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility), vis\n \n vis_shape = list(vis.vis.shape)\n ntimes, nants, _, nchan, npol = vis_shape\n vis_shape[-2] = 1\n newvis = BlockVisibility(data=None,\n frequency=numpy.ones([1]) * numpy.average(vis.frequency),\n channel_bandwidth=numpy.ones([1]) * numpy.sum(vis.channel_bandwidth),\n phasecentre=vis.phasecentre,\n configuration=vis.configuration,\n uvw=vis.uvw,\n time=vis.time,\n vis=numpy.zeros(vis_shape, dtype='complex'),\n weight=numpy.ones(vis_shape, dtype='float'),\n integration_time=vis.integration_time,\n polarisation_frame=vis.polarisation_frame)\n \n newvis.data['vis'][..., 0, :] = numpy.sum(vis.data['vis'] * vis.data['weight'], axis=-2)\n newvis.data['weight'][..., 0, :] = numpy.sum(vis.data['weight'], axis=-2)\n mask = newvis.data['weight'] > 0.0\n newvis.data['vis'][mask] = newvis.data['vis'][mask] / newvis.data['weight'][mask]\n \n return newvis\n\ndef convert_visibility_to_stokes(vis):\n \"\"\"Convert the polarisation frame data into Stokes parameters.\n\n Args:\n vis (obj): ARL visibility data.\n\n Returns:\n vis: Converted visibility data.\n \"\"\"\n poldef = vis.polarisation_frame\n if poldef == PolarisationFrame('linear'):\n vis.data['vis'] = convert_linear_to_stokes(vis.data['vis'], polaxis=1)\n vis.polarisation_frame = PolarisationFrame('stokesIQUV')\n elif poldef == PolarisationFrame('circular'):\n vis.data['vis'] = convert_circular_to_stokes(vis.data['vis'], polaxis=1)\n vis.polarisation_frame = PolarisationFrame('stokesIQUV')\n return vis\n\ndef convert_visibility_to_stokesI(vis):\n \"\"\"Convert the polarisation frame data into Stokes I dropping other polarisations, return new Visibility\n\n Args:\n vis (obj): ARL visibility data.\n\n Returns:\n vis: New, converted visibility data.\n \"\"\"\n polarisation_frame = PolarisationFrame('stokesI')\n poldef = vis.polarisation_frame\n if poldef == PolarisationFrame('linear'):\n vis_data = convert_linear_to_stokesI(vis.data['vis'])\n vis_weight = (vis.weight[...,0] + vis.weight[...,3])[..., numpy.newaxis]\n vis_imaging_weight = (vis.imaging_weight[...,0] + vis.imaging_weight[...,3])[..., numpy.newaxis]\n elif poldef == PolarisationFrame('circular'):\n vis_data = convert_circular_to_stokesI(vis.data['vis'])\n vis_weight = (vis.weight[...,0] + vis.weight[...,3])[..., numpy.newaxis]\n vis_imaging_weight = (vis.imaging_weight[...,0] + vis.imaging_weight[...,3])[..., numpy.newaxis]\n else:\n raise NameError(\"Polarisation frame %s unknown\" % poldef)\n\n return Visibility(frequency=vis.frequency, channel_bandwidth=vis.channel_bandwidth,\n phasecentre=vis.phasecentre, configuration=vis.configuration, uvw=vis.uvw,\n time=vis.time, antenna1=vis.antenna1, antenna2=vis.antenna2, vis=vis_data,\n weight=vis_weight, imaging_weight=vis_imaging_weight, integration_time=vis.integration_time,\n polarisation_frame=polarisation_frame, cindex=vis.cindex,\n blockvis=vis.blockvis)\n" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.plot", "numpy.max", "matplotlib.pyplot.clf", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xlabel", "numpy.angle", "numpy.exp", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "numpy.hstack", "numpy.polyfit", "numpy.abs", "numpy.sqrt", "numpy.min", "numpy.linalg.inv", "numpy.multiply", "numpy.median", "numpy.sort", "numpy.ones", "numpy.max", "numpy.std", "numpy.real", "numpy.zeros_like", "numpy.polyval", "numpy.average", "numpy.zeros", "numpy.sum" ] ]
ADraginda/pandas
[ "f58d8151299ae6804a5e1bc7786c84ec4c0aa333" ]
[ "pandas/core/arrays/datetimelike.py" ]
[ "from __future__ import annotations\n\nfrom datetime import datetime, timedelta\nimport operator\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Optional,\n Sequence,\n Tuple,\n Type,\n TypeVar,\n Union,\n cast,\n)\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import algos, lib\nfrom pandas._libs.tslibs import (\n BaseOffset,\n NaT,\n NaTType,\n Period,\n Resolution,\n Tick,\n Timestamp,\n delta_to_nanoseconds,\n iNaT,\n to_offset,\n)\nfrom pandas._libs.tslibs.timestamps import (\n RoundTo,\n integer_op_not_supported,\n round_nsint64,\n)\nfrom pandas._typing import DatetimeLikeScalar, DtypeObj\nfrom pandas.compat.numpy import function as nv\nfrom pandas.errors import AbstractMethodError, NullFrequencyError, PerformanceWarning\nfrom pandas.util._decorators import Appender, Substitution, cache_readonly\n\nfrom pandas.core.dtypes.common import (\n is_categorical_dtype,\n is_datetime64_any_dtype,\n is_datetime64_dtype,\n is_datetime64tz_dtype,\n is_datetime_or_timedelta_dtype,\n is_dtype_equal,\n is_extension_array_dtype,\n is_float_dtype,\n is_integer_dtype,\n is_list_like,\n is_object_dtype,\n is_period_dtype,\n is_string_dtype,\n is_timedelta64_dtype,\n is_unsigned_integer_dtype,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna\n\nfrom pandas.core import nanops, ops\nfrom pandas.core.algorithms import checked_add_with_arr, isin, unique1d, value_counts\nfrom pandas.core.arraylike import OpsMixin\nfrom pandas.core.arrays._mixins import NDArrayBackedExtensionArray, ravel_compat\nimport pandas.core.common as com\nfrom pandas.core.construction import array, extract_array\nfrom pandas.core.indexers import check_array_indexer, check_setitem_lengths\nfrom pandas.core.ops.common import unpack_zerodim_and_defer\nfrom pandas.core.ops.invalid import invalid_comparison, make_invalid_op\n\nfrom pandas.tseries import frequencies\n\nif TYPE_CHECKING:\n from pandas.core.arrays import DatetimeArray, TimedeltaArray\n\nDTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]\nDatetimeLikeArrayT = TypeVar(\"DatetimeLikeArrayT\", bound=\"DatetimeLikeArrayMixin\")\n\n\nclass InvalidComparison(Exception):\n \"\"\"\n Raised by _validate_comparison_value to indicate to caller it should\n return invalid_comparison.\n \"\"\"\n\n pass\n\n\nclass DatetimeLikeArrayMixin(OpsMixin, NDArrayBackedExtensionArray):\n \"\"\"\n Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray\n\n Assumes that __new__/__init__ defines:\n _data\n _freq\n\n and that the inheriting class has methods:\n _generate_range\n \"\"\"\n\n # _infer_matches -> which infer_dtype strings are close enough to our own\n _infer_matches: Tuple[str, ...]\n _is_recognized_dtype: Callable[[DtypeObj], bool]\n _recognized_scalars: Tuple[Type, ...]\n _data: np.ndarray\n\n def __init__(self, data, dtype=None, freq=None, copy=False):\n raise AbstractMethodError(self)\n\n @classmethod\n def _simple_new(\n cls: Type[DatetimeLikeArrayT],\n values: np.ndarray,\n freq: Optional[BaseOffset] = None,\n dtype=None,\n ) -> DatetimeLikeArrayT:\n raise AbstractMethodError(cls)\n\n @property\n def _scalar_type(self) -> Type[DatetimeLikeScalar]:\n \"\"\"\n The scalar associated with this datelike\n\n * PeriodArray : Period\n * DatetimeArray : Timestamp\n * TimedeltaArray : Timedelta\n \"\"\"\n raise AbstractMethodError(self)\n\n def _scalar_from_string(self, value: str) -> DTScalarOrNaT:\n \"\"\"\n Construct a scalar type from a string.\n\n Parameters\n ----------\n value : str\n\n Returns\n -------\n Period, Timestamp, or Timedelta, or NaT\n Whatever the type of ``self._scalar_type`` is.\n\n Notes\n -----\n This should call ``self._check_compatible_with`` before\n unboxing the result.\n \"\"\"\n raise AbstractMethodError(self)\n\n def _unbox_scalar(\n self, value: DTScalarOrNaT, setitem: bool = False\n ) -> Union[np.int64, np.datetime64, np.timedelta64]:\n \"\"\"\n Unbox the integer value of a scalar `value`.\n\n Parameters\n ----------\n value : Period, Timestamp, Timedelta, or NaT\n Depending on subclass.\n setitem : bool, default False\n Whether to check compatibility with setitem strictness.\n\n Returns\n -------\n int\n\n Examples\n --------\n >>> self._unbox_scalar(Timedelta(\"10s\")) # doctest: +SKIP\n 10000000000\n \"\"\"\n raise AbstractMethodError(self)\n\n def _check_compatible_with(\n self, other: DTScalarOrNaT, setitem: bool = False\n ) -> None:\n \"\"\"\n Verify that `self` and `other` are compatible.\n\n * DatetimeArray verifies that the timezones (if any) match\n * PeriodArray verifies that the freq matches\n * Timedelta has no verification\n\n In each case, NaT is considered compatible.\n\n Parameters\n ----------\n other\n setitem : bool, default False\n For __setitem__ we may have stricter compatibility restrictions than\n for comparisons.\n\n Raises\n ------\n Exception\n \"\"\"\n raise AbstractMethodError(self)\n\n # ------------------------------------------------------------------\n # NDArrayBackedExtensionArray compat\n\n @cache_readonly\n def _ndarray(self) -> np.ndarray:\n return self._data\n\n def _from_backing_data(\n self: DatetimeLikeArrayT, arr: np.ndarray\n ) -> DatetimeLikeArrayT:\n # Note: we do not retain `freq`\n return type(self)._simple_new(arr, dtype=self.dtype)\n\n # ------------------------------------------------------------------\n\n def _box_func(self, x):\n \"\"\"\n box function to get object from internal representation\n \"\"\"\n raise AbstractMethodError(self)\n\n def _box_values(self, values) -> np.ndarray:\n \"\"\"\n apply box func to passed values\n \"\"\"\n return lib.map_infer(values, self._box_func)\n\n def __iter__(self):\n if self.ndim > 1:\n return (self[n] for n in range(len(self)))\n else:\n return (self._box_func(v) for v in self.asi8)\n\n @property\n def asi8(self) -> np.ndarray:\n \"\"\"\n Integer representation of the values.\n\n Returns\n -------\n ndarray\n An ndarray with int64 dtype.\n \"\"\"\n # do not cache or you'll create a memory leak\n return self._data.view(\"i8\")\n\n # ----------------------------------------------------------------\n # Rendering Methods\n\n def _format_native_types(self, na_rep=\"NaT\", date_format=None):\n \"\"\"\n Helper method for astype when converting to strings.\n\n Returns\n -------\n ndarray[str]\n \"\"\"\n raise AbstractMethodError(self)\n\n def _formatter(self, boxed=False):\n # TODO: Remove Datetime & DatetimeTZ formatters.\n return \"'{}'\".format\n\n # ----------------------------------------------------------------\n # Array-Like / EA-Interface Methods\n\n def __array__(self, dtype=None) -> np.ndarray:\n # used for Timedelta/DatetimeArray, overwritten by PeriodArray\n if is_object_dtype(dtype):\n return np.array(list(self), dtype=object)\n return self._ndarray\n\n def __getitem__(\n self, key: Union[int, slice, np.ndarray]\n ) -> Union[DatetimeLikeArrayMixin, DTScalarOrNaT]:\n \"\"\"\n This getitem defers to the underlying array, which by-definition can\n only handle list-likes, slices, and integer scalars\n \"\"\"\n result = super().__getitem__(key)\n if lib.is_scalar(result):\n return result\n\n result._freq = self._get_getitem_freq(key)\n return result\n\n def _get_getitem_freq(self, key):\n \"\"\"\n Find the `freq` attribute to assign to the result of a __getitem__ lookup.\n \"\"\"\n is_period = is_period_dtype(self.dtype)\n if is_period:\n freq = self.freq\n elif self.ndim != 1:\n freq = None\n else:\n key = check_array_indexer(self, key) # maybe ndarray[bool] -> slice\n freq = None\n if isinstance(key, slice):\n if self.freq is not None and key.step is not None:\n freq = key.step * self.freq\n else:\n freq = self.freq\n elif key is Ellipsis:\n # GH#21282 indexing with Ellipsis is similar to a full slice,\n # should preserve `freq` attribute\n freq = self.freq\n elif com.is_bool_indexer(key):\n new_key = lib.maybe_booleans_to_slice(key.view(np.uint8))\n if isinstance(new_key, slice):\n return self._get_getitem_freq(new_key)\n return freq\n\n def __setitem__(\n self,\n key: Union[int, Sequence[int], Sequence[bool], slice],\n value: Union[NaTType, Any, Sequence[Any]],\n ) -> None:\n # I'm fudging the types a bit here. \"Any\" above really depends\n # on type(self). For PeriodArray, it's Period (or stuff coercible\n # to a period in from_sequence). For DatetimeArray, it's Timestamp...\n # I don't know if mypy can do that, possibly with Generics.\n # https://mypy.readthedocs.io/en/latest/generics.html\n no_op = check_setitem_lengths(key, value, self)\n if no_op:\n return\n\n super().__setitem__(key, value)\n self._maybe_clear_freq()\n\n def _maybe_clear_freq(self):\n # inplace operations like __setitem__ may invalidate the freq of\n # DatetimeArray and TimedeltaArray\n pass\n\n def astype(self, dtype, copy=True):\n # Some notes on cases we don't have to handle here in the base class:\n # 1. PeriodArray.astype handles period -> period\n # 2. DatetimeArray.astype handles conversion between tz.\n # 3. DatetimeArray.astype handles datetime -> period\n dtype = pandas_dtype(dtype)\n\n if is_object_dtype(dtype):\n return self._box_values(self.asi8.ravel()).reshape(self.shape)\n elif is_string_dtype(dtype) and not is_categorical_dtype(dtype):\n if is_extension_array_dtype(dtype):\n arr_cls = dtype.construct_array_type()\n return arr_cls._from_sequence(self, dtype=dtype, copy=copy)\n else:\n return self._format_native_types()\n elif is_integer_dtype(dtype):\n # we deliberately ignore int32 vs. int64 here.\n # See https://github.com/pandas-dev/pandas/issues/24381 for more.\n warnings.warn(\n f\"casting {self.dtype} values to int64 with .astype(...) is \"\n \"deprecated and will raise in a future version. \"\n \"Use .view(...) instead.\",\n FutureWarning,\n stacklevel=3,\n )\n\n values = self.asi8\n\n if is_unsigned_integer_dtype(dtype):\n # Again, we ignore int32 vs. int64\n values = values.view(\"uint64\")\n\n if copy:\n values = values.copy()\n return values\n elif (\n is_datetime_or_timedelta_dtype(dtype)\n and not is_dtype_equal(self.dtype, dtype)\n ) or is_float_dtype(dtype):\n # disallow conversion between datetime/timedelta,\n # and conversions for any datetimelike to float\n msg = f\"Cannot cast {type(self).__name__} to dtype {dtype}\"\n raise TypeError(msg)\n elif is_categorical_dtype(dtype):\n arr_cls = dtype.construct_array_type()\n return arr_cls(self, dtype=dtype)\n else:\n return np.asarray(self, dtype=dtype)\n\n def view(self, dtype=None):\n if dtype is None or dtype is self.dtype:\n return type(self)(self._ndarray, dtype=self.dtype)\n return self._ndarray.view(dtype=dtype)\n\n # ------------------------------------------------------------------\n # ExtensionArray Interface\n\n @classmethod\n def _concat_same_type(\n cls: Type[DatetimeLikeArrayT],\n to_concat: Sequence[DatetimeLikeArrayT],\n axis: int = 0,\n ) -> DatetimeLikeArrayT:\n new_obj = super()._concat_same_type(to_concat, axis)\n\n obj = to_concat[0]\n dtype = obj.dtype\n\n new_freq = None\n if is_period_dtype(dtype):\n new_freq = obj.freq\n elif axis == 0:\n # GH 3232: If the concat result is evenly spaced, we can retain the\n # original frequency\n to_concat = [x for x in to_concat if len(x)]\n\n if obj.freq is not None and all(x.freq == obj.freq for x in to_concat):\n pairs = zip(to_concat[:-1], to_concat[1:])\n if all(pair[0][-1] + obj.freq == pair[1][0] for pair in pairs):\n new_freq = obj.freq\n\n new_obj._freq = new_freq\n return new_obj\n\n def copy(self: DatetimeLikeArrayT) -> DatetimeLikeArrayT:\n new_obj = super().copy()\n new_obj._freq = self.freq\n return new_obj\n\n def _values_for_factorize(self):\n return self._ndarray, iNaT\n\n @classmethod\n def _from_factorized(\n cls: Type[DatetimeLikeArrayT], values, original\n ) -> DatetimeLikeArrayT:\n return cls(values, dtype=original.dtype)\n\n # ------------------------------------------------------------------\n # Validation Methods\n # TODO: try to de-duplicate these, ensure identical behavior\n\n def _validate_comparison_value(self, other):\n if isinstance(other, str):\n try:\n # GH#18435 strings get a pass from tzawareness compat\n other = self._scalar_from_string(other)\n except ValueError:\n # failed to parse as Timestamp/Timedelta/Period\n raise InvalidComparison(other)\n\n if isinstance(other, self._recognized_scalars) or other is NaT:\n # pandas\\core\\arrays\\datetimelike.py:432: error: Too many arguments\n # for \"object\" [call-arg]\n other = self._scalar_type(other) # type: ignore[call-arg]\n try:\n self._check_compatible_with(other)\n except TypeError as err:\n # e.g. tzawareness mismatch\n raise InvalidComparison(other) from err\n\n elif not is_list_like(other):\n raise InvalidComparison(other)\n\n elif len(other) != len(self):\n raise ValueError(\"Lengths must match\")\n\n else:\n try:\n other = self._validate_listlike(other, allow_object=True)\n self._check_compatible_with(other)\n except TypeError as err:\n if is_object_dtype(getattr(other, \"dtype\", None)):\n # We will have to operate element-wise\n pass\n else:\n raise InvalidComparison(other) from err\n\n return other\n\n def _validate_fill_value(self, fill_value):\n \"\"\"\n If a fill_value is passed to `take` convert it to an i8 representation,\n raising TypeError if this is not possible.\n\n Parameters\n ----------\n fill_value : object\n\n Returns\n -------\n fill_value : np.int64, np.datetime64, or np.timedelta64\n\n Raises\n ------\n TypeError\n \"\"\"\n return self._validate_scalar(fill_value)\n\n def _validate_shift_value(self, fill_value):\n # TODO(2.0): once this deprecation is enforced, use _validate_fill_value\n if is_valid_nat_for_dtype(fill_value, self.dtype):\n fill_value = NaT\n elif isinstance(fill_value, self._recognized_scalars):\n # pandas\\core\\arrays\\datetimelike.py:746: error: Too many arguments\n # for \"object\" [call-arg]\n fill_value = self._scalar_type(fill_value) # type: ignore[call-arg]\n else:\n # only warn if we're not going to raise\n if self._scalar_type is Period and lib.is_integer(fill_value):\n # kludge for #31971 since Period(integer) tries to cast to str\n new_fill = Period._from_ordinal(fill_value, freq=self.freq)\n else:\n # pandas\\core\\arrays\\datetimelike.py:753: error: Too many\n # arguments for \"object\" [call-arg]\n new_fill = self._scalar_type(fill_value) # type: ignore[call-arg]\n\n # stacklevel here is chosen to be correct when called from\n # DataFrame.shift or Series.shift\n warnings.warn(\n f\"Passing {type(fill_value)} to shift is deprecated and \"\n \"will raise in a future version, pass \"\n f\"{self._scalar_type.__name__} instead.\",\n FutureWarning,\n stacklevel=8,\n )\n fill_value = new_fill\n\n return self._unbox(fill_value, setitem=True)\n\n def _validate_scalar(\n self,\n value,\n *,\n allow_listlike: bool = False,\n setitem: bool = True,\n unbox: bool = True,\n ):\n \"\"\"\n Validate that the input value can be cast to our scalar_type.\n\n Parameters\n ----------\n value : object\n allow_listlike: bool, default False\n When raising an exception, whether the message should say\n listlike inputs are allowed.\n setitem : bool, default True\n Whether to check compatibility with setitem strictness.\n unbox : bool, default True\n Whether to unbox the result before returning. Note: unbox=False\n skips the setitem compatibility check.\n\n Returns\n -------\n self._scalar_type or NaT\n \"\"\"\n if isinstance(value, str):\n # NB: Careful about tzawareness\n try:\n value = self._scalar_from_string(value)\n except ValueError as err:\n msg = self._validation_error_message(value, allow_listlike)\n raise TypeError(msg) from err\n\n elif is_valid_nat_for_dtype(value, self.dtype):\n # GH#18295\n value = NaT\n\n elif isinstance(value, self._recognized_scalars):\n # error: Too many arguments for \"object\" [call-arg]\n value = self._scalar_type(value) # type: ignore[call-arg]\n\n else:\n msg = self._validation_error_message(value, allow_listlike)\n raise TypeError(msg)\n\n if not unbox:\n # NB: In general NDArrayBackedExtensionArray will unbox here;\n # this option exists to prevent a performance hit in\n # TimedeltaIndex.get_loc\n return value\n return self._unbox_scalar(value, setitem=setitem)\n\n def _validation_error_message(self, value, allow_listlike: bool = False) -> str:\n \"\"\"\n Construct an exception message on validation error.\n\n Some methods allow only scalar inputs, while others allow either scalar\n or listlike.\n\n Parameters\n ----------\n allow_listlike: bool, default False\n\n Returns\n -------\n str\n \"\"\"\n if allow_listlike:\n msg = (\n f\"value should be a '{self._scalar_type.__name__}', 'NaT', \"\n f\"or array of those. Got '{type(value).__name__}' instead.\"\n )\n else:\n msg = (\n f\"value should be a '{self._scalar_type.__name__}' or 'NaT'. \"\n f\"Got '{type(value).__name__}' instead.\"\n )\n return msg\n\n def _validate_listlike(self, value, allow_object: bool = False):\n if isinstance(value, type(self)):\n return value\n\n if isinstance(value, list) and len(value) == 0:\n # We treat empty list as our own dtype.\n return type(self)._from_sequence([], dtype=self.dtype)\n\n # Do type inference if necessary up front\n # e.g. we passed PeriodIndex.values and got an ndarray of Periods\n value = array(value)\n value = extract_array(value, extract_numpy=True)\n\n if is_dtype_equal(value.dtype, \"string\"):\n # We got a StringArray\n try:\n # TODO: Could use from_sequence_of_strings if implemented\n # Note: passing dtype is necessary for PeriodArray tests\n value = type(self)._from_sequence(value, dtype=self.dtype)\n except ValueError:\n pass\n\n if is_categorical_dtype(value.dtype):\n # e.g. we have a Categorical holding self.dtype\n if is_dtype_equal(value.categories.dtype, self.dtype):\n # TODO: do we need equal dtype or just comparable?\n value = value._internal_get_values()\n value = extract_array(value, extract_numpy=True)\n\n if allow_object and is_object_dtype(value.dtype):\n pass\n\n elif not type(self)._is_recognized_dtype(value.dtype):\n msg = self._validation_error_message(value, True)\n raise TypeError(msg)\n\n return value\n\n def _validate_searchsorted_value(self, value):\n if not is_list_like(value):\n return self._validate_scalar(value, allow_listlike=True, setitem=False)\n else:\n value = self._validate_listlike(value)\n\n return self._unbox(value)\n\n def _validate_setitem_value(self, value):\n if is_list_like(value):\n value = self._validate_listlike(value)\n else:\n return self._validate_scalar(value, allow_listlike=True)\n\n return self._unbox(value, setitem=True)\n\n def _unbox(\n self, other, setitem: bool = False\n ) -> Union[np.int64, np.datetime64, np.timedelta64, np.ndarray]:\n \"\"\"\n Unbox either a scalar with _unbox_scalar or an instance of our own type.\n \"\"\"\n if lib.is_scalar(other):\n other = self._unbox_scalar(other, setitem=setitem)\n else:\n # same type as self\n self._check_compatible_with(other, setitem=setitem)\n other = other._ndarray\n return other\n\n # ------------------------------------------------------------------\n # Additional array methods\n # These are not part of the EA API, but we implement them because\n # pandas assumes they're there.\n\n def value_counts(self, dropna: bool = False):\n \"\"\"\n Return a Series containing counts of unique values.\n\n Parameters\n ----------\n dropna : bool, default True\n Don't include counts of NaT values.\n\n Returns\n -------\n Series\n \"\"\"\n if self.ndim != 1:\n raise NotImplementedError\n\n from pandas import Index, Series\n\n if dropna:\n values = self[~self.isna()]._ndarray\n else:\n values = self._ndarray\n\n cls = type(self)\n\n result = value_counts(values, sort=False, dropna=dropna)\n index = Index(\n cls(result.index.view(\"i8\"), dtype=self.dtype), name=result.index.name\n )\n return Series(result._values, index=index, name=result.name)\n\n @ravel_compat\n def map(self, mapper):\n # TODO(GH-23179): Add ExtensionArray.map\n # Need to figure out if we want ExtensionArray.map first.\n # If so, then we can refactor IndexOpsMixin._map_values to\n # a standalone function and call from here..\n # Else, just rewrite _map_infer_values to do the right thing.\n from pandas import Index\n\n return Index(self).map(mapper).array\n\n def isin(self, values) -> np.ndarray:\n \"\"\"\n Compute boolean array of whether each value is found in the\n passed set of values.\n\n Parameters\n ----------\n values : set or sequence of values\n\n Returns\n -------\n ndarray[bool]\n \"\"\"\n if not hasattr(values, \"dtype\"):\n values = np.asarray(values)\n\n if values.dtype.kind in [\"f\", \"i\", \"u\", \"c\"]:\n # TODO: de-duplicate with equals, validate_comparison_value\n return np.zeros(self.shape, dtype=bool)\n\n if not isinstance(values, type(self)):\n inferable = [\n \"timedelta\",\n \"timedelta64\",\n \"datetime\",\n \"datetime64\",\n \"date\",\n \"period\",\n ]\n if values.dtype == object:\n inferred = lib.infer_dtype(values, skipna=False)\n if inferred not in inferable:\n if inferred == \"string\":\n pass\n\n elif \"mixed\" in inferred:\n return isin(self.astype(object), values)\n else:\n return np.zeros(self.shape, dtype=bool)\n\n try:\n values = type(self)._from_sequence(values)\n except ValueError:\n return isin(self.astype(object), values)\n\n try:\n self._check_compatible_with(values)\n except (TypeError, ValueError):\n # Includes tzawareness mismatch and IncompatibleFrequencyError\n return np.zeros(self.shape, dtype=bool)\n\n return isin(self.asi8, values.asi8)\n\n # ------------------------------------------------------------------\n # Null Handling\n\n def isna(self) -> np.ndarray:\n return self._isnan\n\n @property # NB: override with cache_readonly in immutable subclasses\n def _isnan(self) -> np.ndarray:\n \"\"\"\n return if each value is nan\n \"\"\"\n return self.asi8 == iNaT\n\n @property # NB: override with cache_readonly in immutable subclasses\n def _hasnans(self) -> np.ndarray:\n \"\"\"\n return if I have any nans; enables various perf speedups\n \"\"\"\n return bool(self._isnan.any())\n\n def _maybe_mask_results(\n self, result: np.ndarray, fill_value=iNaT, convert=None\n ) -> np.ndarray:\n \"\"\"\n Parameters\n ----------\n result : np.ndarray\n fill_value : object, default iNaT\n convert : str, dtype or None\n\n Returns\n -------\n result : ndarray with values replace by the fill_value\n\n mask the result if needed, convert to the provided dtype if its not\n None\n\n This is an internal routine.\n \"\"\"\n if self._hasnans:\n if convert:\n result = result.astype(convert)\n if fill_value is None:\n fill_value = np.nan\n np.putmask(result, self._isnan, fill_value)\n return result\n\n # ------------------------------------------------------------------\n # Frequency Properties/Methods\n\n @property\n def freq(self):\n \"\"\"\n Return the frequency object if it is set, otherwise None.\n \"\"\"\n return self._freq\n\n @freq.setter\n def freq(self, value):\n if value is not None:\n value = to_offset(value)\n self._validate_frequency(self, value)\n\n if self.ndim > 1:\n raise ValueError(\"Cannot set freq with ndim > 1\")\n\n self._freq = value\n\n @property\n def freqstr(self):\n \"\"\"\n Return the frequency object as a string if its set, otherwise None.\n \"\"\"\n if self.freq is None:\n return None\n return self.freq.freqstr\n\n @property # NB: override with cache_readonly in immutable subclasses\n def inferred_freq(self):\n \"\"\"\n Tries to return a string representing a frequency guess,\n generated by infer_freq. Returns None if it can't autodetect the\n frequency.\n \"\"\"\n if self.ndim != 1:\n return None\n try:\n return frequencies.infer_freq(self)\n except ValueError:\n return None\n\n @property # NB: override with cache_readonly in immutable subclasses\n def _resolution_obj(self) -> Optional[Resolution]:\n try:\n return Resolution.get_reso_from_freq(self.freqstr)\n except KeyError:\n return None\n\n @property # NB: override with cache_readonly in immutable subclasses\n def resolution(self) -> str:\n \"\"\"\n Returns day, hour, minute, second, millisecond or microsecond\n \"\"\"\n # error: Item \"None\" of \"Optional[Any]\" has no attribute \"attrname\"\n return self._resolution_obj.attrname # type: ignore[union-attr]\n\n @classmethod\n def _validate_frequency(cls, index, freq, **kwargs):\n \"\"\"\n Validate that a frequency is compatible with the values of a given\n Datetime Array/Index or Timedelta Array/Index\n\n Parameters\n ----------\n index : DatetimeIndex or TimedeltaIndex\n The index on which to determine if the given frequency is valid\n freq : DateOffset\n The frequency to validate\n \"\"\"\n # TODO: this is not applicable to PeriodArray, move to correct Mixin\n inferred = index.inferred_freq\n if index.size == 0 or inferred == freq.freqstr:\n return None\n\n try:\n on_freq = cls._generate_range(\n start=index[0], end=None, periods=len(index), freq=freq, **kwargs\n )\n if not np.array_equal(index.asi8, on_freq.asi8):\n raise ValueError\n except ValueError as e:\n if \"non-fixed\" in str(e):\n # non-fixed frequencies are not meaningful for timedelta64;\n # we retain that error message\n raise e\n # GH#11587 the main way this is reached is if the `np.array_equal`\n # check above is False. This can also be reached if index[0]\n # is `NaT`, in which case the call to `cls._generate_range` will\n # raise a ValueError, which we re-raise with a more targeted\n # message.\n raise ValueError(\n f\"Inferred frequency {inferred} from passed values \"\n f\"does not conform to passed frequency {freq.freqstr}\"\n ) from e\n\n @classmethod\n def _generate_range(\n cls: Type[DatetimeLikeArrayT], start, end, periods, freq, *args, **kwargs\n ) -> DatetimeLikeArrayT:\n raise AbstractMethodError(cls)\n\n # monotonicity/uniqueness properties are called via frequencies.infer_freq,\n # see GH#23789\n\n @property\n def _is_monotonic_increasing(self) -> bool:\n return algos.is_monotonic(self.asi8, timelike=True)[0]\n\n @property\n def _is_monotonic_decreasing(self) -> bool:\n return algos.is_monotonic(self.asi8, timelike=True)[1]\n\n @property\n def _is_unique(self) -> bool:\n return len(unique1d(self.asi8.ravel(\"K\"))) == self.size\n\n # ------------------------------------------------------------------\n # Arithmetic Methods\n\n def _cmp_method(self, other, op):\n if self.ndim > 1 and getattr(other, \"shape\", None) == self.shape:\n # TODO: handle 2D-like listlikes\n return op(self.ravel(), other.ravel()).reshape(self.shape)\n\n try:\n other = self._validate_comparison_value(other)\n except InvalidComparison:\n return invalid_comparison(self, other, op)\n\n dtype = getattr(other, \"dtype\", None)\n if is_object_dtype(dtype):\n # We have to use comp_method_OBJECT_ARRAY instead of numpy\n # comparison otherwise it would fail to raise when\n # comparing tz-aware and tz-naive\n with np.errstate(all=\"ignore\"):\n result = ops.comp_method_OBJECT_ARRAY(\n op, np.asarray(self.astype(object)), other\n )\n return result\n\n other_vals = self._unbox(other)\n # GH#37462 comparison on i8 values is almost 2x faster than M8/m8\n result = op(self._ndarray.view(\"i8\"), other_vals.view(\"i8\"))\n\n o_mask = isna(other)\n mask = self._isnan | o_mask\n if mask.any():\n nat_result = op is operator.ne\n np.putmask(result, mask, nat_result)\n\n return result\n\n # pow is invalid for all three subclasses; TimedeltaArray will override\n # the multiplication and division ops\n __pow__ = make_invalid_op(\"__pow__\")\n __rpow__ = make_invalid_op(\"__rpow__\")\n __mul__ = make_invalid_op(\"__mul__\")\n __rmul__ = make_invalid_op(\"__rmul__\")\n __truediv__ = make_invalid_op(\"__truediv__\")\n __rtruediv__ = make_invalid_op(\"__rtruediv__\")\n __floordiv__ = make_invalid_op(\"__floordiv__\")\n __rfloordiv__ = make_invalid_op(\"__rfloordiv__\")\n __mod__ = make_invalid_op(\"__mod__\")\n __rmod__ = make_invalid_op(\"__rmod__\")\n __divmod__ = make_invalid_op(\"__divmod__\")\n __rdivmod__ = make_invalid_op(\"__rdivmod__\")\n\n def _add_datetimelike_scalar(self, other):\n # Overridden by TimedeltaArray\n raise TypeError(f\"cannot add {type(self).__name__} and {type(other).__name__}\")\n\n _add_datetime_arraylike = _add_datetimelike_scalar\n\n def _sub_datetimelike_scalar(self, other):\n # Overridden by DatetimeArray\n assert other is not NaT\n raise TypeError(f\"cannot subtract a datelike from a {type(self).__name__}\")\n\n _sub_datetime_arraylike = _sub_datetimelike_scalar\n\n def _sub_period(self, other):\n # Overridden by PeriodArray\n raise TypeError(f\"cannot subtract Period from a {type(self).__name__}\")\n\n def _add_period(self, other: Period):\n # Overridden by TimedeltaArray\n raise TypeError(f\"cannot add Period to a {type(self).__name__}\")\n\n def _add_offset(self, offset):\n raise AbstractMethodError(self)\n\n def _add_timedeltalike_scalar(self, other):\n \"\"\"\n Add a delta of a timedeltalike\n\n Returns\n -------\n Same type as self\n \"\"\"\n if isna(other):\n # i.e np.timedelta64(\"NaT\"), not recognized by delta_to_nanoseconds\n new_values = np.empty(self.shape, dtype=\"i8\")\n new_values.fill(iNaT)\n return type(self)(new_values, dtype=self.dtype)\n\n inc = delta_to_nanoseconds(other)\n new_values = checked_add_with_arr(self.asi8, inc, arr_mask=self._isnan).view(\n \"i8\"\n )\n new_values = self._maybe_mask_results(new_values)\n\n new_freq = None\n if isinstance(self.freq, Tick) or is_period_dtype(self.dtype):\n # adding a scalar preserves freq\n new_freq = self.freq\n\n return type(self)._simple_new(new_values, dtype=self.dtype, freq=new_freq)\n\n def _add_timedelta_arraylike(self, other):\n \"\"\"\n Add a delta of a TimedeltaIndex\n\n Returns\n -------\n Same type as self\n \"\"\"\n # overridden by PeriodArray\n\n if len(self) != len(other):\n raise ValueError(\"cannot add indices of unequal length\")\n\n if isinstance(other, np.ndarray):\n # ndarray[timedelta64]; wrap in TimedeltaIndex for op\n from pandas.core.arrays import TimedeltaArray\n\n other = TimedeltaArray._from_sequence(other)\n\n self_i8 = self.asi8\n other_i8 = other.asi8\n new_values = checked_add_with_arr(\n self_i8, other_i8, arr_mask=self._isnan, b_mask=other._isnan\n )\n if self._hasnans or other._hasnans:\n mask = self._isnan | other._isnan\n np.putmask(new_values, mask, iNaT)\n\n return type(self)(new_values, dtype=self.dtype)\n\n def _add_nat(self):\n \"\"\"\n Add pd.NaT to self\n \"\"\"\n if is_period_dtype(self.dtype):\n raise TypeError(\n f\"Cannot add {type(self).__name__} and {type(NaT).__name__}\"\n )\n\n # GH#19124 pd.NaT is treated like a timedelta for both timedelta\n # and datetime dtypes\n result = np.empty(self.shape, dtype=np.int64)\n result.fill(iNaT)\n return type(self)(result, dtype=self.dtype, freq=None)\n\n def _sub_nat(self):\n \"\"\"\n Subtract pd.NaT from self\n \"\"\"\n # GH#19124 Timedelta - datetime is not in general well-defined.\n # We make an exception for pd.NaT, which in this case quacks\n # like a timedelta.\n # For datetime64 dtypes by convention we treat NaT as a datetime, so\n # this subtraction returns a timedelta64 dtype.\n # For period dtype, timedelta64 is a close-enough return dtype.\n result = np.empty(self.shape, dtype=np.int64)\n result.fill(iNaT)\n return result.view(\"timedelta64[ns]\")\n\n def _sub_period_array(self, other):\n # Overridden by PeriodArray\n raise TypeError(\n f\"cannot subtract {other.dtype}-dtype from {type(self).__name__}\"\n )\n\n def _addsub_object_array(self, other: np.ndarray, op):\n \"\"\"\n Add or subtract array-like of DateOffset objects\n\n Parameters\n ----------\n other : np.ndarray[object]\n op : {operator.add, operator.sub}\n\n Returns\n -------\n result : same class as self\n \"\"\"\n assert op in [operator.add, operator.sub]\n if len(other) == 1 and self.ndim == 1:\n # If both 1D then broadcasting is unambiguous\n return op(self, other[0])\n\n warnings.warn(\n \"Adding/subtracting object-dtype array to \"\n f\"{type(self).__name__} not vectorized\",\n PerformanceWarning,\n )\n\n # Caller is responsible for broadcasting if necessary\n assert self.shape == other.shape, (self.shape, other.shape)\n\n res_values = op(self.astype(\"O\"), np.asarray(other))\n result = array(res_values.ravel())\n result = extract_array(result, extract_numpy=True).reshape(self.shape)\n return result\n\n def _time_shift(self, periods, freq=None):\n \"\"\"\n Shift each value by `periods`.\n\n Note this is different from ExtensionArray.shift, which\n shifts the *position* of each element, padding the end with\n missing values.\n\n Parameters\n ----------\n periods : int\n Number of periods to shift by.\n freq : pandas.DateOffset, pandas.Timedelta, or str\n Frequency increment to shift by.\n \"\"\"\n if freq is not None and freq != self.freq:\n if isinstance(freq, str):\n freq = to_offset(freq)\n offset = periods * freq\n return self + offset\n\n if periods == 0 or len(self) == 0:\n # GH#14811 empty case\n return self.copy()\n\n if self.freq is None:\n raise NullFrequencyError(\"Cannot shift with no freq\")\n\n start = self[0] + periods * self.freq\n end = self[-1] + periods * self.freq\n\n # Note: in the DatetimeTZ case, _generate_range will infer the\n # appropriate timezone from `start` and `end`, so tz does not need\n # to be passed explicitly.\n return self._generate_range(start=start, end=end, periods=None, freq=self.freq)\n\n @unpack_zerodim_and_defer(\"__add__\")\n def __add__(self, other):\n other_dtype = getattr(other, \"dtype\", None)\n\n # scalar others\n if other is NaT:\n result = self._add_nat()\n elif isinstance(other, (Tick, timedelta, np.timedelta64)):\n result = self._add_timedeltalike_scalar(other)\n elif isinstance(other, BaseOffset):\n # specifically _not_ a Tick\n result = self._add_offset(other)\n elif isinstance(other, (datetime, np.datetime64)):\n result = self._add_datetimelike_scalar(other)\n elif isinstance(other, Period) and is_timedelta64_dtype(self.dtype):\n result = self._add_period(other)\n elif lib.is_integer(other):\n # This check must come after the check for np.timedelta64\n # as is_integer returns True for these\n if not is_period_dtype(self.dtype):\n raise integer_op_not_supported(self)\n result = self._time_shift(other)\n\n # array-like others\n elif is_timedelta64_dtype(other_dtype):\n # TimedeltaIndex, ndarray[timedelta64]\n result = self._add_timedelta_arraylike(other)\n elif is_object_dtype(other_dtype):\n # e.g. Array/Index of DateOffset objects\n result = self._addsub_object_array(other, operator.add)\n elif is_datetime64_dtype(other_dtype) or is_datetime64tz_dtype(other_dtype):\n # DatetimeIndex, ndarray[datetime64]\n return self._add_datetime_arraylike(other)\n elif is_integer_dtype(other_dtype):\n if not is_period_dtype(self.dtype):\n raise integer_op_not_supported(self)\n result = self._addsub_int_array(other, operator.add)\n else:\n # Includes Categorical, other ExtensionArrays\n # For PeriodDtype, if self is a TimedeltaArray and other is a\n # PeriodArray with a timedelta-like (i.e. Tick) freq, this\n # operation is valid. Defer to the PeriodArray implementation.\n # In remaining cases, this will end up raising TypeError.\n return NotImplemented\n\n if isinstance(result, np.ndarray) and is_timedelta64_dtype(result.dtype):\n from pandas.core.arrays import TimedeltaArray\n\n return TimedeltaArray(result)\n return result\n\n def __radd__(self, other):\n # alias for __add__\n return self.__add__(other)\n\n @unpack_zerodim_and_defer(\"__sub__\")\n def __sub__(self, other):\n\n other_dtype = getattr(other, \"dtype\", None)\n\n # scalar others\n if other is NaT:\n result = self._sub_nat()\n elif isinstance(other, (Tick, timedelta, np.timedelta64)):\n result = self._add_timedeltalike_scalar(-other)\n elif isinstance(other, BaseOffset):\n # specifically _not_ a Tick\n result = self._add_offset(-other)\n elif isinstance(other, (datetime, np.datetime64)):\n result = self._sub_datetimelike_scalar(other)\n elif lib.is_integer(other):\n # This check must come after the check for np.timedelta64\n # as is_integer returns True for these\n if not is_period_dtype(self.dtype):\n raise integer_op_not_supported(self)\n result = self._time_shift(-other)\n\n elif isinstance(other, Period):\n result = self._sub_period(other)\n\n # array-like others\n elif is_timedelta64_dtype(other_dtype):\n # TimedeltaIndex, ndarray[timedelta64]\n result = self._add_timedelta_arraylike(-other)\n elif is_object_dtype(other_dtype):\n # e.g. Array/Index of DateOffset objects\n result = self._addsub_object_array(other, operator.sub)\n elif is_datetime64_dtype(other_dtype) or is_datetime64tz_dtype(other_dtype):\n # DatetimeIndex, ndarray[datetime64]\n result = self._sub_datetime_arraylike(other)\n elif is_period_dtype(other_dtype):\n # PeriodIndex\n result = self._sub_period_array(other)\n elif is_integer_dtype(other_dtype):\n if not is_period_dtype(self.dtype):\n raise integer_op_not_supported(self)\n result = self._addsub_int_array(other, operator.sub)\n else:\n # Includes ExtensionArrays, float_dtype\n return NotImplemented\n\n if isinstance(result, np.ndarray) and is_timedelta64_dtype(result.dtype):\n from pandas.core.arrays import TimedeltaArray\n\n return TimedeltaArray(result)\n return result\n\n def __rsub__(self, other):\n other_dtype = getattr(other, \"dtype\", None)\n\n if is_datetime64_any_dtype(other_dtype) and is_timedelta64_dtype(self.dtype):\n # ndarray[datetime64] cannot be subtracted from self, so\n # we need to wrap in DatetimeArray/Index and flip the operation\n if lib.is_scalar(other):\n # i.e. np.datetime64 object\n return Timestamp(other) - self\n if not isinstance(other, DatetimeLikeArrayMixin):\n # Avoid down-casting DatetimeIndex\n from pandas.core.arrays import DatetimeArray\n\n other = DatetimeArray(other)\n return other - self\n elif (\n is_datetime64_any_dtype(self.dtype)\n and hasattr(other, \"dtype\")\n and not is_datetime64_any_dtype(other.dtype)\n ):\n # GH#19959 datetime - datetime is well-defined as timedelta,\n # but any other type - datetime is not well-defined.\n raise TypeError(\n f\"cannot subtract {type(self).__name__} from {type(other).__name__}\"\n )\n elif is_period_dtype(self.dtype) and is_timedelta64_dtype(other_dtype):\n # TODO: Can we simplify/generalize these cases at all?\n raise TypeError(f\"cannot subtract {type(self).__name__} from {other.dtype}\")\n elif is_timedelta64_dtype(self.dtype):\n self = cast(\"TimedeltaArray\", self)\n return (-self) + other\n\n # We get here with e.g. datetime objects\n return -(self - other)\n\n def __iadd__(self, other):\n result = self + other\n self[:] = result[:]\n\n if not is_period_dtype(self.dtype):\n # restore freq, which is invalidated by setitem\n self._freq = result._freq\n return self\n\n def __isub__(self, other):\n result = self - other\n self[:] = result[:]\n\n if not is_period_dtype(self.dtype):\n # restore freq, which is invalidated by setitem\n self._freq = result._freq\n return self\n\n # --------------------------------------------------------------\n # Reductions\n\n def min(self, *, axis=None, skipna=True, **kwargs):\n \"\"\"\n Return the minimum value of the Array or minimum along\n an axis.\n\n See Also\n --------\n numpy.ndarray.min\n Index.min : Return the minimum value in an Index.\n Series.min : Return the minimum value in a Series.\n \"\"\"\n nv.validate_min((), kwargs)\n nv.validate_minmax_axis(axis, self.ndim)\n\n if is_period_dtype(self.dtype):\n # pass datetime64 values to nanops to get correct NaT semantics\n result = nanops.nanmin(\n self._ndarray.view(\"M8[ns]\"), axis=axis, skipna=skipna\n )\n if result is NaT:\n return NaT\n result = result.view(\"i8\")\n if axis is None or self.ndim == 1:\n return self._box_func(result)\n return self._from_backing_data(result)\n\n result = nanops.nanmin(self._ndarray, axis=axis, skipna=skipna)\n return self._wrap_reduction_result(axis, result)\n\n def max(self, *, axis=None, skipna=True, **kwargs):\n \"\"\"\n Return the maximum value of the Array or maximum along\n an axis.\n\n See Also\n --------\n numpy.ndarray.max\n Index.max : Return the maximum value in an Index.\n Series.max : Return the maximum value in a Series.\n \"\"\"\n # TODO: skipna is broken with max.\n # See https://github.com/pandas-dev/pandas/issues/24265\n nv.validate_max((), kwargs)\n nv.validate_minmax_axis(axis, self.ndim)\n\n if is_period_dtype(self.dtype):\n # pass datetime64 values to nanops to get correct NaT semantics\n result = nanops.nanmax(\n self._ndarray.view(\"M8[ns]\"), axis=axis, skipna=skipna\n )\n if result is NaT:\n return result\n result = result.view(\"i8\")\n if axis is None or self.ndim == 1:\n return self._box_func(result)\n return self._from_backing_data(result)\n\n result = nanops.nanmax(self._ndarray, axis=axis, skipna=skipna)\n return self._wrap_reduction_result(axis, result)\n\n def mean(self, *, skipna=True, axis: Optional[int] = 0):\n \"\"\"\n Return the mean value of the Array.\n\n .. versionadded:: 0.25.0\n\n Parameters\n ----------\n skipna : bool, default True\n Whether to ignore any NaT elements.\n axis : int, optional, default 0\n\n Returns\n -------\n scalar\n Timestamp or Timedelta.\n\n See Also\n --------\n numpy.ndarray.mean : Returns the average of array elements along a given axis.\n Series.mean : Return the mean value in a Series.\n\n Notes\n -----\n mean is only defined for Datetime and Timedelta dtypes, not for Period.\n \"\"\"\n if is_period_dtype(self.dtype):\n # See discussion in GH#24757\n raise TypeError(\n f\"mean is not implemented for {type(self).__name__} since the \"\n \"meaning is ambiguous. An alternative is \"\n \"obj.to_timestamp(how='start').mean()\"\n )\n\n result = nanops.nanmean(\n self._ndarray, axis=axis, skipna=skipna, mask=self.isna()\n )\n return self._wrap_reduction_result(axis, result)\n\n def median(self, *, axis: Optional[int] = None, skipna: bool = True, **kwargs):\n nv.validate_median((), kwargs)\n\n if axis is not None and abs(axis) >= self.ndim:\n raise ValueError(\"abs(axis) must be less than ndim\")\n\n if is_period_dtype(self.dtype):\n # pass datetime64 values to nanops to get correct NaT semantics\n result = nanops.nanmedian(\n self._ndarray.view(\"M8[ns]\"), axis=axis, skipna=skipna\n )\n result = result.view(\"i8\")\n if axis is None or self.ndim == 1:\n return self._box_func(result)\n return self._from_backing_data(result)\n\n result = nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna)\n return self._wrap_reduction_result(axis, result)\n\n\nclass DatelikeOps(DatetimeLikeArrayMixin):\n \"\"\"\n Common ops for DatetimeIndex/PeriodIndex, but not TimedeltaIndex.\n \"\"\"\n\n @Substitution(\n URL=\"https://docs.python.org/3/library/datetime.html\"\n \"#strftime-and-strptime-behavior\"\n )\n def strftime(self, date_format):\n \"\"\"\n Convert to Index using specified date_format.\n\n Return an Index of formatted strings specified by date_format, which\n supports the same string format as the python standard library. Details\n of the string format can be found in `python string format\n doc <%(URL)s>`__.\n\n Parameters\n ----------\n date_format : str\n Date format string (e.g. \"%%Y-%%m-%%d\").\n\n Returns\n -------\n ndarray\n NumPy ndarray of formatted strings.\n\n See Also\n --------\n to_datetime : Convert the given argument to datetime.\n DatetimeIndex.normalize : Return DatetimeIndex with times to midnight.\n DatetimeIndex.round : Round the DatetimeIndex to the specified freq.\n DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq.\n\n Examples\n --------\n >>> rng = pd.date_range(pd.Timestamp(\"2018-03-10 09:00\"),\n ... periods=3, freq='s')\n >>> rng.strftime('%%B %%d, %%Y, %%r')\n Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM',\n 'March 10, 2018, 09:00:02 AM'],\n dtype='object')\n \"\"\"\n result = self._format_native_types(date_format=date_format, na_rep=np.nan)\n return result.astype(object)\n\n\n_round_doc = \"\"\"\n Perform {op} operation on the data to the specified `freq`.\n\n Parameters\n ----------\n freq : str or Offset\n The frequency level to {op} the index to. Must be a fixed\n frequency like 'S' (second) not 'ME' (month end). See\n :ref:`frequency aliases <timeseries.offset_aliases>` for\n a list of possible `freq` values.\n ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'\n Only relevant for DatetimeIndex:\n\n - 'infer' will attempt to infer fall dst-transition hours based on\n order\n - bool-ndarray where True signifies a DST time, False designates\n a non-DST time (note that this flag is only applicable for\n ambiguous times)\n - 'NaT' will return NaT where there are ambiguous times\n - 'raise' will raise an AmbiguousTimeError if there are ambiguous\n times.\n\n .. versionadded:: 0.24.0\n\n nonexistent : 'shift_forward', 'shift_backward', 'NaT', timedelta, default 'raise'\n A nonexistent time does not exist in a particular timezone\n where clocks moved forward due to DST.\n\n - 'shift_forward' will shift the nonexistent time forward to the\n closest existing time\n - 'shift_backward' will shift the nonexistent time backward to the\n closest existing time\n - 'NaT' will return NaT where there are nonexistent times\n - timedelta objects will shift nonexistent times by the timedelta\n - 'raise' will raise an NonExistentTimeError if there are\n nonexistent times.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n DatetimeIndex, TimedeltaIndex, or Series\n Index of the same type for a DatetimeIndex or TimedeltaIndex,\n or a Series with the same index for a Series.\n\n Raises\n ------\n ValueError if the `freq` cannot be converted.\n\n Examples\n --------\n **DatetimeIndex**\n\n >>> rng = pd.date_range('1/1/2018 11:59:00', periods=3, freq='min')\n >>> rng\n DatetimeIndex(['2018-01-01 11:59:00', '2018-01-01 12:00:00',\n '2018-01-01 12:01:00'],\n dtype='datetime64[ns]', freq='T')\n \"\"\"\n\n_round_example = \"\"\">>> rng.round('H')\n DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00',\n '2018-01-01 12:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Series**\n\n >>> pd.Series(rng).dt.round(\"H\")\n 0 2018-01-01 12:00:00\n 1 2018-01-01 12:00:00\n 2 2018-01-01 12:00:00\n dtype: datetime64[ns]\n \"\"\"\n\n_floor_example = \"\"\">>> rng.floor('H')\n DatetimeIndex(['2018-01-01 11:00:00', '2018-01-01 12:00:00',\n '2018-01-01 12:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Series**\n\n >>> pd.Series(rng).dt.floor(\"H\")\n 0 2018-01-01 11:00:00\n 1 2018-01-01 12:00:00\n 2 2018-01-01 12:00:00\n dtype: datetime64[ns]\n \"\"\"\n\n_ceil_example = \"\"\">>> rng.ceil('H')\n DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00',\n '2018-01-01 13:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Series**\n\n >>> pd.Series(rng).dt.ceil(\"H\")\n 0 2018-01-01 12:00:00\n 1 2018-01-01 12:00:00\n 2 2018-01-01 13:00:00\n dtype: datetime64[ns]\n \"\"\"\n\n\nclass TimelikeOps(DatetimeLikeArrayMixin):\n \"\"\"\n Common ops for TimedeltaIndex/DatetimeIndex, but not PeriodIndex.\n \"\"\"\n\n def _round(self, freq, mode, ambiguous, nonexistent):\n # round the local times\n if is_datetime64tz_dtype(self.dtype):\n # operate on naive timestamps, then convert back to aware\n self = cast(\"DatetimeArray\", self)\n naive = self.tz_localize(None)\n result = naive._round(freq, mode, ambiguous, nonexistent)\n return result.tz_localize(\n self.tz, ambiguous=ambiguous, nonexistent=nonexistent\n )\n\n values = self.view(\"i8\")\n result = round_nsint64(values, mode, freq)\n result = self._maybe_mask_results(result, fill_value=NaT)\n return self._simple_new(result, dtype=self.dtype)\n\n @Appender((_round_doc + _round_example).format(op=\"round\"))\n def round(self, freq, ambiguous=\"raise\", nonexistent=\"raise\"):\n return self._round(freq, RoundTo.NEAREST_HALF_EVEN, ambiguous, nonexistent)\n\n @Appender((_round_doc + _floor_example).format(op=\"floor\"))\n def floor(self, freq, ambiguous=\"raise\", nonexistent=\"raise\"):\n return self._round(freq, RoundTo.MINUS_INFTY, ambiguous, nonexistent)\n\n @Appender((_round_doc + _ceil_example).format(op=\"ceil\"))\n def ceil(self, freq, ambiguous=\"raise\", nonexistent=\"raise\"):\n return self._round(freq, RoundTo.PLUS_INFTY, ambiguous, nonexistent)\n\n # --------------------------------------------------------------\n # Frequency Methods\n\n def _maybe_clear_freq(self):\n self._freq = None\n\n def _with_freq(self, freq):\n \"\"\"\n Helper to get a view on the same data, with a new freq.\n\n Parameters\n ----------\n freq : DateOffset, None, or \"infer\"\n\n Returns\n -------\n Same type as self\n \"\"\"\n # GH#29843\n if freq is None:\n # Always valid\n pass\n elif len(self) == 0 and isinstance(freq, BaseOffset):\n # Always valid. In the TimedeltaArray case, we assume this\n # is a Tick offset.\n pass\n else:\n # As an internal method, we can ensure this assertion always holds\n assert freq == \"infer\"\n freq = to_offset(self.inferred_freq)\n\n arr = self.view()\n arr._freq = freq\n return arr\n\n # --------------------------------------------------------------\n\n def factorize(self, na_sentinel=-1, sort: bool = False):\n if self.freq is not None:\n # We must be unique, so can short-circuit (and retain freq)\n codes = np.arange(len(self), dtype=np.intp)\n uniques = self.copy() # TODO: copy or view?\n if sort and self.freq.n < 0:\n codes = codes[::-1]\n # TODO: overload __getitem__, a slice indexer returns same type as self\n # error: Incompatible types in assignment (expression has type\n # \"Union[DatetimeLikeArrayMixin, Union[Any, Any]]\", variable\n # has type \"TimelikeOps\") [assignment]\n uniques = uniques[::-1] # type: ignore[assignment]\n return codes, uniques\n # FIXME: shouldn't get here; we are ignoring sort\n return super().factorize(na_sentinel=na_sentinel)\n\n\n# -------------------------------------------------------------------\n# Shared Constructor Helpers\n\n\ndef validate_periods(periods):\n \"\"\"\n If a `periods` argument is passed to the Datetime/Timedelta Array/Index\n constructor, cast it to an integer.\n\n Parameters\n ----------\n periods : None, float, int\n\n Returns\n -------\n periods : None or int\n\n Raises\n ------\n TypeError\n if periods is None, float, or int\n \"\"\"\n if periods is not None:\n if lib.is_float(periods):\n periods = int(periods)\n elif not lib.is_integer(periods):\n raise TypeError(f\"periods must be a number, got {periods}\")\n return periods\n\n\ndef validate_endpoints(closed):\n \"\"\"\n Check that the `closed` argument is among [None, \"left\", \"right\"]\n\n Parameters\n ----------\n closed : {None, \"left\", \"right\"}\n\n Returns\n -------\n left_closed : bool\n right_closed : bool\n\n Raises\n ------\n ValueError : if argument is not among valid values\n \"\"\"\n left_closed = False\n right_closed = False\n\n if closed is None:\n left_closed = True\n right_closed = True\n elif closed == \"left\":\n left_closed = True\n elif closed == \"right\":\n right_closed = True\n else:\n raise ValueError(\"Closed has to be either 'left', 'right' or None\")\n\n return left_closed, right_closed\n\n\ndef validate_inferred_freq(freq, inferred_freq, freq_infer):\n \"\"\"\n If the user passes a freq and another freq is inferred from passed data,\n require that they match.\n\n Parameters\n ----------\n freq : DateOffset or None\n inferred_freq : DateOffset or None\n freq_infer : bool\n\n Returns\n -------\n freq : DateOffset or None\n freq_infer : bool\n\n Notes\n -----\n We assume at this point that `maybe_infer_freq` has been called, so\n `freq` is either a DateOffset object or None.\n \"\"\"\n if inferred_freq is not None:\n if freq is not None and freq != inferred_freq:\n raise ValueError(\n f\"Inferred frequency {inferred_freq} from passed \"\n \"values does not conform to passed frequency \"\n f\"{freq.freqstr}\"\n )\n elif freq is None:\n freq = inferred_freq\n freq_infer = False\n\n return freq, freq_infer\n\n\ndef maybe_infer_freq(freq):\n \"\"\"\n Comparing a DateOffset to the string \"infer\" raises, so we need to\n be careful about comparisons. Make a dummy variable `freq_infer` to\n signify the case where the given freq is \"infer\" and set freq to None\n to avoid comparison trouble later on.\n\n Parameters\n ----------\n freq : {DateOffset, None, str}\n\n Returns\n -------\n freq : {DateOffset, None}\n freq_infer : bool\n Whether we should inherit the freq of passed data.\n \"\"\"\n freq_infer = False\n if not isinstance(freq, BaseOffset):\n # if a passed freq is None, don't infer automatically\n if freq != \"infer\":\n freq = to_offset(freq)\n else:\n freq_infer = True\n freq = None\n return freq, freq_infer\n" ]
[ [ "pandas.Series", "pandas._libs.tslibs.Timestamp", "numpy.asarray", "pandas.core.dtypes.common.is_extension_array_dtype", "pandas.core.dtypes.common.is_dtype_equal", "pandas._libs.lib.is_scalar", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas.core.arrays.TimedeltaArray", "pandas.core.dtypes.common.is_datetime64_dtype", "pandas.core.indexers.check_array_indexer", "pandas.core.nanops.nanmin", "pandas.core.indexers.check_setitem_lengths", "pandas.core.ops.common.unpack_zerodim_and_defer", "pandas.compat.numpy.function.validate_median", "pandas.core.dtypes.common.is_unsigned_integer_dtype", "pandas.util._decorators.Substitution", "pandas.core.ops.invalid.invalid_comparison", "pandas._libs.tslibs.to_offset", "pandas.errors.AbstractMethodError", "pandas.core.construction.array", "pandas._libs.lib.is_integer", "pandas._libs.tslibs.timestamps.round_nsint64", "pandas.Index", "pandas._libs.lib.map_infer", "pandas.errors.NullFrequencyError", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.dtypes.common.is_string_dtype", "pandas.core.nanops.nanmedian", "numpy.zeros", "pandas.core.dtypes.common.is_categorical_dtype", "pandas.core.ops.invalid.make_invalid_op", "pandas.core.dtypes.common.is_list_like", "numpy.putmask", "pandas.core.dtypes.common.is_integer_dtype", "pandas._libs.tslibs.delta_to_nanoseconds", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.algorithms.checked_add_with_arr", "pandas.core.dtypes.common.is_timedelta64_dtype", "pandas.core.dtypes.common.is_datetime64_any_dtype", "pandas.core.dtypes.common.is_period_dtype", "pandas._libs.tslibs.timestamps.integer_op_not_supported", "pandas.core.arrays.DatetimeArray", "pandas._libs.algos.is_monotonic", "numpy.errstate", "pandas._libs.tslibs.Period._from_ordinal", "pandas.core.dtypes.missing.is_valid_nat_for_dtype", "pandas.compat.numpy.function.validate_minmax_axis", "pandas._libs.lib.is_float", "numpy.array_equal", "pandas.core.algorithms.isin", "pandas._libs.tslibs.Resolution.get_reso_from_freq", "pandas.core.arrays.TimedeltaArray._from_sequence", "pandas.core.common.is_bool_indexer", "pandas.compat.numpy.function.validate_max", "pandas.core.algorithms.value_counts", "pandas.compat.numpy.function.validate_min", "pandas.tseries.frequencies.infer_freq", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.dtypes.missing.isna", "pandas.core.dtypes.common.is_datetime_or_timedelta_dtype", "pandas._libs.lib.infer_dtype", "pandas.core.nanops.nanmax", "pandas.core.construction.extract_array", "numpy.empty" ] ]
Butters-cloud/Denoising-Normalizing-Flow
[ "2aeafbaebc9b49737b602ccf65bbb60499c0119e" ]
[ "experiments/training/trainer.py" ]
[ "import logging\nimport numpy as np\nimport torch\nfrom torch import optim, nn\nfrom torch.autograd import grad\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch.nn.utils import clip_grad_norm_\n\nimport random\n\nlogger = logging.getLogger(__name__)\n\n\nclass EarlyStoppingException(Exception):\n pass\n\n\nclass NanException(Exception):\n pass\n\n\nclass BaseTrainer(object):\n \"\"\" Training functionality shared between normal trainers and alternating trainers. \"\"\"\n\n def __init__(self, model, run_on_gpu=True, multi_gpu=True, double_precision=False):\n self.model = model\n\n self.run_on_gpu = run_on_gpu and torch.cuda.is_available()\n self.multi_gpu = self.run_on_gpu and multi_gpu and torch.cuda.device_count() > 1\n\n self.device = torch.device(\"cuda\" if self.run_on_gpu else \"cpu\")\n self.dtype = torch.double if double_precision else torch.float\n if self.run_on_gpu and double_precision:\n torch.set_default_tensor_type(\"torch.cuda.DoubleTensor\")\n elif self.run_on_gpu:\n torch.set_default_tensor_type(\"torch.cuda.FloatTensor\")\n elif double_precision:\n torch.set_default_tensor_type(\"torch.DoubleTensor\")\n else:\n torch.set_default_tensor_type(\"torch.FloatTensor\")\n\n self.model = self.model.to(self.device, self.dtype)\n self.last_batch = None\n\n logger.info(\n \"Training on %s with %s precision\",\n \"{} GPUS\".format(torch.cuda.device_count()) if self.multi_gpu else \"GPU\" if self.run_on_gpu else \"CPU\",\n \"double\" if double_precision else \"single\",\n )\n\n def check_early_stopping(self, best_loss, best_model, best_epoch, loss, i_epoch, early_stopping_patience=None):\n try:\n loss_ = loss[0]\n except:\n loss_ = loss\n\n if best_loss is None or loss_ < best_loss:\n best_loss = loss_\n best_model = self.model.state_dict()\n best_epoch = i_epoch\n\n if early_stopping_patience is not None and i_epoch - best_epoch > early_stopping_patience >= 0:\n raise EarlyStoppingException\n\n return best_loss, best_model, best_epoch\n\n def wrap_up_early_stopping(self, best_model, currrent_loss, best_loss, best_epoch):\n try:\n loss_ = currrent_loss[0]\n except:\n loss_ = currrent_loss\n\n if loss_ is None or best_loss is None:\n logger.warning(\"Loss is None, cannot wrap up early stopping\")\n elif best_loss < loss_:\n logger.info(\"Early stopping after epoch %s, with loss %8.5f compared to final loss %8.5f\", best_epoch + 1, best_loss, loss_)\n self.model.load_state_dict(best_model)\n else:\n logger.info(\"Early stopping did not improve performance\")\n\n @staticmethod\n def report_epoch(i_epoch, loss_labels, loss_train, loss_val, loss_contributions_train, loss_contributions_val, verbose=False):\n logging_fn = logger.info if verbose else logger.debug\n\n def contribution_summary(labels, contributions):\n summary = \"\"\n for i, (label, value) in enumerate(zip(labels, contributions)):\n if i > 0:\n summary += \", \"\n summary += \"{}: {:>6.3f}\".format(label, value)\n return summary\n\n try:\n train_report = \"Epoch {:>3d}: train loss {:>8.5f} +/- {:>8.5f} ({})\".format(\n i_epoch + 1, loss_train[0], loss_train[1], contribution_summary(loss_labels, loss_contributions_train)\n )\n except:\n train_report = \"Epoch {:>3d}: train loss {:>8.5f} ({})\".format(i_epoch + 1, loss_train, contribution_summary(loss_labels, loss_contributions_train))\n logging_fn(train_report)\n\n if loss_val is not None:\n try:\n val_report = \" val. loss {:>8.5f} +/- {:>8.5f} ({})\".format(loss_val[0], loss_val[1], contribution_summary(loss_labels, loss_contributions_val))\n except:\n val_report = \" val. loss {:>8.5f} ({})\".format(loss_val, contribution_summary(loss_labels, loss_contributions_val))\n logging_fn(val_report)\n\n @staticmethod\n def _check_for_nans(label, *tensors, fix_until=None, replace=0.0):\n for tensor in tensors:\n if tensor is None:\n continue\n\n if torch.isnan(tensor).any():\n n_nans = torch.sum(torch.isnan(tensor)).item()\n if fix_until is not None:\n if n_nans <= fix_until:\n logger.debug(\"%s contains %s NaNs, setting them to zero\", label, n_nans)\n tensor[torch.isnan(tensor)] = replace\n return\n\n logger.warning(\"%s contains %s NaNs, aborting training!\", label, n_nans)\n raise NanException\n\n @staticmethod\n def make_dataloader(dataset, validation_split, batch_size, n_workers=4):\n logger.debug(\"Setting up dataloaders with %s workers\", n_workers)\n\n if validation_split is None or validation_split <= 0.0:\n train_loader = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=True,\n # pin_memory=self.run_on_gpu,\n num_workers=n_workers,\n )\n val_loader = None\n\n else:\n assert 0.0 < validation_split < 1.0, \"Wrong validation split: {}\".format(validation_split)\n\n n_samples = len(dataset)\n indices = list(range(n_samples))\n split = int(np.floor(validation_split * n_samples))\n np.random.shuffle(indices)\n train_idx, valid_idx = indices[split:], indices[:split]\n if dataset in ['thin_spiral']:\n np.save(create_filename(\"sample\", \"validation_index\", args), valid_idx) #save validation indices for PAE evaluation\n logger.debug(\"Training partition indices: %s...\", train_idx[:10])\n logger.debug(\"Validation partition indices: %s...\", valid_idx[:10])\n\n train_sampler = SubsetRandomSampler(train_idx)\n val_sampler = SubsetRandomSampler(valid_idx)\n\n train_loader = DataLoader(\n dataset,\n sampler=train_sampler,\n batch_size=batch_size,\n # pin_memory=self.run_on_gpu,\n num_workers=n_workers,\n )\n val_loader = DataLoader(\n dataset,\n sampler=val_sampler,\n batch_size=batch_size,\n # pin_memory=self.run_on_gpu,\n num_workers=n_workers,\n )\n \n\n return train_loader, val_loader\n\n @staticmethod\n def sum_losses(contributions, weights):\n loss = weights[0] * contributions[0]\n for _w, _l in zip(weights[1:], contributions[1:]):\n loss = loss + _w * _l\n return loss\n\n def optimizer_step(self, optimizer, loss, clip_gradient, parameters):\n optimizer.zero_grad()\n loss.backward()\n if clip_gradient is not None:\n clip_grad_norm_(parameters, clip_gradient)\n # grad_norm = clip_grad_norm_(parameters, clip_gradient)\n # logger.debug(\" Gradient norm (clipping at %s): %s\", clip_gradient, grad_norm)\n optimizer.step()\n\n @staticmethod\n def _set_verbosity(epochs, verbose):\n # Verbosity\n if verbose == \"all\": # Print output after every epoch\n n_epochs_verbose = 1\n elif verbose == \"many\": # Print output after 2%, 4%, ..., 100% progress\n n_epochs_verbose = max(int(round(epochs / 50, 0)), 1)\n elif verbose == \"some\": # Print output after 10%, 20%, ..., 100% progress\n n_epochs_verbose = max(int(round(epochs / 20, 0)), 1)\n elif verbose == \"few\": # Print output after 20%, 40%, ..., 100% progress\n n_epochs_verbose = max(int(round(epochs / 5, 0)), 1)\n elif verbose == \"none\": # Never print output\n n_epochs_verbose = epochs + 2\n else:\n raise ValueError(\"Unknown value %s for keyword verbose\", verbose)\n return n_epochs_verbose\n\n\n\nclass Trainer(BaseTrainer):\n \"\"\" Base trainer class. Any subclass has to implement the forward_pass() function. \"\"\"\n\n def train(\n self,\n dataset,\n loss_functions,\n loss_weights=None,\n loss_labels=None,\n epochs=50,\n batch_size=100,\n optimizer=optim.AdamW,\n optimizer_kwargs=None,\n initial_lr=1.0e-3,\n scheduler=optim.lr_scheduler.CosineAnnealingLR,\n scheduler_kwargs=None,\n restart_scheduler=None,\n validation_split=0.25,\n early_stopping=True,\n early_stopping_patience=None,\n clip_gradient=1.0,\n verbose=\"all\",\n parameters=None,\n callbacks=None,\n forward_kwargs=None,\n custom_kwargs=None,\n compute_loss_variance=False,\n seed=None,\n initial_epoch=None,\n sig2 = 0.0,\n noise_type = None\n ):\n\n if initial_epoch is not None and initial_epoch >= epochs:\n logging.info(\"Initial epoch is larger than epochs, nothing to do in this training phase!\")\n elif initial_epoch is not None and initial_epoch <= 0:\n initial_epoch = None\n\n if loss_labels is None:\n loss_labels = [fn.__name__ for fn in loss_functions]\n \n \n if seed is not None:\n np.random.seed(seed)\n torch.manual_seed(seed)\n \"\"\" \n seed = 1237\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n \"\"\"\n logger.debug(\"Initialising training data\")\n train_loader, val_loader = self.make_dataloader(dataset, validation_split, batch_size)\n \n logger.debug(\"Setting up optimizer\")\n optimizer_kwargs = {} if optimizer_kwargs is None else optimizer_kwargs\n if parameters is None:\n parameters = list(self.model.parameters())\n opt = optimizer(parameters, lr=initial_lr, **optimizer_kwargs)\n \n \n logger.debug(\"Setting up LR scheduler\")\n if epochs < 2:\n scheduler = None\n logger.info(\"Deactivating scheduler for only %s epoch\", epochs)\n scheduler_kwargs = {} if scheduler_kwargs is None else scheduler_kwargs\n sched = None\n epochs_per_scheduler = restart_scheduler if restart_scheduler is not None else epochs\n if scheduler is not None:\n try:\n sched = scheduler(optimizer=opt, T_max=epochs_per_scheduler, **scheduler_kwargs)\n except:\n sched = scheduler(optimizer=opt, **scheduler_kwargs)\n\n early_stopping = early_stopping and (validation_split is not None) and (epochs > 1)\n best_loss, best_model, best_epoch = None, None, None\n if early_stopping and early_stopping_patience is None:\n logger.debug(\"Using early stopping with infinite patience\")\n elif early_stopping:\n logger.debug(\"Using early stopping with patience %s\", early_stopping_patience)\n else:\n logger.debug(\"No early stopping\")\n\n n_losses = len(loss_labels)\n loss_weights = [1.0] * n_losses if loss_weights is None else loss_weights\n\n n_epochs_verbose = self._set_verbosity(epochs, verbose)\n\n logger.debug(\"Beginning main training loop\")\n losses_train, losses_val = [], []\n\n # Resuming training\n if initial_epoch is None:\n initial_epoch = 0\n else:\n logger.info(\"Resuming with epoch %s\", initial_epoch + 1)\n for _ in range(initial_epoch):\n sched.step() # Hacky, but last_epoch doesn't work when not saving the optimizer state\n\n # Initial callbacks\n if callbacks is not None:\n for callback in callbacks:\n callback(-1, self.model, 0.0, 0.0, last_batch=self.last_batch)\n\n # Loop over epochs\n for i_epoch in range(initial_epoch, epochs):\n logger.debug(\"Training epoch %s / %s\", i_epoch + 1, epochs)\n\n # LR schedule\n if sched is not None:\n logger.debug(\"Learning rate: %s\", sched.get_last_lr())\n\n try:\n loss_train, loss_val, loss_contributions_train, loss_contributions_val = self.epoch(\n i_epoch,\n train_loader,\n val_loader,\n opt,\n loss_functions,\n loss_weights,\n clip_gradient,\n parameters,\n sig2,\n noise_type,\n forward_kwargs=forward_kwargs,\n custom_kwargs=custom_kwargs,\n compute_loss_variance=compute_loss_variance,\n )\n losses_train.append(loss_train)\n losses_val.append(loss_val)\n except NanException:\n logger.info(\"Ending training during epoch %s because NaNs appeared\", i_epoch + 1)\n raise\n\n if early_stopping:\n try:\n best_loss, best_model, best_epoch = self.check_early_stopping(best_loss, best_model, best_epoch, loss_val, i_epoch, early_stopping_patience)\n except EarlyStoppingException:\n logger.info(\"Early stopping: ending training after %s epochs\", i_epoch + 1)\n break\n\n verbose_epoch = (i_epoch + 1) % n_epochs_verbose == 0\n self.report_epoch(i_epoch, loss_labels, loss_train, loss_val, loss_contributions_train, loss_contributions_val, verbose=verbose_epoch)\n\n # Callbacks\n if callbacks is not None:\n for callback in callbacks:\n callback(i_epoch, self.model, loss_train, loss_val, last_batch=self.last_batch)\n\n # LR scheduler\n if sched is not None:\n sched.step()\n if restart_scheduler is not None and (i_epoch + 1) % restart_scheduler == 0:\n try:\n sched = scheduler(optimizer=opt, T_max=epochs_per_scheduler, **scheduler_kwargs)\n except:\n sched = scheduler(optimizer=opt, **scheduler_kwargs)\n\n if early_stopping and len(losses_val) > 0:\n self.wrap_up_early_stopping(best_model, losses_val[-1], best_loss, best_epoch)\n\n logger.debug(\"Training finished\")\n\n return np.array(losses_train), np.array(losses_val)\n\n def epoch(\n self,\n i_epoch,\n train_loader,\n val_loader,\n optimizer,\n loss_functions,\n loss_weights,\n clip_gradient,\n parameters,\n sig2,\n noise_type,\n forward_kwargs=None,\n custom_kwargs=None,\n compute_loss_variance=False,\n ):\n n_losses = len(loss_weights)\n \n self.model.train()\n loss_contributions_train = np.zeros(n_losses)\n loss_train = [] if compute_loss_variance else 0.0\n \n for i_batch, batch_data in enumerate(train_loader):\n if i_batch == 0 and i_epoch == 0:\n self.first_batch(batch_data)\n batch_loss, batch_loss_contributions = self.batch_train(\n batch_data, loss_functions, loss_weights, optimizer, clip_gradient, parameters,sig2,noise_type,i_epoch, forward_kwargs=forward_kwargs, custom_kwargs=custom_kwargs\n )\n if compute_loss_variance:\n loss_train.append(batch_loss)\n else:\n loss_train += batch_loss\n for i, batch_loss_contribution in enumerate(batch_loss_contributions[:n_losses]):\n loss_contributions_train[i] += batch_loss_contribution\n\n self.report_batch(i_epoch, i_batch, True, batch_data, batch_loss)\n\n loss_contributions_train /= len(train_loader)\n if compute_loss_variance:\n loss_train = np.array([np.mean(loss_train), np.std(loss_train)])\n else:\n loss_train /= len(train_loader)\n\n if val_loader is not None:\n self.model.eval()\n loss_contributions_val = np.zeros(n_losses)\n loss_val = [] if compute_loss_variance else 0.0\n\n for i_batch, batch_data in enumerate(val_loader):\n batch_loss, batch_loss_contributions = self.batch_val(batch_data, loss_functions, loss_weights,None,noise_type,i_epoch, forward_kwargs=forward_kwargs, custom_kwargs=custom_kwargs)\n if compute_loss_variance:\n loss_val.append(batch_loss)\n else:\n loss_val += batch_loss\n for i, batch_loss_contribution in enumerate(batch_loss_contributions[:n_losses]):\n loss_contributions_val[i] += batch_loss_contribution\n\n self.report_batch(i_epoch, i_batch, False, batch_data, batch_loss)\n\n loss_contributions_val /= len(val_loader)\n if compute_loss_variance:\n loss_val = np.array([np.mean(loss_val), np.std(loss_val)])\n else:\n loss_val /= len(val_loader)\n\n else:\n loss_contributions_val = None\n loss_val = None\n\n return loss_train, loss_val, loss_contributions_train, loss_contributions_val\n\n def partial_epoch(\n self,\n i_epoch,\n train_loader,\n val_loader,\n optimizer,\n loss_functions,\n loss_weights,\n parameters,\n sig2 = None,\n noise_type = None,\n clip_gradient=None,\n i_batch_start_train=0,\n i_batch_start_val=0,\n forward_kwargs=None,\n custom_kwargs=None,\n compute_loss_variance=False,\n ):\n if compute_loss_variance:\n raise NotImplementedError\n\n n_losses = len(loss_weights)\n assert len(loss_functions) == n_losses, \"{} loss functions, but {} weights\".format(len(loss_functions), n_losses)\n\n self.model.train()\n loss_contributions_train = np.zeros(n_losses)\n loss_train = [] if compute_loss_variance else 0.0\n\n i_batch = i_batch_start_train\n\n for batch_data in train_loader:\n if i_batch == 0 and i_epoch == 0:\n self.first_batch(batch_data)\n batch_loss, batch_loss_contributions = self.batch_train(\n batch_data, loss_functions, loss_weights, optimizer, clip_gradient, parameters,sig2,noise_type,i_epoch,forward_kwargs=forward_kwargs, custom_kwargs=custom_kwargs\n )\n if compute_loss_variance:\n loss_train.append(batch_loss)\n else:\n loss_train += batch_loss\n for i, batch_loss_contribution in enumerate(batch_loss_contributions[:n_losses]):\n loss_contributions_train[i] += batch_loss_contribution\n\n self.report_batch(i_epoch, i_batch, True, batch_data, batch_loss)\n\n i_batch += 1\n\n loss_contributions_train /= len(train_loader)\n if compute_loss_variance:\n loss_train = np.array([np.mean(loss_train), np.std(loss_train)])\n else:\n loss_train /= len(train_loader)\n\n if val_loader is not None:\n self.model.eval()\n loss_contributions_val = np.zeros(n_losses)\n loss_val = [] if compute_loss_variance else 0.0\n\n i_batch = i_batch_start_val\n\n for batch_data in val_loader:\n batch_loss, batch_loss_contributions = self.batch_val(batch_data, loss_functions, loss_weights, None, noise_type, i_epoch,forward_kwargs=forward_kwargs, custom_kwargs=custom_kwargs)\n if compute_loss_variance:\n loss_val.append(batch_loss)\n else:\n loss_val += batch_loss\n for i, batch_loss_contribution in enumerate(batch_loss_contributions[:n_losses]):\n loss_contributions_val[i] += batch_loss_contribution\n\n self.report_batch(i_epoch, i_batch, False, batch_data, batch_loss)\n\n i_batch += 1\n\n loss_contributions_val /= len(val_loader)\n if compute_loss_variance:\n loss_val = np.array([np.mean(loss_val), np.std(loss_val)])\n else:\n loss_val /= len(val_loader)\n\n else:\n loss_contributions_val = None\n loss_val = None\n\n return loss_train, loss_val, loss_contributions_train, loss_contributions_val\n\n def first_batch(self, batch_data):\n pass\n\n def batch_train(self, batch_data, loss_functions, loss_weights, optimizer, clip_gradient, parameters, sig2, noise_type, i_epoch , forward_kwargs=None, custom_kwargs=None):\n loss_contributions = self.forward_pass(batch_data, loss_functions, sig2, noise_type, i_epoch, forward_kwargs=forward_kwargs, custom_kwargs=custom_kwargs)\n loss = self.sum_losses(loss_contributions, loss_weights)\n self.optimizer_step(optimizer, loss, clip_gradient, parameters)\n\n loss = loss.item()\n loss_contributions = [contrib.item() for contrib in loss_contributions]\n return loss, loss_contributions\n\n def batch_val(self, batch_data, loss_functions, loss_weights,sig2,noise_type, i_epoch, forward_kwargs=None, custom_kwargs=None):\n loss_contributions = self.forward_pass(batch_data, loss_functions, None, noise_type, i_epoch, forward_kwargs=forward_kwargs, custom_kwargs=custom_kwargs)\n loss = self.sum_losses(loss_contributions, loss_weights)\n\n loss = loss.item()\n loss_contributions = [contrib.item() for contrib in loss_contributions]\n return loss, loss_contributions\n\n def forward_pass(self, batch_data, loss_functions, sig2, noise_type, forward_kwargs=None, custom_kwargs=None):\n \"\"\"\n Forward pass of the model. Needs to be implemented by any subclass.\n\n Parameters\n ----------\n batch_data : OrderedDict with str keys and Tensor values\n The data of the minibatch.\n\n loss_functions : list of function\n Loss functions.\n\n Returns\n -------\n losses : list of Tensor\n Losses as scalar pyTorch tensors.\n\n \"\"\"\n raise NotImplementedError\n\n def report_batch(self, i_epoch, i_batch, train, batch_data, batch_loss):\n pass\n\n\nclass ForwardTrainer(Trainer):\n \"\"\" Trainer for likelihood-based flow training when the model is not conditional. \"\"\"\n\n def first_batch(self, batch_data):\n if self.multi_gpu:\n x, y = batch_data\n if len(x.size()) < 2:\n x = x.view(x.size(0), -1)\n x = x.to(self.device, self.dtype)\n self.model(x[: x.shape[0] // torch.cuda.device_count(), ...])\n\n def add_noise(self,dataset,noise_type,x,sig2):\n if noise_type == 'gaussian': \n noise = np.sqrt(sig2) * torch.randn(x.shape,device=self.device,requires_grad = False).to(self.device)\n \n elif noise_type == 'true_normal': \n if dataset == 'thin_spiral':\n norm = torch.norm(x,dim=1).reshape([x.shape[0],1])\n z = 3 * norm\n e_r = x / norm\n R = torch.tensor([[0,-1],[1,0]]).float()\n e_phi = +1*torch.matmul(e_r,R)\n x_norm = (e_r + z * e_phi)/3 \n scale = np.sqrt(sig2) * torch.randn([x.shape[0]])\n noise_ = scale.reshape([x.shape[0],1]) * x_norm / torch.norm(x_norm,dim=1).reshape([x.shape[0],1])\n noise = torch.matmul(noise_,R)\n elif dataset == 'circle':\n noise = x\n \n elif noise_type == 'model_nn':\n x_normal = self.model.normal_sampling(x).detach().clone().to(self.device, self.dtype) - x\n norm = torch.norm(x_normal,dim=1).reshape([x.shape[0],1])\n x_normal_norm = (x_normal / norm)\n scale = np.sqrt(sig2) * torch.randn([x_normal.shape[0]])\n noise = scale.reshape([x_normal.shape[0],1]) * x_normal_norm \n \n elif noise_type == 'R3_nn':\n noise = self.model.normal_sampling(x).detach().clone().to(self.device, self.dtype) - x\n \n return noise\n\n def forward_pass(self, batch_data, loss_functions, sig2, noise_type, i_epoch, forward_kwargs=None, custom_kwargs=None):\n if forward_kwargs is None:\n forward_kwargs = {}\n\n x = batch_data[0]\n self._check_for_nans(\"Training data\", x)\n \n if len(x.size()) < 2:\n #logger.info('x size is <2')\n x = x.view(x.size(0), -1)\n x = x.to(self.device, self.dtype)\n #logger.info('First batch coordinate %s',x[0,0,0,0])\n if self.multi_gpu:\n results = nn.parallel.data_parallel(self.model, x, module_kwargs=forward_kwargs)\n else:\n if sig2 is not None:\n noise = self.add_noise('thin_spiral',noise_type,x,sig2)\n x_tilde = x + noise\n\n else: x_tilde = x\n \n results = self.model(x_tilde, **forward_kwargs)\n if len(results) == 4:\n x_reco, log_prob, u, hidden = results\n else:\n x_reco, log_prob, u = results\n hidden = None\n #logger.info('First x_reco %s',x_reco[0,0,0,0])\n \n self._check_for_nans(\"Reconstructed data\", x_reco, fix_until=5)\n if log_prob is not None:\n self._check_for_nans(\"Log likelihood\", log_prob, fix_until=5)\n if x.size(0) >= 15:\n self.last_batch = {\n \"x\": x.detach().cpu().numpy(),\n \"x_reco\": x_reco.detach().cpu().numpy(),\n \"log_prob\": None if log_prob is None else log_prob.detach().cpu().numpy(),\n \"u\": u.detach().cpu().numpy(),\n }\n\n losses = [loss_fn(x_reco, x, log_prob, hidden=hidden) for loss_fn in loss_functions]\n self._check_for_nans(\"Loss\", *losses)\n\n return losses\n\n\nclass ConditionalForwardTrainer(Trainer):\n \"\"\" Trainer for likelihood-based flow training for conditional models. \"\"\"\n\n def add_noise(self,dataset,noise_type,x,sig2):\n if noise_type == 'gaussian': \n noise = np.sqrt(sig2) * torch.randn(x.shape,device=self.device,requires_grad = False).to(self.device)\n \n elif noise_type == 'true_normal': \n if dataset == 'thin_sprial':\n norm = torch.norm(x,dim=1).reshape([x.shape[0],1])\n z = 3 * norm\n e_r = x / norm\n R = torch.tensor([[0,-1],[1,0]]).float()\n e_phi = +1*torch.matmul(e_r,R)\n x_norm = (e_r + z * e_phi)/3 \n scale = np.sqrt(sig2) * torch.randn([x.shape[0]])\n noise_ = scale.reshape([x.shape[0],1]) * x_norm / torch.norm(x_norm,dim=1) \n noise = torch.matmul(noise_,R)\n elif dataset == 'circle':\n noise = x\n \n elif noise_type == 'model_nn':\n x_normal = self.model.normal_sampling(x).detach().clone().to(self.device, self.dtype) - x\n norm = torch.norm(x_normal,dim=1).reshape([x.shape[0],1])\n x_normal_norm = (x_normal / norm)\n scale = np.sqrt(sig2) * torch.randn([x_normal.shape[0]])\n noise = scale.reshape([x_normal.shape[0],1]) * x_normal_norm \n \n elif noise_type == 'R3_nn':\n noise = self.model.normal_sampling(x).detach().clone().to(self.device, self.dtype) - x\n \n return noise\n\n def forward_pass(self, batch_data, loss_functions,sig2,noise_type, i_epoch, forward_kwargs=None, custom_kwargs=None):\n if forward_kwargs is None:\n forward_kwargs = {}\n\n x = batch_data[0]\n params = batch_data[1]\n\n if len(x.size()) < 2:\n x = x.view(x.size(0), -1)\n if len(params.size()) < 2:\n params = params.view(params.size(0), -1)\n\n x = x.to(self.device, self.dtype)\n params = params.to(self.device, self.dtype)\n self._check_for_nans(\"Training data\", x, params)\n\n if self.multi_gpu:\n forward_kwargs[\"context\"] = params\n results = nn.parallel.data_parallel(self.model, x, module_kwargs=forward_kwargs)\n else:\n if sig2 is not None:\n noise = self.add_noise('thin_spiral',noise_type,x,sig2)\n x_tilde = x + noise\n else: x_tilde = x\n \n results = self.model(x, context=params, **forward_kwargs)\n\n if len(results) == 4:\n x_reco, log_prob, u, hidden = results\n else:\n x_reco, log_prob, u = results\n hidden = None\n\n self._check_for_nans(\"Reconstructed data\", x_reco)\n if log_prob is not None:\n self._check_for_nans(\"Log likelihood\", log_prob, fix_until=5)\n if x.size(0) >= 15:\n self.last_batch = {\n \"x\": x.detach().cpu().numpy(),\n \"params\": params.detach().cpu().numpy(),\n \"x_reco\": x_reco.detach().cpu().numpy(),\n \"log_prob\": None if log_prob is None else log_prob.detach().cpu().numpy(),\n \"u\": u.detach().cpu().numpy(),\n }\n\n losses = [loss_fn(x_reco, x, log_prob, hidden=hidden) for loss_fn in loss_functions]\n self._check_for_nans(\"Loss\", *losses)\n\n return losses\n\n\nclass SCANDALForwardTrainer(Trainer):\n \"\"\" Trainer for likelihood-based flow training for conditional models with SCANDAL-like loss. \"\"\"\n\n def forward_pass(self, batch_data, loss_functions, forward_kwargs=None, custom_kwargs=None):\n if forward_kwargs is None:\n forward_kwargs = {}\n\n x, params, t_xz = batch_data\n\n if len(x.size()) < 2:\n x = x.view(x.size(0), -1)\n if len(params.size()) < 2:\n params = params.view(params.size(0), -1)\n\n x = x.to(self.device, self.dtype)\n params = params.to(self.device, self.dtype)\n t_xz = t_xz.to(self.device, self.dtype)\n self._check_for_nans(\"Training data\", x, params, t_xz)\n\n if not params.requires_grad:\n params.requires_grad = True\n\n if self.multi_gpu:\n x_reco, log_prob, _ = nn.parallel.data_parallel(self.model, x, module_kwargs={\"context\": params})\n else:\n x_reco, log_prob, _ = self.model(x, context=params, **forward_kwargs)\n\n (t,) = grad(log_prob, params, grad_outputs=torch.ones_like(log_prob.data), only_inputs=True, create_graph=True)\n\n self._check_for_nans(\"Reconstructed data\", x_reco)\n if log_prob is not None:\n self._check_for_nans(\"Log likelihood\", log_prob, fix_until=5)\n\n losses = [loss_fn(x_reco, x, log_prob, t, t_xz) for loss_fn in loss_functions]\n self._check_for_nans(\"Loss\", *losses)\n\n return losses\n\n\nclass AdversarialTrainer(Trainer):\n \"\"\" Trainer for adversarial (OT) flow training when the model is not conditional. \"\"\"\n\n # TODO: multi-GPU support\n def forward_pass(self, batch_data, loss_functions, forward_kwargs=None, custom_kwargs=None):\n if forward_kwargs is None:\n forward_kwargs = {}\n\n x = batch_data[0]\n batch_size = x.size(0)\n\n if len(x.size()) < 2:\n x = x.view(batch_size, -1)\n x = x.to(self.device, self.dtype)\n self._check_for_nans(\"Training data\", x)\n\n x_gen = self.model.sample(n=batch_size, **forward_kwargs)\n self._check_for_nans(\"Generated data\", x_gen)\n\n losses = [loss_fn(x_gen, x, None) for loss_fn in loss_functions]\n self._check_for_nans(\"Loss\", *losses)\n\n return losses\n\n\nclass ConditionalAdversarialTrainer(AdversarialTrainer):\n \"\"\" Trainer for adversarial (OT) flow training and conditional models. \"\"\"\n\n # TODO: multi-GPU support\n def forward_pass(self, batch_data, loss_functions, forward_kwargs=None, custom_kwargs=None):\n if forward_kwargs is None:\n forward_kwargs = {}\n\n x = batch_data[0]\n params = batch_data[1]\n batch_size = x.size(0)\n\n if len(x.size()) < 2:\n x = x.view(batch_size, -1)\n if len(params.size()) < 2:\n params = params.view(batch_size, -1)\n self._check_for_nans(\"Training data\", x, params)\n\n x = x.to(self.device, self.dtype)\n params = params.to(self.device, self.dtype)\n\n x_gen = self.model.sample(n=batch_size, context=params, **forward_kwargs)\n self._check_for_nans(\"Generated data\", x_gen)\n\n losses = [loss_fn(x_gen, x, None) for loss_fn in loss_functions]\n self._check_for_nans(\"Loss\", *losses)\n\n return losses\n\n\n# class VarDimForwardTrainer(ForwardTrainer):\n# \"\"\" Trainer for likelihood-based flow training for PIE with variable epsilons and non-conditional models. \"\"\"\n#\n# def train(\n# self,\n# dataset,\n# loss_functions,\n# loss_weights=None,\n# loss_labels=None,\n# epochs=50,\n# batch_size=100,\n# optimizer=optim.Adam,\n# optimizer_kwargs=None,\n# initial_lr=1.0e-3,\n# scheduler=optim.lr_scheduler.CosineAnnealingLR,\n# scheduler_kwargs=None,\n# restart_scheduler=None,\n# validation_split=0.25,\n# early_stopping=True,\n# early_stopping_patience=None,\n# clip_gradient=1.0,\n# verbose=\"some\",\n# parameters=None,\n# callbacks=None,\n# forward_kwargs=None,\n# custom_kwargs=None,\n# compute_loss_variance=False,\n# l1=0.0,\n# l2=0.0,\n# ):\n# # Prepare inputs\n# if custom_kwargs is None:\n# custom_kwargs = dict()\n# if l1 is not None:\n# custom_kwargs[\"l1\"] = l1\n# if l2 is not None:\n# custom_kwargs[\"l2\"] = l2\n#\n# n_losses = len(loss_functions) + 1\n# if loss_labels is None:\n# loss_labels = [fn.__name__ for fn in loss_functions]\n# loss_labels.append(\"Regularizer\")\n# loss_weights = [1.0] * n_losses if loss_weights is None else loss_weights + [1.0]\n#\n# return super().train(\n# dataset,\n# loss_functions,\n# loss_weights,\n# loss_labels,\n# epochs,\n# batch_size,\n# optimizer,\n# optimizer_kwargs,\n# initial_lr,\n# scheduler,\n# scheduler_kwargs,\n# restart_scheduler,\n# validation_split,\n# early_stopping,\n# early_stopping_patience,\n# clip_gradient,\n# verbose,\n# parameters,\n# callbacks,\n# forward_kwargs,\n# custom_kwargs,\n# compute_loss_variance=compute_loss_variance,\n# )\n#\n# def forward_pass(self, batch_data, loss_functions, forward_kwargs=None, custom_kwargs=None):\n# losses = super().forward_pass(batch_data, loss_functions, forward_kwargs)\n#\n# if custom_kwargs is not None:\n# l1 = custom_kwargs.get(\"l1\", 0.0)\n# l2 = custom_kwargs.get(\"l2\", 0.0)\n# reg = self.model.latent_regularizer(l1, l2)\n# losses.append(reg)\n#\n# return losses\n#\n# def report_epoch(self, i_epoch, loss_labels, loss_train, loss_val, loss_contributions_train, loss_contributions_val, verbose=False):\n# logging_fn = logger.info if verbose else logger.debug\n# super().report_epoch(i_epoch, loss_labels, loss_train, loss_val, loss_contributions_train, loss_contributions_val, verbose)\n#\n# logging_fn(\" latent dim {:>8d}\".format(self.model.calculate_latent_dim()))\n# logger.debug(\" stds {}\".format(self.model.latent_stds().detach().numpy()))\n#\n#\n# class ConditionalVarDimForwardTrainer(ConditionalForwardTrainer):\n# \"\"\" Trainer for likelihood-based flow training for PIE with variable epsilons and conditional models. \"\"\"\n#\n# def train(\n# self,\n# dataset,\n# loss_functions,\n# loss_weights=None,\n# loss_labels=None,\n# epochs=50,\n# batch_size=100,\n# optimizer=optim.Adam,\n# optimizer_kwargs=None,\n# initial_lr=1.0e-3,\n# scheduler=optim.lr_scheduler.CosineAnnealingLR,\n# scheduler_kwargs=None,\n# restart_scheduler=None,\n# validation_split=0.25,\n# early_stopping=True,\n# early_stopping_patience=None,\n# clip_gradient=1.0,\n# verbose=\"some\",\n# parameters=None,\n# callbacks=None,\n# forward_kwargs=None,\n# custom_kwargs=None,\n# compute_loss_variance=False,\n# l1=0.0,\n# l2=0.0,\n# ):\n# # Prepare inputs\n# if custom_kwargs is None:\n# custom_kwargs = dict()\n# if l1 is not None:\n# custom_kwargs[\"l1\"] = l1\n# if l2 is not None:\n# custom_kwargs[\"l2\"] = l2\n#\n# n_losses = len(loss_functions) + 1\n# if loss_labels is None:\n# loss_labels = [fn.__name__ for fn in loss_functions]\n# loss_labels.append(\"Regularizer\")\n# loss_weights = [1.0] * n_losses if loss_weights is None else loss_weights + [1.0]\n#\n# return super().train(\n# dataset,\n# loss_functions,\n# loss_weights,\n# loss_labels,\n# epochs,\n# batch_size,\n# optimizer,\n# optimizer_kwargs,\n# initial_lr,\n# scheduler,\n# scheduler_kwargs,\n# restart_scheduler,\n# validation_split,\n# early_stopping,\n# early_stopping_patience,\n# clip_gradient,\n# verbose,\n# parameters,\n# callbacks,\n# forward_kwargs,\n# custom_kwargs,\n# compute_loss_variance=compute_loss_variance,\n# )\n#\n# def forward_pass(self, batch_data, loss_functions, forward_kwargs=None, custom_kwargs=None):\n# losses = super().forward_pass(batch_data, loss_functions, forward_kwargs)\n#\n# if custom_kwargs is not None:\n# l1 = custom_kwargs.get(\"l1\", 0.0)\n# l2 = custom_kwargs.get(\"l2\", 0.0)\n# reg = self.model.latent_regularizer(l1, l2)\n# losses.append(reg)\n#\n# return losses\n#\n# def report_epoch(self, i_epoch, loss_labels, loss_train, loss_val, loss_contributions_train, loss_contributions_val, verbose=False):\n# logging_fn = logger.info if verbose else logger.debug\n# super().report_epoch(i_epoch, loss_labels, loss_train, loss_val, loss_contributions_train, loss_contributions_val, verbose)\n#\n# logging_fn(\" latent dim {:>8d}\".format(self.model.calculate_latent_dim()))\n# logger.debug(\" stds {}\".format(self.model.latent_stds().detach().numpy()))\n" ]
[ [ "torch.set_default_tensor_type", "numpy.sqrt", "torch.utils.data.DataLoader", "numpy.mean", "torch.cuda.is_available", "torch.device", "torch.norm", "torch.randn", "torch.tensor", "numpy.std", "numpy.zeros", "torch.ones_like", "torch.utils.data.sampler.SubsetRandomSampler", "numpy.floor", "torch.cuda.device_count", "numpy.array", "numpy.random.seed", "torch.nn.parallel.data_parallel", "torch.isnan", "torch.manual_seed", "numpy.random.shuffle", "torch.nn.utils.clip_grad_norm_", "torch.matmul" ] ]
Julia2505/image-segmentation-keras
[ "8c474da49e36cb8c18f1b5fe657ea5c7db83d4b8" ]
[ "keras_segmentation/models/mobilenet.py" ]
[ "import tensorflow.keras.backend as K\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.utils import get_file\n\nfrom .config import IMAGE_ORDERING\n\nBASE_WEIGHT_PATH = ('https://github.com/fchollet/deep-learning-models/'\n 'releases/download/v0.6/')\n\n\ndef relu6(x):\n return K.relu(x, max_value=6)\n\n\ndef _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):\n\n channel_axis = 1 if IMAGE_ORDERING == 'channels_first' else -1\n filters = int(filters * alpha)\n x = ZeroPadding2D(padding=(1, 1), name='conv1_pad',\n data_format=IMAGE_ORDERING)(inputs)\n x = Conv2D(filters, kernel, data_format=IMAGE_ORDERING,\n padding='valid',\n use_bias=False,\n strides=strides,\n name='conv1')(x)\n x = BatchNormalization(axis=channel_axis, name='conv1_bn')(x)\n return Activation(relu6, name='conv1_relu')(x)\n\n\ndef _depthwise_conv_block(inputs, pointwise_conv_filters, alpha,\n depth_multiplier=1, strides=(1, 1), block_id=1):\n\n channel_axis = 1 if IMAGE_ORDERING == 'channels_first' else -1\n pointwise_conv_filters = int(pointwise_conv_filters * alpha)\n\n x = ZeroPadding2D((1, 1), data_format=IMAGE_ORDERING,\n name='conv_pad_%d' % block_id)(inputs)\n x = DepthwiseConv2D((3, 3), data_format=IMAGE_ORDERING,\n padding='valid',\n depth_multiplier=depth_multiplier,\n strides=strides,\n use_bias=False,\n name='conv_dw_%d' % block_id)(x)\n x = BatchNormalization(\n axis=channel_axis, name='conv_dw_%d_bn' % block_id)(x)\n x = Activation(relu6, name='conv_dw_%d_relu' % block_id)(x)\n\n x = Conv2D(pointwise_conv_filters, (1, 1), data_format=IMAGE_ORDERING,\n padding='same',\n use_bias=False,\n strides=(1, 1),\n name='conv_pw_%d' % block_id)(x)\n x = BatchNormalization(axis=channel_axis,\n name='conv_pw_%d_bn' % block_id)(x)\n return Activation(relu6, name='conv_pw_%d_relu' % block_id)(x)\n\n\ndef get_mobilenet_encoder(input_height=224, input_width=224,\n pretrained='imagenet', channels=3):\n\n # todo add more alpha and stuff\n\n assert (K.image_data_format() ==\n 'channels_last'), \"Currently only channels last mode is supported\"\n assert (IMAGE_ORDERING ==\n 'channels_last'), \"Currently only channels last mode is supported\"\n assert (input_height == 224), \\\n \"For mobilenet , 224 input_height is supported \"\n assert (input_width == 224), \"For mobilenet , 224 width is supported \"\n\n assert input_height % 32 == 0\n assert input_width % 32 == 0\n\n alpha = 1.0\n depth_multiplier = 1\n dropout = 1e-3\n\n img_input = Input(shape=(input_height, input_width, channels))\n\n x = _conv_block(img_input, 32, alpha, strides=(2, 2))\n x = _depthwise_conv_block(x, 64, alpha, depth_multiplier, block_id=1)\n f1 = x\n\n x = _depthwise_conv_block(x, 128, alpha, depth_multiplier,\n strides=(2, 2), block_id=2)\n x = _depthwise_conv_block(x, 128, alpha, depth_multiplier, block_id=3)\n f2 = x\n\n x = _depthwise_conv_block(x, 256, alpha, depth_multiplier,\n strides=(2, 2), block_id=4)\n x = _depthwise_conv_block(x, 256, alpha, depth_multiplier, block_id=5)\n f3 = x\n\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier,\n strides=(2, 2), block_id=6)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=7)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=8)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=9)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=10)\n x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=11)\n f4 = x\n\n x = _depthwise_conv_block(x, 1024, alpha, depth_multiplier,\n strides=(2, 2), block_id=12)\n x = _depthwise_conv_block(x, 1024, alpha, depth_multiplier, block_id=13)\n f5 = x\n\n if pretrained == 'imagenet':\n model_name = 'mobilenet_%s_%d_tf_no_top.h5' % ('1_0', 224)\n\n weight_path = BASE_WEIGHT_PATH + model_name\n weights_path = get_file(model_name, weight_path)\n\n Model(img_input, x).load_weights(weights_path, by_name=True, skip_mismatch=True)\n\n return img_input, [f1, f2, f3, f4, f5]\n" ]
[ [ "tensorflow.keras.utils.get_file", "tensorflow.keras.backend.relu", "tensorflow.keras.backend.image_data_format" ] ]
benellis3/REFIL
[ "fe3d6ea5a6eb307128cf8a47ddc6e59cb126a52a" ]
[ "src/controllers/basic_controller.py" ]
[ "from modules.agents import REGISTRY as agent_REGISTRY\nfrom components.action_selectors import REGISTRY as action_REGISTRY\nimport torch as th\n\n\n# This multi-agent controller shares parameters between agents\nclass BasicMAC:\n def __init__(self, scheme, groups, args):\n self.n_agents = args.n_agents\n self.args = args\n input_shape = self._get_input_shape(scheme)\n self._build_agents(input_shape)\n self.agent_output_type = args.agent_output_type\n\n self.action_selector = action_REGISTRY[args.action_selector](args)\n\n self.hidden_states = None\n\n def select_actions(self, ep_batch, t_ep, t_env, bs=slice(None), test_mode=False, ret_agent_outs=False):\n # Only select actions for the selected batch elements in bs\n avail_actions = ep_batch[\"avail_actions\"][:, t_ep]\n agent_outputs = self.forward(ep_batch, t_ep, test_mode=test_mode)\n chosen_actions = self.action_selector.select_action(agent_outputs[bs], avail_actions[bs], t_env, test_mode=test_mode)\n if ret_agent_outs:\n return chosen_actions, agent_outputs[bs]\n return chosen_actions\n\n def forward(self, ep_batch, t, test_mode=False, **kwargs):\n if t is None:\n t = slice(0, ep_batch[\"avail_actions\"].shape[1])\n int_t = False\n elif type(t) is int:\n t = slice(t, t + 1)\n int_t = True\n\n agent_inputs = self._build_inputs(ep_batch, t)\n avail_actions = ep_batch[\"avail_actions\"][:, t]\n if kwargs.get('imagine', False):\n agent_outs, self.hidden_states, groups = self.agent(agent_inputs, self.hidden_states, **kwargs)\n else:\n agent_outs, self.hidden_states = self.agent(agent_inputs, self.hidden_states)\n\n if self.agent_output_type == \"pi_logits\":\n\n if getattr(self.args, \"mask_before_softmax\", True):\n # Make the logits for unavailable actions very negative to minimise their affect on the softmax\n agent_outs[avail_actions == 0] = -1e10\n\n agent_outs = th.nn.functional.softmax(agent_outs, dim=-1)\n if not test_mode:\n # Epsilon floor\n epsilon_action_num = agent_outs.size(-1)\n if getattr(self.args, \"mask_before_softmax\", True):\n # With probability epsilon, we will pick an available action uniformly\n epsilon_action_num = avail_actions.sum(dim=-1, keepdim=True).float()\n\n agent_outs = ((1 - self.action_selector.epsilon) * agent_outs\n + th.ones_like(agent_outs) * self.action_selector.epsilon/epsilon_action_num)\n\n if getattr(self.args, \"mask_before_softmax\", True):\n # Zero out the unavailable actions\n agent_outs[avail_actions == 0] = 0.0\n if int_t:\n return agent_outs.squeeze(1)\n if kwargs.get('imagine', False):\n return agent_outs, groups\n return agent_outs\n\n def init_hidden(self, batch_size):\n self.hidden_states = self.agent.init_hidden().unsqueeze(0).expand(batch_size, self.n_agents, -1) # bav\n\n def parameters(self):\n return self.agent.parameters()\n\n def load_state(self, other_mac):\n self.agent.load_state_dict(other_mac.agent.state_dict())\n\n def cuda(self):\n self.agent.cuda()\n\n def eval(self):\n self.agent.eval()\n\n def train(self):\n self.agent.train()\n\n def save_models(self, path):\n th.save(self.agent.state_dict(), \"{}/agent.th\".format(path))\n\n def load_models(self, path):\n self.agent.load_state_dict(th.load(\"{}/agent.th\".format(path), map_location=lambda storage, loc: storage))\n\n def _build_agents(self, input_shape):\n self.agent = agent_REGISTRY[self.args.agent](input_shape, self.args)\n\n def _build_inputs(self, batch, t):\n # Assumes homogenous agents with flat observations.\n # Other MACs might want to e.g. delegate building inputs to each agent\n bs, ts, na, os = batch[\"obs\"].shape\n inputs = []\n inputs.append(batch[\"obs\"][:, t]) # btav\n if self.args.obs_last_action:\n if t.start == 0:\n acs = th.zeros_like(batch[\"actions_onehot\"][:, t])\n acs[:, 1:] = batch[\"actions_onehot\"][:, slice(0, t.stop - 1)]\n else:\n acs = batch[\"actions_onehot\"][:, slice(t.start - 1, t.stop - 1)]\n inputs.append(acs)\n if self.args.obs_agent_id:\n inputs.append(th.eye(self.n_agents, device=batch.device).view(1, 1, self.n_agents, self.n_agents).expand(bs, t.stop - t.start, -1, -1))\n inputs = th.cat(inputs, dim=3)\n return inputs\n\n def _get_input_shape(self, scheme):\n input_shape = scheme[\"obs\"][\"vshape\"]\n if self.args.obs_last_action:\n input_shape += scheme[\"actions_onehot\"][\"vshape\"][0]\n if self.args.obs_agent_id:\n input_shape += self.n_agents\n\n return input_shape\n" ]
[ [ "torch.nn.functional.softmax", "torch.cat", "torch.eye", "torch.zeros_like", "torch.ones_like" ] ]
chaddy1004/pytorch-lightning
[ "c93b92deb8443bfa80614e498380d2a58b35aa0e" ]
[ "tests/accelerators/test_accelerator_connector.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License\n\nimport os\nfrom typing import Optional\nfrom unittest import mock\n\nimport pytest\nimport torch\nimport torch.distributed\n\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.accelerators.accelerator import Accelerator\nfrom pytorch_lightning.accelerators.cpu import CPUAccelerator\nfrom pytorch_lightning.accelerators.gpu import GPUAccelerator\nfrom pytorch_lightning.plugins import PrecisionPlugin\nfrom pytorch_lightning.plugins.environments import (\n KubeflowEnvironment,\n LightningEnvironment,\n SLURMEnvironment,\n TorchElasticEnvironment,\n)\nfrom pytorch_lightning.strategies import (\n DataParallelStrategy,\n DDP2Strategy,\n DDPShardedStrategy,\n DDPSpawnShardedStrategy,\n DDPSpawnStrategy,\n DDPStrategy,\n DeepSpeedStrategy,\n ParallelStrategy,\n SingleDeviceStrategy,\n)\nfrom pytorch_lightning.utilities import _AcceleratorType\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom tests.helpers.runif import RunIf\n\n\ndef test_accelerator_choice_cpu(tmpdir):\n trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, SingleDeviceStrategy)\n\n\n@pytest.mark.parametrize((\"num_processes\", \"num_nodes\"), ([(1, 1), (1, 2), (2, 1), (2, 2)]))\ndef test_accelerator_choice_ddp_cpu(tmpdir, num_processes: int, num_nodes: int):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", num_processes=num_processes, num_nodes=num_nodes)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n no_spawn = num_processes == 1 and num_nodes > 1\n assert isinstance(trainer.strategy, DDPStrategy if no_spawn else DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@mock.patch.dict(os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp(cuda_available_mock, device_count_mock):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@mock.patch.dict(os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_spawn(cuda_available_mock, device_count_mock):\n with pytest.deprecated_call(match=r\"accelerator='ddp_spawn'\\)` has been deprecated\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_spawn\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_slurm(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp2_slurm(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp2'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp2\", gpus=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=1)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_te(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=1)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp2_te(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp2'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp2\", gpus=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ, {\"WORLD_SIZE\": \"2\", \"LOCAL_WORLD_SIZE\": \"2\", \"RANK\": \"1\", \"LOCAL_RANK\": \"1\", \"GROUP_RANK\": \"0\"}\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_accelerator_choice_ddp_cpu_te(*_):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0\",\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=1)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_accelerator_choice_ddp_kubeflow(*_):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated in v1.5\"):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_accelerator_choice_ddp_cpu_kubeflow(*_):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", num_processes=1)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_accelerator_choice_ddp_cpu_slurm(*_):\n trainer = Trainer(fast_dev_run=True, accelerator=\"ddp_cpu\", num_processes=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.local_rank == 0\n\n\n@RunIf(skip_windows=True, standalone=True)\ndef test_accelerator_choice_ddp_cpu_and_strategy(tmpdir):\n \"\"\"Test that accelerator=\"ddp_cpu\" can work together with an instance of DDPStrategy.\"\"\"\n _test_accelerator_choice_ddp_cpu_and_strategy(tmpdir, ddp_strategy_class=DDPStrategy)\n\n\n@RunIf(skip_windows=True, skip_49370=True)\ndef test_accelerator_choice_ddp_cpu_and_strategy_spawn(tmpdir):\n \"\"\"Test that accelerator=\"ddp_cpu\" can work together with an instance of DDPPSpawnPlugin.\"\"\"\n _test_accelerator_choice_ddp_cpu_and_strategy(tmpdir, ddp_strategy_class=DDPSpawnStrategy)\n\n\ndef _test_accelerator_choice_ddp_cpu_and_strategy(tmpdir, ddp_strategy_class):\n trainer = Trainer(\n default_root_dir=tmpdir,\n strategy=ddp_strategy_class(find_unused_parameters=True),\n fast_dev_run=True,\n accelerator=\"ddp_cpu\",\n num_processes=2,\n )\n assert isinstance(trainer.strategy, ddp_strategy_class)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert trainer.strategy.num_processes == 2\n assert trainer.strategy.parallel_devices == [torch.device(\"cpu\")] * 2\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\ndef test_accelerator_choice_ddp_cpu_custom_cluster(_, tmpdir):\n \"\"\"Test that we choose the custom cluster even when SLURM or TE flags are around.\"\"\"\n\n class CustomCluster(LightningEnvironment):\n @property\n def main_address(self):\n return \"asdf\"\n\n @property\n def creates_processes_externally(self) -> bool:\n return True\n\n trainer = Trainer(\n default_root_dir=tmpdir, plugins=[CustomCluster()], fast_dev_run=True, accelerator=\"ddp_cpu\", num_processes=2\n )\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, CustomCluster)\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_custom_accelerator(device_count_mock, setup_distributed_mock):\n class Accel(Accelerator):\n @staticmethod\n def auto_device_count() -> int:\n return 1\n\n @staticmethod\n def is_available() -> bool:\n return True\n\n class Prec(PrecisionPlugin):\n pass\n\n class Strat(SingleDeviceStrategy):\n pass\n\n strategy = Strat(device=torch.device(\"cpu\"), accelerator=Accel(), precision_plugin=Prec())\n trainer = Trainer(strategy=strategy, fast_dev_run=True, num_processes=2)\n assert isinstance(trainer.accelerator, Accel)\n assert isinstance(trainer.strategy, Strat)\n assert isinstance(trainer.precision_plugin, Prec)\n assert trainer._accelerator_connector.strategy is strategy\n\n class Strat(DDPStrategy):\n pass\n\n strategy = Strat(accelerator=Accel(), precision_plugin=Prec())\n trainer = Trainer(strategy=strategy, fast_dev_run=True, num_processes=2)\n assert isinstance(trainer.accelerator, Accel)\n assert isinstance(trainer.strategy, Strat)\n assert isinstance(trainer.precision_plugin, Prec)\n assert trainer._accelerator_connector.strategy is strategy\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_dist_backend_accelerator_mapping(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert trainer.strategy.local_rank == 0\n\n\n@mock.patch(\"pytorch_lightning.utilities._IS_INTERACTIVE\", return_value=True)\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\ndef test_ipython_incompatible_backend_error(*_):\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp'\\)`.*is not compatible\"):\n Trainer(strategy=\"ddp\", gpus=2)\n\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp2'\\)`.*is not compatible\"):\n Trainer(strategy=\"ddp2\", gpus=2)\n\n\n@mock.patch(\"pytorch_lightning.utilities._IS_INTERACTIVE\", return_value=True)\ndef test_ipython_compatible_backend(*_):\n Trainer(strategy=\"ddp_spawn\", num_processes=2)\n\n\n@pytest.mark.parametrize([\"accelerator\", \"plugin\"], [(\"ddp_spawn\", \"ddp_sharded\"), (None, \"ddp_sharded\")])\ndef test_plugin_accelerator_choice(accelerator: Optional[str], plugin: str):\n \"\"\"Ensure that when a plugin and accelerator is passed in, that the plugin takes precedent.\"\"\"\n if accelerator is None:\n with pytest.deprecated_call(match=\"Passing .* `strategy` to the `plugins`\"):\n trainer = Trainer(accelerator=accelerator, plugins=plugin, num_processes=2)\n else:\n with pytest.deprecated_call(match=r\"accelerator=.*\\)` has been deprecated\"):\n trainer = Trainer(accelerator=accelerator, plugins=plugin, num_processes=2)\n assert isinstance(trainer.strategy, DDPShardedStrategy)\n\n with pytest.deprecated_call(match=\"Passing .* `strategy` to the `plugins`\"):\n trainer = Trainer(plugins=plugin, num_processes=2)\n assert isinstance(trainer.strategy, DDPShardedStrategy)\n\n\n@pytest.mark.parametrize(\n [\"accelerator\", \"plugin\"],\n [\n (\"ddp\", DDPStrategy),\n (\"ddp_spawn\", DDPSpawnStrategy),\n (\"ddp_sharded\", DDPShardedStrategy),\n (\"ddp_sharded_spawn\", DDPSpawnShardedStrategy),\n pytest.param(\"deepspeed\", DeepSpeedStrategy, marks=RunIf(deepspeed=True)),\n ],\n)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@pytest.mark.parametrize(\"gpus\", [1, 2])\ndef test_accelerator_choice_multi_node_gpu(\n mock_is_available, mock_device_count, tmpdir, accelerator: str, plugin: ParallelStrategy, gpus: int\n):\n with pytest.deprecated_call(match=r\"accelerator=.*\\)` has been deprecated\"):\n trainer = Trainer(accelerator=accelerator, default_root_dir=tmpdir, num_nodes=2, gpus=gpus)\n assert isinstance(trainer.strategy, plugin)\n\n\n@mock.patch(\"torch.cuda.is_available\", return_value=False)\ndef test_accelerator_cpu(_):\n\n trainer = Trainer(accelerator=\"cpu\")\n\n assert trainer._device_type == \"cpu\"\n assert isinstance(trainer.accelerator, CPUAccelerator)\n\n with pytest.raises(MisconfigurationException, match=\"You requested gpu:\"):\n trainer = Trainer(gpus=1)\n # TODO enable this test when add device availability check\n # with pytest.raises(MisconfigurationException, match=\"You requested gpu, but gpu is not available\"):\n # trainer = Trainer(accelerator=\"gpu\")\n with pytest.raises(MisconfigurationException, match=\"You requested gpu:\"):\n trainer = Trainer(accelerator=\"cpu\", gpus=1)\n\n\n@RunIf(min_gpus=1)\ndef test_accelerator_gpu():\n\n trainer = Trainer(accelerator=\"gpu\", gpus=1)\n\n assert trainer._device_type == \"gpu\"\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n trainer = Trainer(accelerator=\"gpu\")\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n trainer = Trainer(accelerator=\"auto\", gpus=1)\n\n assert trainer._device_type == \"gpu\"\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n\n@RunIf(min_gpus=1)\ndef test_accelerator_cpu_with_gpus_flag():\n\n trainer = Trainer(accelerator=\"cpu\", gpus=1)\n\n assert trainer._device_type == \"cpu\"\n assert isinstance(trainer.accelerator, CPUAccelerator)\n\n\n@RunIf(min_gpus=2)\ndef test_accelerator_cpu_with_multiple_gpus():\n\n trainer = Trainer(accelerator=\"cpu\", gpus=2)\n\n assert trainer._device_type == \"cpu\"\n assert isinstance(trainer.accelerator, CPUAccelerator)\n\n\n@pytest.mark.parametrize([\"devices\", \"plugin\"], [(1, SingleDeviceStrategy), (5, DDPSpawnStrategy)])\ndef test_accelerator_cpu_with_devices(devices, plugin):\n\n trainer = Trainer(accelerator=\"cpu\", devices=devices)\n\n assert trainer.num_processes == devices\n assert isinstance(trainer.strategy, plugin)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n\n\ndef test_accelerator_cpu_with_num_processes_priority():\n \"\"\"Test for checking num_processes takes priority over devices.\"\"\"\n\n num_processes = 5\n with pytest.warns(UserWarning, match=\"The flag `devices=8` will be ignored,\"):\n trainer = Trainer(accelerator=\"cpu\", devices=8, num_processes=num_processes)\n\n assert trainer.num_processes == num_processes\n\n\n@RunIf(min_gpus=2)\n@pytest.mark.parametrize(\n [\"devices\", \"plugin\"], [(1, SingleDeviceStrategy), ([1], SingleDeviceStrategy), (2, DDPSpawnStrategy)]\n)\ndef test_accelerator_gpu_with_devices(devices, plugin):\n\n trainer = Trainer(accelerator=\"gpu\", devices=devices)\n\n assert trainer.gpus == devices\n assert isinstance(trainer.strategy, plugin)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n\n@RunIf(min_gpus=1)\ndef test_accelerator_auto_with_devices_gpu():\n\n trainer = Trainer(accelerator=\"auto\", devices=1)\n\n assert trainer._device_type == \"gpu\"\n assert trainer.gpus == 1\n\n\n@RunIf(min_gpus=1)\ndef test_accelerator_gpu_with_gpus_priority():\n \"\"\"Test for checking `gpus` flag takes priority over `devices`.\"\"\"\n\n gpus = 1\n with pytest.warns(UserWarning, match=\"The flag `devices=4` will be ignored,\"):\n trainer = Trainer(accelerator=\"gpu\", devices=4, gpus=gpus)\n\n assert trainer.gpus == gpus\n\n\ndef test_validate_accelerator_and_devices():\n\n trainer = Trainer(accelerator=\"ddp_cpu\", devices=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert trainer.num_processes == 2\n\n\ndef test_set_devices_if_none_cpu():\n\n trainer = Trainer(accelerator=\"cpu\", num_processes=3)\n assert trainer.devices == 3\n\n\n@RunIf(min_gpus=2)\ndef test_set_devices_if_none_gpu():\n\n trainer = Trainer(accelerator=\"gpu\", gpus=2)\n assert trainer.devices == 2\n\n\ndef test_devices_with_cpu_only_supports_integer():\n\n with pytest.warns(UserWarning, match=\"The flag `devices` must be an int\"):\n trainer = Trainer(accelerator=\"cpu\", devices=\"1,3\")\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert trainer.devices == 1\n\n\n@pytest.mark.parametrize(\"training_type\", [\"ddp2\", \"dp\"])\ndef test_unsupported_strategy_types_on_cpu(training_type):\n with pytest.warns(UserWarning, match=\"is not supported on CPUs, hence setting `strategy='ddp\"):\n trainer = Trainer(accelerator=training_type, num_processes=2)\n assert isinstance(trainer.strategy, DDPStrategy)\n\n\ndef test_accelerator_ddp_for_cpu(tmpdir):\n with pytest.deprecated_call(match=r\"accelerator='ddp'\\)` has been deprecated\"):\n trainer = Trainer(accelerator=\"ddp\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n\n\ndef test_exception_when_strategy_used_with_accelerator():\n with pytest.raises(MisconfigurationException, match=\"but have also passed\"), pytest.deprecated_call(\n match=r\"accelerator='ddp'\\)` has been deprecated\"\n ):\n Trainer(accelerator=\"ddp\", strategy=\"ddp_spawn\")\n\n\ndef test_exception_when_strategy_used_with_plugins():\n with pytest.raises(MisconfigurationException, match=\"only specify one strategy, but you have passed\"):\n with pytest.deprecated_call(match=r\"`strategy` to the `plugins` flag in Trainer has been deprecated\"):\n Trainer(plugins=\"ddp_find_unused_parameters_false\", strategy=\"ddp_spawn\")\n\n\ndef test_exception_invalid_strategy():\n with pytest.raises(MisconfigurationException, match=r\"strategy='ddp_cpu'\\)` is not a valid\"):\n Trainer(strategy=\"ddp_cpu\")\n with pytest.raises(MisconfigurationException, match=r\"strategy='tpu_spawn'\\)` is not a valid\"):\n Trainer(strategy=\"tpu_spawn\")\n\n\n@pytest.mark.parametrize(\n [\"strategy\", \"plugin\"],\n [\n (\"ddp_spawn\", DDPSpawnStrategy),\n (\"ddp_spawn_find_unused_parameters_false\", DDPSpawnStrategy),\n (\"ddp\", DDPStrategy),\n (\"ddp_find_unused_parameters_false\", DDPStrategy),\n ],\n)\ndef test_strategy_choice_cpu_str(tmpdir, strategy, plugin):\n trainer = Trainer(strategy=strategy, accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@pytest.mark.parametrize(\"plugin\", [DDPSpawnStrategy, DDPStrategy])\ndef test_strategy_choice_cpu_plugin(tmpdir, plugin):\n trainer = Trainer(strategy=plugin(), accelerator=\"cpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@RunIf(min_gpus=2)\n@pytest.mark.parametrize(\n [\"strategy\", \"plugin\"],\n [\n (\"ddp_spawn\", DDPSpawnStrategy),\n (\"ddp_spawn_find_unused_parameters_false\", DDPSpawnStrategy),\n (\"ddp\", DDPStrategy),\n (\"ddp_find_unused_parameters_false\", DDPStrategy),\n (\"ddp2\", DDP2Strategy),\n (\"dp\", DataParallelStrategy),\n (\"ddp_sharded\", DDPShardedStrategy),\n (\"ddp_sharded_spawn\", DDPSpawnShardedStrategy),\n pytest.param(\"deepspeed\", DeepSpeedStrategy, marks=RunIf(deepspeed=True)),\n ],\n)\ndef test_strategy_choice_gpu_str(tmpdir, strategy, plugin):\n trainer = Trainer(strategy=strategy, accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@RunIf(min_gpus=2)\n@pytest.mark.parametrize(\"plugin\", [DDPSpawnStrategy, DDPStrategy])\ndef test_strategy_choice_gpu_plugin(tmpdir, plugin):\n trainer = Trainer(strategy=plugin(), accelerator=\"gpu\", devices=2)\n assert isinstance(trainer.strategy, plugin)\n\n\n@RunIf(min_gpus=2)\n@pytest.mark.parametrize(\"plugin\", [DDPSpawnStrategy, DDPStrategy])\ndef test_device_type_when_training_plugin_gpu_passed(tmpdir, plugin):\n\n trainer = Trainer(strategy=plugin(), gpus=2)\n assert isinstance(trainer.strategy, plugin)\n assert trainer._device_type == _AcceleratorType.GPU\n assert isinstance(trainer.accelerator, GPUAccelerator)\n\n\n@pytest.mark.parametrize(\"precision\", [1, 12, \"invalid\"])\ndef test_validate_precision_type(tmpdir, precision):\n\n with pytest.raises(MisconfigurationException, match=f\"Precision {repr(precision)} is invalid\"):\n Trainer(precision=precision)\n\n\ndef test_amp_level_raises_error_with_native():\n with pytest.raises(MisconfigurationException, match=\"O2'` but it's only supported with `amp_backend='apex'`\"):\n _ = Trainer(amp_level=\"O2\", amp_backend=\"native\", precision=16)\n\n\ndef test_strategy_choice_ddp_spawn_cpu(tmpdir):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@mock.patch.dict(os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp(cuda_available_mock, device_count_mock):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@mock.patch.dict(os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0,1\"})\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp_spawn(cuda_available_mock, device_count_mock):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPSpawnStrategy)\n assert isinstance(trainer.strategy.cluster_environment, LightningEnvironment)\n\n\n@RunIf(min_gpus=2)\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@pytest.mark.parametrize(\"strategy\", [\"ddp\", DDPStrategy()])\ndef test_strategy_choice_ddp_slurm(setup_distributed_mock, strategy):\n trainer = Trainer(fast_dev_run=True, strategy=strategy, gpus=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"SLURM_PROCID\": \"1\",\n \"SLURM_LOCALID\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\n@pytest.mark.parametrize(\"strategy\", [\"ddp2\", DDP2Strategy()])\ndef test_strategy_choice_ddp2_slurm(\n set_device_mock, device_count_mock, setup_distributed_mock, is_available_mock, strategy\n):\n trainer = Trainer(fast_dev_run=True, strategy=strategy, gpus=2)\n assert trainer._accelerator_connector._is_slurm_managing_tasks()\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp_te(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp\", gpus=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0,1\",\n \"WORLD_SIZE\": \"2\",\n \"LOCAL_WORLD_SIZE\": \"2\",\n \"RANK\": \"1\",\n \"LOCAL_RANK\": \"1\",\n \"GROUP_RANK\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp2_te(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp2\", gpus=2)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDP2Strategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ, {\"WORLD_SIZE\": \"2\", \"LOCAL_WORLD_SIZE\": \"2\", \"RANK\": \"1\", \"LOCAL_RANK\": \"1\", \"GROUP_RANK\": \"0\"}\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_strategy_choice_ddp_cpu_te(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, TorchElasticEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 1\n assert trainer.strategy.local_rank == 1\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"CUDA_VISIBLE_DEVICES\": \"0\",\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.set_device\")\n@mock.patch(\"torch.cuda.device_count\", return_value=1)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\ndef test_strategy_choice_ddp_kubeflow(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp\", gpus=1)\n assert isinstance(trainer.accelerator, GPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"KUBERNETES_PORT\": \"tcp://127.0.0.1:443\",\n \"MASTER_ADDR\": \"1.2.3.4\",\n \"MASTER_PORT\": \"500\",\n \"WORLD_SIZE\": \"20\",\n \"RANK\": \"1\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\ndef test_strategy_choice_ddp_cpu_kubeflow(*_):\n trainer = Trainer(fast_dev_run=True, strategy=\"ddp_spawn\", num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, KubeflowEnvironment)\n assert trainer.strategy.cluster_environment.local_rank() == 0\n assert trainer.strategy.local_rank == 0\n\n\n@mock.patch.dict(\n os.environ,\n {\n \"SLURM_NTASKS\": \"2\",\n \"SLURM_JOB_NAME\": \"SOME_NAME\",\n \"SLURM_NODEID\": \"0\",\n \"LOCAL_RANK\": \"0\",\n \"SLURM_PROCID\": \"0\",\n \"SLURM_LOCALID\": \"0\",\n },\n)\n@mock.patch(\"torch.cuda.device_count\", return_value=0)\n@mock.patch(\"pytorch_lightning.strategies.DDPStrategy.setup_distributed\", autospec=True)\n@pytest.mark.parametrize(\"strategy\", [\"ddp\", DDPStrategy()])\ndef test_strategy_choice_ddp_cpu_slurm(device_count_mock, setup_distributed_mock, strategy):\n trainer = Trainer(fast_dev_run=True, strategy=strategy, num_processes=2)\n assert isinstance(trainer.accelerator, CPUAccelerator)\n assert isinstance(trainer.strategy, DDPStrategy)\n assert isinstance(trainer.strategy.cluster_environment, SLURMEnvironment)\n assert trainer.strategy.local_rank == 0\n\n\ndef test_unsupported_tpu_choice(monkeypatch):\n import pytorch_lightning.utilities.imports as imports\n from pytorch_lightning.trainer.connectors.accelerator_connector import AcceleratorConnector\n\n monkeypatch.setattr(imports, \"_XLA_AVAILABLE\", True)\n monkeypatch.setattr(AcceleratorConnector, \"has_tpu\", True)\n with pytest.raises(MisconfigurationException, match=r\"accelerator='tpu', precision=64\\)` is not implemented\"):\n Trainer(accelerator=\"tpu\", precision=64)\n\n # if user didn't set strategy, AcceleratorConnector will choose the TPUSingleStrategy or TPUSpawnStrategy\n with pytest.raises(ValueError, match=\"TPUAccelerator` can only be used with a `SingleTPUStrategy`\"):\n with pytest.warns(UserWarning, match=r\"accelerator='tpu', precision=16\\)` but native AMP is not supported\"):\n Trainer(accelerator=\"tpu\", precision=16, strategy=\"ddp\")\n\n with pytest.raises(ValueError, match=\"TPUAccelerator` can only be used with a `SingleTPUStrategy`\"):\n with pytest.warns(UserWarning, match=r\"accelerator='tpu', precision=16\\)` but apex AMP is not supported\"):\n Trainer(accelerator=\"tpu\", precision=16, amp_backend=\"apex\", strategy=\"single_device\")\n\n\ndef test_unsupported_ipu_choice(monkeypatch):\n import pytorch_lightning.strategies.ipu as ipu\n import pytorch_lightning.utilities.imports as imports\n from pytorch_lightning.trainer.connectors.accelerator_connector import AcceleratorConnector\n\n monkeypatch.setattr(imports, \"_IPU_AVAILABLE\", True)\n monkeypatch.setattr(ipu, \"_IPU_AVAILABLE\", True)\n monkeypatch.setattr(AcceleratorConnector, \"has_ipu\", True)\n with pytest.raises(MisconfigurationException, match=r\"accelerator='ipu', precision='bf16'\\)` is not supported\"):\n Trainer(accelerator=\"ipu\", precision=\"bf16\")\n with pytest.raises(MisconfigurationException, match=r\"accelerator='ipu', precision=64\\)` is not supported\"):\n Trainer(accelerator=\"ipu\", precision=64)\n\n\n@mock.patch(\"torch.cuda.is_available\", return_value=False)\n@mock.patch(\"pytorch_lightning.utilities.imports._TPU_AVAILABLE\", return_value=False)\n@mock.patch(\"pytorch_lightning.utilities.imports._IPU_AVAILABLE\", return_value=False)\ndef test_devices_auto_choice_cpu(is_ipu_available_mock, is_tpu_available_mock, is_gpu_available_mock):\n trainer = Trainer(accelerator=\"auto\", devices=\"auto\")\n assert trainer.devices == 1\n assert trainer.num_processes == 1\n\n\n@mock.patch(\"torch.cuda.is_available\", return_value=True)\n@mock.patch(\"torch.cuda.device_count\", return_value=2)\ndef test_devices_auto_choice_gpu(is_gpu_available_mock, device_count_mock):\n trainer = Trainer(accelerator=\"auto\", devices=\"auto\")\n assert trainer.devices == 2\n assert trainer.gpus == 2\n\n\ndef test_passing_zero_and_empty_list_to_devices_flag():\n with pytest.warns(UserWarning, match=r\"switching to `cpu` accelerator\"):\n Trainer(accelerator=\"gpu\", devices=0)\n\n with pytest.warns(UserWarning, match=r\"switching to `cpu` accelerator\"):\n Trainer(accelerator=\"gpu\", devices=[])\n\n\n@pytest.mark.parametrize(\"deterministic\", [True, False])\ndef test_deterministic_init(deterministic):\n trainer = Trainer(accelerator=\"auto\", deterministic=deterministic)\n assert trainer._accelerator_connector.deterministic == deterministic\n if deterministic:\n assert os.environ.get(\"CUBLAS_WORKSPACE_CONFIG\") == \":4096:8\"\n assert os.environ.get(\"HOROVOD_FUSION_THRESHOLD\") == \"0\"\n" ]
[ [ "torch.device" ] ]
Drakeblaze10/Surf_up
[ "85137b96d12b5fdf45f62a2fa1b1ca4a08523833" ]
[ "app.py" ]
[ "#Import dependencies\nimport datetime as dt\nimport json\nimport numpy as np\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\n# Set up database\nengine = create_engine(\"sqlite:///hawaii.sqlite\")\nBase = automap_base()\nBase.prepare(engine, reflect=True)\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\nsession = Session(engine)\n\n#Set up Flask\napp = Flask(__name__)\n\n# Create flask route\n@app.route(\"/\")\ndef welcome():\n return(\n '''\n Welcome to the Climate Analysis API!\n Available Routes:\n /api/v1.0/precipitation\n /api/v1.0/stations\n /api/v1.0/tobs\n /api/v1.0/temp/start/end\n ''')\n\n@app.route('/api/v1.0/precipitation')\ndef precipitation():\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n precipitation = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= prev_year).all()\n precip = {date: prcp for date, prcp in precipitation}\n return jsonify(precip)\n\n@app.route('/api/v1.0/stations')\ndef stations():\n results = session.query(Station.station).all()\n stations = list(np.ravel(results))\n return jsonify(stations=stations)\n\n@app.route('/api/v1.0/tobs')\ndef temp_monthly():\n prev_year = dt.date(2017, 8, 23)- dt.timedelta(days=365)\n results = session.query(Measurement.tobs).\\\n filter(Measurement.station == 'USC00519281').\\\n filter(Measurement.date >= prev_year).all()\n temps = list(np.ravel(results))\n return jsonify(temps=temps)\n\n@app.route('/api/v1.0/temp/<start>')\n@app.route('/api/v1.0/temp/<start>/<end>')\ndef stats(start=None, end=None):\n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n\n if not end:\n results = session.query(*sel).\\\n filter(Measurement.date >= start).all()\n temps = list(np.ravel(results))\n return jsonify(temps=temps)\n\n results = session.query(*sel).\\\n filter(Measurement.date >= start).\\\n filter(Measurement.date <= end).all()\n temps = list(np.ravel(results))\n return jsonify(temps)\n\nif __name__ == '__main__':\n app.run(debug=True)" ]
[ [ "numpy.ravel" ] ]
Shihab-Shahriar/scikit-clean
[ "1f5d4266c91ca7074f1833de78526c39d97a5648" ]
[ "skclean/utils/_utils.py" ]
[ "import os\nfrom pathlib import Path\nfrom time import ctime, perf_counter\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score, check_cv\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder\nfrom sklearn.utils import shuffle, check_random_state\n\n_intervals = (\n ('weeks', 604800), # 60 * 60 * 24 * 7\n ('days', 86400), # 60 * 60 * 24\n ('hours', 3600), # 60 * 60\n ('minutes', 60),\n ('seconds', 1),\n)\n\n\n# Code taken from https://stackoverflow.com/a/24542445/4553309\ndef _display_time(seconds, granularity=4):\n if seconds < 60:\n return f\"{seconds:.2f} seconds\"\n\n result = []\n\n for name, count in _intervals:\n value = seconds // count\n if value:\n seconds -= value * count\n if value == 1:\n name = name.rstrip('s')\n result.append(\"{} {}\".format(value, name))\n return ', '.join(result[:granularity])\n\n\nROOT_DATASET_DIR = Path(__file__).parent.parent / 'datasets'\n\n\n# TODO: Add support for downloading dataset\ndef load_data(data_name=None, data_path=None, stats=False):\n if data_name is not None:\n path = os.path.join(ROOT_DATASET_DIR, f\"{data_name}.csv\")\n else:\n path = data_path\n\n try:\n df = pd.read_csv(path, header=None)\n except FileNotFoundError as e:\n raise e\n\n df = df.astype('float64')\n data = df.values\n X, Y = data[:, :-1], data[:, -1]\n Y = LabelEncoder().fit_transform(Y)\n X = MinMaxScaler().fit_transform(X)\n if stats:\n labels, freq = np.unique(Y, return_counts=True)\n print(f\"{X.shape}, {len(labels)}, {freq.min() / freq.max():.3f}\\n\")\n return shuffle(X, Y, random_state=42)\n\n\n# TODO: Support resuming inside cross_val_score, use Dask?\ndef compare(models: dict, datasets: list, cv, df_path=None, n_jobs=-1,\n scoring='accuracy', random_state=None, verbose=True,\n fit_params=None, **kwargs):\n \"\"\"\n Compare different methods across several datasets, with support for \\\n parallelization, reproducibility and automatic resumption. Output is \\\n a csv file where each row represents a dataset and each column \\\n represents a method/ algorithm. It's basically a wrapper around \\\n `sklearn.model_selection.cross_val_score`- check this for more details.\n\n Note that support for resumption is somewhat limited, it can only \\\n recover output of (dataset, method) pair for whom computation is fully \\\n complete. In other words, if a 10-fold cross-validation is stopped \\\n after 5-fold, the results of that 5-fold is lost.\n\n\n Parameters\n --------------\n models : dict\n Keys are model name, values are scikit-learn API compatible classifiers.\n\n datasets : list\n A list of either `string`, denoting dataset names to be loaded with \\\n `load_data`, or a nested tuple of (name, (X, y)), denoting dataset \\\n name, features and labels respectively.\n\n cv : int, cross-validation generator or an iterable\n if int, no of folds to use in stratified k-fold\n\n df_path : string, default=None\n Path to (csv) file to store results- will be overwritten if already \\\n present.\n\n scoring : string, or a scorer callable object / function with signature \\\n ``scorer(estimator, X, y)`` which should return only a single value.\n\n n_jobs : int, default=1\n No of parallel cpu cores to use\n\n random_state : int, default=None\n Set this value for reproducibility. Note that this will overwrite \\\n existing random state of methods even if it's already present.\n\n verbose : Controls the verbosity level\n\n fit_params : dict, default=None\n Parameters to send to fit() method of each classifiers. Keys should be\n classifier names, same as in `models`, and values themselves are ``dict``\n of parameter-name, value pairs.\n\n kwargs : Other parameters for ``cross_val_score``.\n\n \"\"\"\n\n rns = check_random_state(random_state)\n cv = check_cv(cv)\n cv.random_state = rns.randint(100)\n seeds = iter(rns.randint(10 ** 8, size=len(models) * len(datasets)))\n\n try:\n df = pd.read_csv(df_path, index_col=0)\n if verbose:\n print(\"Result file found, resuming...\") # Word 'resuming' is used in test\n except (FileNotFoundError, ValueError):\n df = pd.DataFrame()\n\n for data in datasets:\n\n if type(data) == str:\n X, Y = load_data(data, stats=verbose)\n else:\n data, (X, Y) = data # Nested tuple of (name, (data, target))\n\n if data not in df.index:\n df.loc[data, :] = None\n\n for name, clf in models.items():\n if 'n_jobs' in clf.get_params():\n clf.set_params(n_jobs=1)\n if 'random_state' in clf.get_params():\n clf.set_params(random_state=next(seeds))\n\n if name not in df.columns:\n df[name] = None\n\n if not pd.isna(df.loc[data, name]):\n v = df.loc[data, name]\n if verbose:\n print(f\"Skipping {data},{name} :{v}\")\n continue\n elif verbose:\n print(f\"Starting: {data}, {name} at {ctime()[-14:-4]}\")\n\n fit_par = None if fit_params is None else fit_params.get(name, None)\n start = perf_counter()\n res = cross_val_score(clf, X, Y, cv=cv, n_jobs=n_jobs, scoring=scoring,\n error_score='raise', fit_params=fit_par, **kwargs)\n df.at[data, name] = res.mean()\n elapsed_time = _display_time(perf_counter() - start)\n if verbose:\n print(f\"Result: {df.loc[data, name]:.4f} in {elapsed_time} \\n\")\n if df_path:\n df.to_csv(df_path)\n if verbose:\n print()\n return df\n" ]
[ [ "pandas.read_csv", "sklearn.model_selection.cross_val_score", "numpy.unique", "sklearn.utils.shuffle", "sklearn.model_selection.check_cv", "pandas.DataFrame", "pandas.isna", "sklearn.preprocessing.LabelEncoder", "sklearn.utils.check_random_state", "sklearn.preprocessing.MinMaxScaler" ] ]
verg1lio/ross
[ "d4456f42c7906b52963341fcbed88b9c25dafd34" ]
[ "ross/bearing_seal_element.py" ]
[ "\"\"\"Bearing Element module.\n\nThis module defines the BearingElement classes which will be used to represent the rotor\nbearings and seals. There're 6 different classes to represent bearings options,\nand 2 element options with 8 or 12 degrees of freedom.\n\"\"\"\n# fmt: off\nimport os\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport plotly.graph_objects as go\nimport scipy.interpolate as interpolate\n\nfrom ross.element import Element\nfrom ross.fluid_flow import fluid_flow as flow\nfrom ross.fluid_flow.fluid_flow_coefficients import (\n calculate_damping_matrix, calculate_stiffness_matrix)\nfrom ross.units import check_units\nfrom ross.utils import read_table_file\n\n# fmt: on\n\n__all__ = [\n \"BearingElement\",\n \"SealElement\",\n \"BallBearingElement\",\n \"RollerBearingElement\",\n \"BearingElement6DoF\",\n \"MagneticBearingElement\",\n]\n\n\nclass _Coefficient:\n \"\"\"Auxiliary bearing coefficient class.\n\n This class takes bearing elements' coefficients and frequencies values and\n interpolate the arrays when necessary.\n\n Parameters\n ----------\n coefficient : int, float, array, pint.Quantity\n Bearing element stiffness or damping coefficient (direct or cross-coupled).\n If coefficient is int or float, it is considered constant along the frequency\n array. If coefficient is an array, it's interpolated with the frequency array.\n frequency: array, pint.Quantity, optional\n Array with the frequencies (rad/s).\n Frequency is optional only if coefficient is an int or a float (constant value).\n\n Returns\n -------\n The bearing element dynamic coefficient.\n Kxx, Kxy, Kyx, Kyy, Cxx, Cxy, Cyx, Cyy.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.kxx\n [1000000.0, 1000000.0...\n \"\"\"\n\n def __init__(self, coefficient, frequency=None):\n if isinstance(coefficient, (int, float)):\n if frequency is not None and type(frequency) != float:\n coefficient = [coefficient for _ in range(len(frequency))]\n else:\n coefficient = [coefficient]\n\n self.coefficient = coefficient\n self.frequency = frequency\n\n if len(self.coefficient) > 1:\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n self.interpolated = interpolate.UnivariateSpline(\n self.frequency, self.coefficient\n )\n # dfitpack.error is not exposed by scipy\n # so a bare except is used\n except:\n try:\n if len(self.frequency) in (2, 3):\n self.interpolated = interpolate.interp1d(\n self.frequency,\n self.coefficient,\n kind=len(self.frequency) - 1,\n fill_value=\"extrapolate\",\n )\n except:\n raise ValueError(\n \"Arguments (coefficients and frequency)\"\n \" must have the same dimension\"\n )\n else:\n self.interpolated = lambda x: np.array(self.coefficient[0])\n\n def __eq__(self, other):\n \"\"\"Equality method for comparasions.\n\n Parameters\n ----------\n other: object\n The second object to be compared with.\n\n Returns\n -------\n bool\n True if the comparison is true; False otherwise.\n\n Examples\n --------\n >>> bearing1 = bearing_example()\n >>> bearing2 = bearing_example()\n >>> bearing1.kxx == bearing2.kxx\n True\n \"\"\"\n if np.allclose(self.__dict__[\"coefficient\"], other.__dict__[\"coefficient\"]):\n return True\n else:\n return False\n\n def __repr__(self):\n \"\"\"Return a string representation of a bearing element.\n\n Returns\n -------\n A string representation of a bearing element object.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.cxx # doctest: +ELLIPSIS\n [200.0, 200.0, 200.0,...\n \"\"\"\n return repr(self.coefficient)\n\n def __getitem__(self, item):\n \"\"\"Return an element from the coeffcient array.\n\n This method allows the elements from the coefficient array to be returned as\n ints or floats, given an index (item).\n\n Parameters\n ----------\n item : int, slices\n Array index.\n\n Returns\n -------\n An element from the coefficient array.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.kxx[0]\n 1000000.0\n \"\"\"\n return self.coefficient[item]\n\n def plot(self, **kwargs):\n \"\"\"Plot coefficient vs frequency.\n\n Parameters\n ----------\n **kwargs : optional\n Additional key word arguments can be passed to change the plot layout only\n (e.g. width=1000, height=800, ...).\n *See Plotly Python Figure Reference for more information.\n\n Returns\n -------\n fig : Plotly graph_objects.Figure()\n The figure object with the plot.\n\n Example\n -------\n >>> bearing = bearing_example()\n >>> fig = bearing.kxx.plot()\n >>> # fig.show()\n \"\"\"\n w_range = np.linspace(min(self.frequency), max(self.frequency), 30)\n\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x=w_range,\n y=self.interpolated(w_range),\n mode=\"lines\",\n line=dict(width=3.0, color=\"royalblue\"),\n showlegend=False,\n hovertemplate=(\"Frequency: %{x:.2f}<br>\" + \"Coefficient: %{y:.3e}\"),\n )\n )\n\n fig.update_xaxes(\n title_text=\"<b>Frequency</b>\",\n title_font=dict(family=\"Arial\", size=20),\n tickfont=dict(size=16),\n gridcolor=\"lightgray\",\n showline=True,\n linewidth=2.5,\n linecolor=\"black\",\n mirror=True,\n )\n fig.update_yaxes(\n title_font=dict(family=\"Arial\", size=20),\n tickfont=dict(size=16),\n gridcolor=\"lightgray\",\n showline=True,\n linewidth=2.5,\n linecolor=\"black\",\n mirror=True,\n exponentformat=\"power\",\n )\n fig.update_layout(\n width=800,\n height=600,\n plot_bgcolor=\"white\",\n hoverlabel_align=\"right\",\n **kwargs,\n )\n\n return fig\n\n\nclass _Stiffness_Coefficient(_Coefficient):\n \"\"\"Stiffness coefficient auxiliary class.\n\n Inherits from _Coefficient class. It will adapt the plot layout to stiffness\n coefficients.\n \"\"\"\n\n def plot(self, **kwargs):\n \"\"\"Plot stiffness coefficient vs frequency.\n\n Parameters\n ----------\n **kwargs : optional\n Additional key word arguments can be passed to change the plot layout only\n (e.g. width=1000, height=800, ...).\n *See Plotly Python Figure Reference for more information.\n\n Returns\n -------\n fig : Plotly graph_objects.Figure()\n The figure object with the plot.\n\n Example\n -------\n >>> bearing = bearing_example()\n >>> fig = bearing.kxx.plot()\n >>> # fig.show()\n \"\"\"\n fig = super().plot(**kwargs)\n fig.update_yaxes(title_text=\"<b>Stiffness (N/m)</b>\")\n\n return fig\n\n\nclass _Damping_Coefficient(_Coefficient):\n \"\"\"Stiffness coefficient auxiliary class.\n\n Inherits from _Coefficient class. It will adapt the plot layout to damping\n coefficients.\n \"\"\"\n\n def plot(self, **kwargs):\n \"\"\"Plot damping coefficient vs frequency.\n\n Parameters\n ----------\n **kwargs : optional\n Additional key word arguments can be passed to change the plot layout only\n (e.g. width=1000, height=800, ...).\n *See Plotly Python Figure Reference for more information.\n\n Returns\n -------\n fig : Plotly graph_objects.Figure()\n The figure object with the plot.\n\n Example\n -------\n >>> bearing = bearing_example()\n >>> fig = bearing.cxx.plot()\n >>> # fig.show()\n \"\"\"\n fig = super().plot(**kwargs)\n fig.update_yaxes(title_text=\"<b>Damping (Ns/m)</b>\")\n\n return fig\n\n\nclass BearingElement(Element):\n \"\"\"A bearing element.\n\n This class will create a bearing element.\n Parameters can be a constant value or speed dependent.\n For speed dependent parameters, each argument should be passed\n as an array and the correspondent speed values should also be\n passed as an array.\n Values for each parameter will be interpolated for the speed.\n\n Parameters\n ----------\n n: int\n Node which the bearing will be located in\n kxx: float, array, pint.Quantity\n Direct stiffness in the x direction.\n cxx: float, array, pint.Quantity\n Direct damping in the x direction.\n kyy: float, array, pint.Quantity, optional\n Direct stiffness in the y direction.\n (defaults to kxx)\n cyy: float, array, pint.Quantity, optional\n Direct damping in the y direction.\n (defaults to cxx)\n kxy: float, array, pint.Quantity ,optional\n Cross coupled stiffness in the x direction.\n (defaults to 0)\n cxy: float, array, pint.Quantity, optional\n Cross coupled damping in the x direction.\n (defaults to 0)\n kyx: float, array, pint.Quantity, optional\n Cross coupled stiffness in the y direction.\n (defaults to 0)\n cyx: float, array, pint.Quantity, optional\n Cross coupled damping in the y direction.\n (defaults to 0)\n frequency: array, pint.Quantity, optional\n Array with the frequencies (rad/s).\n tag: str, optional\n A tag to name the element\n Default is None.\n n_link: int, optional\n Node to which the bearing will connect. If None the bearing is\n connected to ground.\n Default is None.\n scale_factor: float, optional\n The scale factor is used to scale the bearing drawing.\n Default is 1.\n color : str, optional\n A color to be used when the element is represented.\n Default is '#355d7a' (Cardinal).\n\n Examples\n --------\n >>> # A bearing element located in the first rotor node, with these\n >>> # following stiffness and damping coefficients and speed range from\n >>> # 0 to 200 rad/s\n >>> import ross as rs\n >>> kxx = 1e6\n >>> kyy = 0.8e6\n >>> cxx = 2e2\n >>> cyy = 1.5e2\n >>> frequency = np.linspace(0, 200, 11)\n >>> bearing0 = rs.BearingElement(n=0, kxx=kxx, kyy=kyy, cxx=cxx, cyy=cyy, frequency=frequency)\n >>> bearing0.K(frequency) # doctest: +ELLIPSIS\n array([[[1000000., 1000000., ...\n >>> bearing0.C(frequency) # doctest: +ELLIPSIS\n array([[[200., 200., ...\n \"\"\"\n\n @check_units\n def __init__(\n self,\n n,\n kxx,\n cxx,\n kyy=None,\n kxy=0,\n kyx=0,\n cyy=None,\n cxy=0,\n cyx=0,\n frequency=None,\n tag=None,\n n_link=None,\n scale_factor=1,\n color=\"#355d7a\",\n ):\n\n args = [\"kxx\", \"kyy\", \"kxy\", \"kyx\", \"cxx\", \"cyy\", \"cxy\", \"cyx\"]\n\n # all args to coefficients\n args_dict = locals()\n coefficients = {}\n\n if kyy is None:\n args_dict[\"kyy\"] = kxx\n if cyy is None:\n args_dict[\"cyy\"] = cxx\n\n for arg in args:\n if arg[0] == \"k\":\n coefficients[arg] = _Stiffness_Coefficient(\n coefficient=args_dict[arg], frequency=args_dict[\"frequency\"]\n )\n else:\n coefficients[arg] = _Damping_Coefficient(\n args_dict[arg], args_dict[\"frequency\"]\n )\n\n coefficients_len = [len(v.coefficient) for v in coefficients.values()]\n\n if frequency is not None and type(frequency) != float:\n coefficients_len.append(len(args_dict[\"frequency\"]))\n if len(set(coefficients_len)) > 1:\n raise ValueError(\n \"Arguments (coefficients and frequency)\"\n \" must have the same dimension\"\n )\n else:\n for c in coefficients_len:\n if c != 1:\n raise ValueError(\n \"Arguments (coefficients and frequency)\"\n \" must have the same dimension\"\n )\n\n for k, v in coefficients.items():\n setattr(self, k, v)\n\n self.n = n\n self.n_link = n_link\n self.n_l = n\n self.n_r = n\n\n self.frequency = np.array(frequency, dtype=np.float64)\n self.tag = tag\n self.color = color\n self.scale_factor = scale_factor\n self.dof_global_index = None\n\n def __repr__(self):\n \"\"\"Return a string representation of a bearing element.\n\n Returns\n -------\n A string representation of a bearing element object.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing # doctest: +ELLIPSIS\n BearingElement(n=0, n_link=None,\n kxx=[...\n \"\"\"\n return (\n f\"{self.__class__.__name__}\"\n f\"(n={self.n}, n_link={self.n_link},\\n\"\n f\" kxx={self.kxx}, kxy={self.kxy},\\n\"\n f\" kyx={self.kyx}, kyy={self.kyy},\\n\"\n f\" cxx={self.cxx}, cxy={self.cxy},\\n\"\n f\" cyx={self.cyx}, cyy={self.cyy},\\n\"\n f\" frequency={self.frequency}, tag={self.tag!r})\"\n )\n\n def __eq__(self, other):\n \"\"\"Equality method for comparasions.\n\n Parameters\n ----------\n other: object\n The second object to be compared with.\n\n Returns\n -------\n bool\n True if the comparison is true; False otherwise.\n\n Examples\n --------\n >>> bearing1 = bearing_example()\n >>> bearing2 = bearing_example()\n >>> bearing1 == bearing2\n True\n \"\"\"\n compared_attributes = [\n \"kxx\",\n \"kyy\",\n \"kxy\",\n \"kyx\",\n \"cxx\",\n \"cyy\",\n \"cxy\",\n \"cyx\",\n \"frequency\",\n \"n\",\n \"n_link\",\n ]\n if isinstance(other, self.__class__):\n return all(\n (\n np.array(getattr(self, attr)).all()\n == np.array(getattr(other, attr)).all()\n for attr in compared_attributes\n )\n )\n return False\n\n def __hash__(self):\n return hash(self.tag)\n\n def save(self, file_name=Path(os.getcwd())):\n \"\"\"Save a bearing element in a toml format.\n\n It works as an auxiliary function of the save function in the Rotor class.\n\n Parameters\n ----------\n file_name: string\n The name of the file the bearing element will be saved in.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.save(Path(os.getcwd()))\n \"\"\"\n data = self.get_data(Path(file_name) / \"BearingElement.toml\")\n\n if type(self.frequency) == np.ndarray:\n try:\n self.frequency[0]\n frequency = list(self.frequency)\n except IndexError:\n frequency = None\n\n data[\"BearingElement\"][str(self.n)] = {\n \"n\": self.n,\n \"kxx\": self.kxx.coefficient,\n \"cxx\": self.cxx.coefficient,\n \"kyy\": self.kyy.coefficient,\n \"kxy\": self.kxy.coefficient,\n \"kyx\": self.kyx.coefficient,\n \"cyy\": self.cyy.coefficient,\n \"cxy\": self.cxy.coefficient,\n \"cyx\": self.cyx.coefficient,\n \"frequency\": frequency,\n \"tag\": self.tag,\n \"n_link\": self.n_link,\n \"scale_factor\": self.scale_factor,\n }\n self.dump_data(data, Path(file_name) / \"BearingElement.toml\")\n\n @staticmethod\n def load(file_name=\"\"):\n \"\"\"Load a list of bearing elements saved in a toml format.\n\n It works as an auxiliary function of the load function in the Rotor class.\n\n Parameters\n ----------\n file_name: string\n The name of the file of the bearing element to be loaded.\n\n Returns\n -------\n A list of bearing elements.\n\n Examples\n --------\n >>> bearing1 = bearing_example()\n >>> bearing1.save(os.getcwd())\n >>> list_of_bearings = BearingElement.load(os.getcwd())\n >>> bearing1 == list_of_bearings[0]\n True\n \"\"\"\n bearing_elements = []\n bearing_elements_dict = BearingElement.get_data(\n file_name=Path(file_name) / \"BearingElement.toml\"\n )\n for element in bearing_elements_dict[\"BearingElement\"]:\n bearing = BearingElement(**bearing_elements_dict[\"BearingElement\"][element])\n bearing.kxx.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"kxx\"\n ]\n\n bearing.kxy.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"kxy\"\n ]\n\n bearing.kyx.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"kyx\"\n ]\n\n bearing.kyy.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"kyy\"\n ]\n\n bearing.cxx.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"cxx\"\n ]\n\n bearing.cxy.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"cxy\"\n ]\n\n bearing.cyx.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"cyx\"\n ]\n\n bearing.cyy.coefficient = bearing_elements_dict[\"BearingElement\"][element][\n \"cyy\"\n ]\n\n bearing_elements.append(bearing)\n return bearing_elements\n\n def dof_mapping(self):\n \"\"\"Degrees of freedom mapping.\n\n Returns a dictionary with a mapping between degree of freedom and its\n index.\n\n Returns\n -------\n dof_mapping : dict\n A dictionary containing the degrees of freedom and their indexes.\n\n Examples\n --------\n The numbering of the degrees of freedom for each node.\n\n Being the following their ordering for a node:\n\n x_0 - horizontal translation\n y_0 - vertical translation\n\n >>> bearing = bearing_example()\n >>> bearing.dof_mapping()\n {'x_0': 0, 'y_0': 1}\n \"\"\"\n return dict(x_0=0, y_0=1)\n\n def M(self):\n \"\"\"Mass matrix for an instance of a bearing element.\n\n This method returns the mass matrix for an instance of a bearing\n element.\n\n Returns\n -------\n M : np.ndarray\n Mass matrix.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.M()\n array([[0., 0.],\n [0., 0.]])\n \"\"\"\n M = np.zeros_like(self.K(0))\n\n return M\n\n def K(self, frequency):\n \"\"\"Stiffness matrix for an instance of a bearing element.\n\n This method returns the stiffness matrix for an instance of a bearing\n element.\n\n Parameters\n ----------\n frequency : float\n The excitation frequency.\n\n Returns\n -------\n K : np.ndarray\n A 2x2 matrix of floats containing the kxx, kxy, kyx, and kyy values.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.K(0)\n array([[1000000., 0.],\n [ 0., 800000.]])\n \"\"\"\n kxx = self.kxx.interpolated(frequency)\n kyy = self.kyy.interpolated(frequency)\n kxy = self.kxy.interpolated(frequency)\n kyx = self.kyx.interpolated(frequency)\n\n K = np.array([[kxx, kxy], [kyx, kyy]])\n\n if self.n_link is not None:\n # fmt: off\n K = np.vstack((np.hstack([K, -K]),\n np.hstack([-K, K])))\n # fmt: on\n\n return K\n\n def C(self, frequency):\n \"\"\"Damping matrix for an instance of a bearing element.\n\n This method returns the damping matrix for an instance of a bearing\n element.\n\n Parameters\n ----------\n frequency : float\n The excitation frequency.\n\n Returns\n -------\n C : np.ndarray\n A 2x2 matrix of floats containing the cxx, cxy, cyx, and cyy values.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.C(0)\n array([[200., 0.],\n [ 0., 150.]])\n \"\"\"\n cxx = self.cxx.interpolated(frequency)\n cyy = self.cyy.interpolated(frequency)\n cxy = self.cxy.interpolated(frequency)\n cyx = self.cyx.interpolated(frequency)\n\n C = np.array([[cxx, cxy], [cyx, cyy]])\n\n if self.n_link is not None:\n # fmt: off\n C = np.vstack((np.hstack([C, -C]),\n np.hstack([-C, C])))\n # fmt: on\n\n return C\n\n def G(self):\n \"\"\"Gyroscopic matrix for an instance of a bearing element.\n\n This method returns the mass matrix for an instance of a bearing\n element.\n\n Returns\n -------\n G : np.ndarray\n A 2x2 matrix of floats.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.G()\n array([[0., 0.],\n [0., 0.]])\n \"\"\"\n G = np.zeros_like(self.K(0))\n\n return G\n\n def _patch(self, position, fig):\n \"\"\"Bearing element patch.\n\n Patch that will be used to draw the bearing element using Plotly library.\n\n Parameters\n ----------\n position : tuple\n Position (z, y_low, y_upp) in which the patch will be drawn.\n fig : plotly.graph_objects.Figure\n The figure object which traces are added on.\n\n Returns\n -------\n fig : plotly.graph_objects.Figure\n The figure object which traces are added on.\n \"\"\"\n default_values = dict(\n mode=\"lines\",\n line=dict(width=3.5, color=self.color),\n name=self.tag,\n legendgroup=\"bearings\",\n showlegend=False,\n hoverinfo=\"none\",\n )\n\n # geometric factors\n zpos, ypos, ypos_s = position\n\n icon_h = ypos_s - ypos # bearing icon height\n icon_w = icon_h / 2.0 # bearing icon width\n coils = 6 # number of points to generate spring\n n = 5 # number of ground lines\n step = icon_w / (coils + 1) # spring step\n\n zs0 = zpos - (icon_w / 2.0)\n zs1 = zpos + (icon_w / 2.0)\n ys0 = ypos + 0.25 * icon_h\n\n # plot bottom base\n x_bot = [zpos, zpos, zs0, zs1]\n yl_bot = [ypos, ys0, ys0, ys0]\n yu_bot = [-y for y in yl_bot]\n\n fig.add_trace(go.Scatter(x=x_bot, y=yl_bot, **default_values))\n fig.add_trace(go.Scatter(x=x_bot, y=yu_bot, **default_values))\n\n # plot top base\n x_top = [zpos, zpos, zs0, zs1]\n yl_top = [\n ypos + icon_h,\n ypos + 0.75 * icon_h,\n ypos + 0.75 * icon_h,\n ypos + 0.75 * icon_h,\n ]\n yu_top = [-y for y in yl_top]\n fig.add_trace(go.Scatter(x=x_top, y=yl_top, **default_values))\n fig.add_trace(go.Scatter(x=x_top, y=yu_top, **default_values))\n\n # plot ground\n if self.n_link is None:\n zl_g = [zs0 - step, zs1 + step]\n yl_g = [yl_top[0], yl_top[0]]\n yu_g = [-y for y in yl_g]\n fig.add_trace(go.Scatter(x=zl_g, y=yl_g, **default_values))\n fig.add_trace(go.Scatter(x=zl_g, y=yu_g, **default_values))\n\n step2 = (zl_g[1] - zl_g[0]) / n\n for i in range(n + 1):\n zl_g2 = [(zs0 - step) + step2 * (i), (zs0 - step) + step2 * (i + 1)]\n yl_g2 = [yl_g[0], 1.1 * yl_g[0]]\n yu_g2 = [-y for y in yl_g2]\n fig.add_trace(go.Scatter(x=zl_g2, y=yl_g2, **default_values))\n fig.add_trace(go.Scatter(x=zl_g2, y=yu_g2, **default_values))\n\n # plot spring\n z_spring = np.array([zs0, zs0, zs0, zs0])\n yl_spring = np.array([ys0, ys0 + step, ys0 + icon_w - step, ys0 + icon_w])\n\n for i in range(coils):\n z_spring = np.insert(z_spring, i + 2, zs0 - (-1) ** i * step)\n yl_spring = np.insert(yl_spring, i + 2, ys0 + (i + 1) * step)\n yu_spring = [-y for y in yl_spring]\n\n fig.add_trace(go.Scatter(x=z_spring, y=yl_spring, **default_values))\n fig.add_trace(go.Scatter(x=z_spring, y=yu_spring, **default_values))\n\n # plot damper - base\n z_damper1 = [zs1, zs1]\n yl_damper1 = [ys0, ys0 + 2 * step]\n yu_damper1 = [-y for y in yl_damper1]\n fig.add_trace(go.Scatter(x=z_damper1, y=yl_damper1, **default_values))\n fig.add_trace(go.Scatter(x=z_damper1, y=yu_damper1, **default_values))\n\n # plot damper - center\n z_damper2 = [zs1 - 2 * step, zs1 - 2 * step, zs1 + 2 * step, zs1 + 2 * step]\n yl_damper2 = [ys0 + 5 * step, ys0 + 2 * step, ys0 + 2 * step, ys0 + 5 * step]\n yu_damper2 = [-y for y in yl_damper2]\n fig.add_trace(go.Scatter(x=z_damper2, y=yl_damper2, **default_values))\n fig.add_trace(go.Scatter(x=z_damper2, y=yu_damper2, **default_values))\n\n # plot damper - top\n z_damper3 = [z_damper2[0], z_damper2[2], zs1, zs1]\n yl_damper3 = [\n ys0 + 4 * step,\n ys0 + 4 * step,\n ys0 + 4 * step,\n ypos + 1.5 * icon_w,\n ]\n yu_damper3 = [-y for y in yl_damper3]\n\n fig.add_trace(go.Scatter(x=z_damper3, y=yl_damper3, **default_values))\n fig.add_trace(go.Scatter(x=z_damper3, y=yu_damper3, **default_values))\n\n return fig\n\n @classmethod\n def table_to_toml(cls, n, file):\n \"\"\"Convert bearing parameters to toml.\n\n Convert a table with parameters of a bearing element to a dictionary ready to\n save to a toml file that can be later loaded by ross.\n\n Parameters\n ----------\n n : int\n The node in which the bearing will be located in the rotor.\n file: str\n Path to the file containing the bearing parameters.\n\n Returns\n -------\n data: dict\n A dict that is ready to save to toml and readable by ross.\n\n Examples\n --------\n >>> import os\n >>> file_path = os.path.dirname(os.path.realpath(__file__)) + '/tests/data/bearing_seal_si.xls'\n >>> BearingElement.table_to_toml(0, file_path) # doctest: +ELLIPSIS\n {'n': 0, 'kxx': array([...\n \"\"\"\n b_elem = cls.from_table(n, file)\n data = {\n \"n\": b_elem.n,\n \"kxx\": b_elem.kxx.coefficient,\n \"cxx\": b_elem.cxx.coefficient,\n \"kyy\": b_elem.kyy.coefficient,\n \"kxy\": b_elem.kxy.coefficient,\n \"kyx\": b_elem.kyx.coefficient,\n \"cyy\": b_elem.cyy.coefficient,\n \"cxy\": b_elem.cxy.coefficient,\n \"cyx\": b_elem.cyx.coefficient,\n \"frequency\": b_elem.frequency,\n }\n return data\n\n @classmethod\n def from_table(\n cls,\n n,\n file,\n sheet_name=0,\n tag=None,\n n_link=None,\n scale_factor=1,\n color=\"#355d7a\",\n ):\n \"\"\"Instantiate a bearing using inputs from an Excel table.\n\n A header with the names of the columns is required. These names should match the\n names expected by the routine (usually the names of the parameters, but also\n similar ones). The program will read every row bellow the header\n until they end or it reaches a NaN.\n\n Parameters\n ----------\n n : int\n The node in which the bearing will be located in the rotor.\n file: str\n Path to the file containing the bearing parameters.\n sheet_name: int or str, optional\n Position of the sheet in the file (starting from 0) or its name. If none is\n passed, it is assumed to be the first sheet in the file.\n tag : str, optional\n A tag to name the element.\n Default is None.\n n_link : int, optional\n Node to which the bearing will connect. If None the bearing is connected to\n ground.\n Default is None.\n scale_factor : float, optional\n The scale factor is used to scale the bearing drawing.\n Default is 1.\n color : str, optional\n A color to be used when the element is represented.\n Default is '#355d7a' (Cardinal).\n\n Returns\n -------\n bearing: rs.BearingElement\n A bearing object.\n\n Examples\n --------\n >>> import os\n >>> file_path = os.path.dirname(os.path.realpath(__file__)) + '/tests/data/bearing_seal_si.xls'\n >>> BearingElement.from_table(0, file_path, n_link=1) # doctest: +ELLIPSIS\n BearingElement(n=0, n_link=1,\n kxx=array([...\n \"\"\"\n parameters = read_table_file(file, \"bearing\", sheet_name, n)\n return cls(\n n=parameters[\"n\"],\n kxx=parameters[\"kxx\"],\n cxx=parameters[\"cxx\"],\n kyy=parameters[\"kyy\"],\n kxy=parameters[\"kxy\"],\n kyx=parameters[\"kyx\"],\n cyy=parameters[\"cyy\"],\n cxy=parameters[\"cxy\"],\n cyx=parameters[\"cyx\"],\n frequency=parameters[\"frequency\"],\n tag=tag,\n n_link=n_link,\n scale_factor=scale_factor,\n color=color,\n )\n\n @classmethod\n def from_fluid_flow(\n cls,\n n,\n nz,\n ntheta,\n nradius,\n length,\n omega,\n p_in,\n p_out,\n radius_rotor,\n radius_stator,\n visc,\n rho,\n eccentricity=None,\n load=None,\n ):\n \"\"\"Instantiate a bearing using inputs from its fluid flow.\n\n Parameters\n ----------\n n : int\n The node in which the bearing will be located in the rotor.\n\n Grid related\n ^^^^^^^^^^^^\n Describes the discretization of the problem\n nz: int\n Number of points along the Z direction (direction of flow).\n ntheta: int\n Number of points along the direction theta. NOTE: ntheta must be odd.\n nradius: int\n Number of points along the direction r.\n length: float\n Length in the Z direction (m).\n\n Operation conditions\n ^^^^^^^^^^^^^^^^^^^^\n Describes the operation conditions.\n omega: float\n Rotation of the rotor (rad/s).\n p_in: float\n Input Pressure (Pa).\n p_out: float\n Output Pressure (Pa).\n load: float\n Load applied to the rotor (N).\n\n Geometric data of the problem\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n Describes the geometric data of the problem.\n radius_rotor: float\n Rotor radius (m).\n radius_stator: float\n Stator Radius (m).\n eccentricity: float\n Eccentricity (m) is the euclidean distance between rotor and stator centers.\n The center of the stator is in position (0,0).\n\n Fluid characteristics\n ^^^^^^^^^^^^^^^^^^^^^\n Describes the fluid characteristics.\n visc: float\n Viscosity (Pa.s).\n rho: float\n Fluid density(Kg/m^3).\n\n Returns\n -------\n bearing: rs.BearingElement\n A bearing object.\n\n Examples\n --------\n >>> nz = 30\n >>> ntheta = 20\n >>> nradius = 11\n >>> length = 0.03\n >>> omega = 157.1\n >>> p_in = 0.\n >>> p_out = 0.\n >>> radius_rotor = 0.0499\n >>> radius_stator = 0.05\n >>> eccentricity = (radius_stator - radius_rotor)*0.2663\n >>> visc = 0.1\n >>> rho = 860.\n >>> BearingElement.from_fluid_flow(0, nz, ntheta, nradius, length, omega, p_in,\n ... p_out, radius_rotor, radius_stator,\n ... visc, rho, eccentricity=eccentricity) # doctest: +ELLIPSIS\n BearingElement(n=0, n_link=None,\n kxx=[...\n \"\"\"\n fluid_flow = flow.FluidFlow(\n nz,\n ntheta,\n nradius,\n length,\n omega,\n p_in,\n p_out,\n radius_rotor,\n radius_stator,\n visc,\n rho,\n eccentricity=eccentricity,\n load=load,\n )\n c = calculate_damping_matrix(fluid_flow, force_type=\"short\")\n k = calculate_stiffness_matrix(fluid_flow, force_type=\"short\")\n return cls(\n n,\n kxx=k[0],\n cxx=c[0],\n kyy=k[3],\n kxy=k[1],\n kyx=k[2],\n cyy=c[3],\n cxy=c[1],\n cyx=c[2],\n frequency=fluid_flow.omega,\n )\n\n\nclass SealElement(BearingElement):\n \"\"\"A seal element.\n\n This class will create a seal element.\n Parameters can be a constant value or speed dependent.\n For speed dependent parameters, each argument should be passed\n as an array and the correspondent speed values should also be\n passed as an array.\n Values for each parameter will be interpolated for the speed.\n\n SealElement objects are handled differently in the Rotor class, even though it\n inherits from BearingElement class. Seal elements are not considered in static\n analysis, i.e., it does not add reaction forces (only bearings support the rotor).\n In stability level 1 analysis, seal elements are removed temporarily from the model,\n so that the cross coupled coefficients are calculated and replace the seals from\n the rotor model.\n SealElement data is stored in an individual data frame, separate from other\n bearing elements.\n\n Notes\n -----\n SealElement class is strongly recommended to represent seals.\n Avoid using BearingElement class for this purpose.\n\n Parameters\n ----------\n n: int\n Node which the bearing will be located in\n kxx: float, array, pint.Quantity\n Direct stiffness in the x direction.\n cxx: float, array, pint.Quantity\n Direct damping in the x direction.\n kyy: float, array, pint.Quantity, optional\n Direct stiffness in the y direction.\n (defaults to kxx)\n cyy: float, array, pint.Quantity, optional\n Direct damping in the y direction.\n (defaults to cxx)\n kxy: float, array, pint.Quantity, optional\n Cross coupled stiffness in the x direction.\n (defaults to 0)\n cxy: float, array, pint.Quantity, optional\n Cross coupled damping in the x direction.\n (defaults to 0)\n kyx: float, array, pint.Quantity, optional\n Cross coupled stiffness in the y direction.\n (defaults to 0)\n cyx: float, array, pint.Quantity, optional\n Cross coupled damping in the y direction.\n (defaults to 0)\n frequency: array, pint.Quantity, optional\n Array with the speeds (rad/s).\n seal_leakage: float, optional\n Amount of leakage.\n tag : str, optional\n A tag to name the element\n Default is None.\n scale_factor: float, optional\n The scale factor is used to scale the seal drawing.\n Default is 1\n\n Examples\n --------\n >>> # A seal element located in the first rotor node, with these\n >>> # following stiffness and damping coefficients and speed range from\n >>> # 0 to 200 rad/s\n >>> import ross as rs\n >>> kxx = 1e6\n >>> kyy = 0.8e6\n >>> cxx = 2e2\n >>> cyy = 1.5e2\n >>> frequency = np.linspace(0, 200, 11)\n >>> seal = rs.SealElement(n=0, kxx=kxx, kyy=kyy, cxx=cxx, cyy=cyy, frequency=frequency)\n >>> seal.K(frequency) # doctest: +ELLIPSIS\n array([[[1000000., 1000000., ...\n >>> seal.C(frequency) # doctest: +ELLIPSIS\n array([[[200., 200., ...\n \"\"\"\n\n @check_units\n def __init__(\n self,\n n,\n kxx,\n cxx,\n kyy=None,\n kxy=0,\n kyx=0,\n cyy=None,\n cxy=0,\n cyx=0,\n frequency=None,\n seal_leakage=None,\n tag=None,\n scale_factor=1.0,\n ):\n super().__init__(\n n=n,\n frequency=frequency,\n kxx=kxx,\n kxy=kxy,\n kyx=kyx,\n kyy=kyy,\n cxx=cxx,\n cxy=cxy,\n cyx=cyx,\n cyy=cyy,\n tag=tag,\n scale_factor=scale_factor,\n )\n\n self.seal_leakage = seal_leakage\n self.color = \"#77ACA2\"\n\n\nclass BallBearingElement(BearingElement):\n \"\"\"A bearing element for ball bearings.\n\n This class will create a bearing element based on some geometric and\n constructive parameters of ball bearings. The main difference is that\n cross-coupling stiffness and damping are not modeled in this case.\n\n Parameters\n ----------\n n: int\n Node which the bearing will be located in.\n n_balls: float\n Number of steel spheres in the bearing.\n d_balls: float\n Diameter of the steel sphere.\n fs: float,optional\n Static bearing loading force.\n alpha: float, optional\n Contact angle between the steel sphere and the inner / outer raceway.\n cxx: float, optional\n Direct stiffness in the x direction.\n Default is None.\n cyy: float, optional\n Direct damping in the y direction.\n Defaults is None.\n tag: str, optional\n A tag to name the element\n Default is None.\n n_link: int, optional\n Node to which the bearing will connect. If None the bearing is\n connected to ground.\n Default is None.\n scale_factor: float, optional\n The scale factor is used to scale the bearing drawing.\n Default is 1.\n\n Examples\n --------\n >>> n = 0\n >>> n_balls= 8\n >>> d_balls = 0.03\n >>> fs = 500.0\n >>> alpha = np.pi / 6\n >>> tag = \"ballbearing\"\n >>> bearing = BallBearingElement(n=n, n_balls=n_balls, d_balls=d_balls,\n ... fs=fs, alpha=alpha, tag=tag)\n >>> bearing.K(0)\n array([[4.64168838e+07, 0.00000000e+00],\n [0.00000000e+00, 1.00906269e+08]])\n \"\"\"\n\n def __init__(\n self,\n n,\n n_balls,\n d_balls,\n fs,\n alpha,\n cxx=None,\n cyy=None,\n tag=None,\n n_link=None,\n scale_factor=1,\n ):\n\n Kb = 13.0e6\n kyy = (\n Kb\n * n_balls ** (2.0 / 3)\n * d_balls ** (1.0 / 3)\n * fs ** (1.0 / 3)\n * (np.cos(alpha)) ** (5.0 / 3)\n )\n\n nb = [8, 12, 16]\n ratio = [0.46, 0.64, 0.73]\n dict_ratio = dict(zip(nb, ratio))\n\n if n_balls in dict_ratio.keys():\n kxx = dict_ratio[n_balls] * kyy\n else:\n f = interpolate.interp1d(nb, ratio, kind=\"quadratic\")\n kxx = f(n_balls)\n\n if cxx is None:\n cxx = 1.25e-5 * kxx\n if cyy is None:\n cyy = 1.25e-5 * kyy\n\n super().__init__(\n n=n,\n frequency=None,\n kxx=kxx,\n kxy=0.0,\n kyx=0.0,\n kyy=kyy,\n cxx=cxx,\n cxy=0.0,\n cyx=0.0,\n cyy=cyy,\n tag=tag,\n n_link=n_link,\n scale_factor=scale_factor,\n )\n\n self.color = \"#77ACA2\"\n\n\nclass RollerBearingElement(BearingElement):\n \"\"\"A bearing element for roller bearings.\n\n This class will create a bearing element based on some geometric and\n constructive parameters of roller bearings. The main difference is that\n cross-coupling stiffness and damping are not modeled in this case.\n\n Parameters\n ----------\n n: int\n Node which the bearing will be located in.\n n_rollers: float\n Number of steel spheres in the bearing.\n l_rollers: float\n Length of the steel rollers.\n fs: float,optional\n Static bearing loading force.\n alpha: float, optional\n Contact angle between the steel sphere and the inner / outer raceway.\n cxx: float, optional\n Direct stiffness in the x direction.\n Default is None.\n cyy: float, optional\n Direct damping in the y direction.\n Defaults is None.\n tag: str, optional\n A tag to name the element\n Default is None.\n n_link: int, optional\n Node to which the bearing will connect. If None the bearing is\n connected to ground.\n Default is None.\n scale_factor: float, optional\n The scale factor is used to scale the bearing drawing.\n Default is 1.\n\n Examples\n --------\n >>> n = 0\n >>> n_rollers= 8\n >>> l_rollers = 0.03\n >>> fs = 500.0\n >>> alpha = np.pi / 6\n >>> tag = \"rollerbearing\"\n >>> bearing = RollerBearingElement(n=n, n_rollers=n_rollers, l_rollers=l_rollers,\n ... fs=fs, alpha=alpha, tag=tag)\n >>> bearing.K(0)\n array([[2.72821927e+08, 0.00000000e+00],\n [0.00000000e+00, 5.56779444e+08]])\n \"\"\"\n\n def __init__(\n self,\n n,\n n_rollers,\n l_rollers,\n fs,\n alpha,\n cxx=None,\n cyy=None,\n tag=None,\n n_link=None,\n scale_factor=1,\n ):\n\n Kb = 1.0e9\n kyy = (\n Kb\n * n_rollers ** 0.9\n * l_rollers ** 0.8\n * fs ** 0.1\n * (np.cos(alpha)) ** 1.9\n )\n\n nr = [8, 12, 16]\n ratio = [0.49, 0.66, 0.74]\n dict_ratio = dict(zip(nr, ratio))\n\n if n_rollers in dict_ratio.keys():\n kxx = dict_ratio[n_rollers] * kyy\n else:\n f = interpolate.interp1d(nr, ratio, kind=\"quadratic\")\n kxx = f(n_rollers)\n\n if cxx is None:\n cxx = 1.25e-5 * kxx\n if cyy is None:\n cyy = 1.25e-5 * kyy\n\n super().__init__(\n n=n,\n frequency=None,\n kxx=kxx,\n kxy=0.0,\n kyx=0.0,\n kyy=kyy,\n cxx=cxx,\n cxy=0.0,\n cyx=0.0,\n cyy=cyy,\n tag=tag,\n n_link=n_link,\n scale_factor=scale_factor,\n )\n\n self.color = \"#77ACA2\"\n\n\nclass MagneticBearingElement(BearingElement):\n \"\"\"Magnetic bearing.\n\n This class creates a magnetic bearing element.\n Converts electromagnetic parameters and PID gains to stiffness and damping\n coefficients.\n\n Parameters\n ----------\n n : int\n The node in which the magnetic bearing will be located in the rotor.\n g0: float\n Air gap in m^2.\n i0: float\n Bias current in Ampere\n ag: float\n Pole area in m^2.\n nw: float or int\n Number of windings\n alpha: float or int\n Pole angle in radians.\n kp_pid: float or int\n Proportional gain of the PID controller.\n kd_pid: float or int\n Derivative gain of the PID controller.\n k_amp: float or int\n Gain of the amplifier model.\n k_sense: float or int\n Gain of the sensor model.\n tag: str, optional\n A tag to name the element\n Default is None.\n n_link: int, optional\n Node to which the bearing will connect. If None the bearing is\n connected to ground.\n Default is None.\n scale_factor: float, optional\n The scale factor is used to scale the bearing drawing.\n Default is 1.\n\n ----------\n See the following reference for the electromagnetic parameters g0, i0, ag, nw, alpha:\n Book: Magnetic Bearings. Theory, Design, and Application to Rotating Machinery\n Authors: Gerhard Schweitzer and Eric H. Maslen\n Page: 84-95\n\n Examples\n --------\n >>> n = 0\n >>> g0 = 1e-3\n >>> i0 = 1.0\n >>> ag = 1e-4\n >>> nw = 200\n >>> alpha = 0.392\n >>> kp_pid = 1.0\n >>> kd_pid = 1.0\n >>> k_amp = 1.0\n >>> k_sense = 1.0\n >>> tag = \"magneticbearing\"\n >>> mbearing = MagneticBearingElement(n=n, g0=g0, i0=i0, ag=ag, nw=nw,alpha=alpha,\n ... kp_pid=kp_pid, kd_pid=kd_pid, k_amp=k_amp,\n ... k_sense=k_sense)\n >>> mbearing.kxx\n [-4640.623377181318]\n \"\"\"\n\n def __init__(\n self,\n n,\n g0,\n i0,\n ag,\n nw,\n alpha,\n kp_pid,\n kd_pid,\n k_amp,\n k_sense,\n tag=None,\n n_link=None,\n scale_factor=1,\n ):\n pL = [g0, i0, ag, nw, alpha, kp_pid, kd_pid, k_amp, k_sense]\n pA = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n # Check if it is a number or a list with 2 items\n for i in range(9):\n if type(pL[i]) == float or int:\n pA[i] = np.array(pL[i])\n else:\n if type(pL[i]) == list:\n if len(pL[i]) > 2:\n raise ValueError(\n \"Parameters must be scalar or a list with 2 items\"\n )\n else:\n pA[i] = np.array(pL[i])\n else:\n raise ValueError(\"Parameters must be scalar or a list with 2 items\")\n\n # From: \"Magnetic Bearings. Theory, Design, and Application to Rotating Machinery\"\n # Authors: Gerhard Schweitzer and Eric H. Maslen\n # Page: 354\n ks = (\n -4.0\n * pA[1] ** 2.0\n * np.cos(pA[4])\n * 4.0\n * np.pi\n * 1e-7\n * pA[3] ** 2.0\n * pA[2]\n / (4.0 * pA[0] ** 3)\n )\n ki = (\n 4.0\n * pA[1]\n * np.cos(pA[4])\n * 4.0\n * np.pi\n * 1e-7\n * pA[3] ** 2.0\n * pA[2]\n / (4.0 * pA[0] ** 2)\n )\n k = ki * pA[7] * pA[8] * (pA[5] + np.divide(ks, ki * pA[7] * pA[8]))\n c = ki * pA[7] * pA[5] * pA[8]\n # k = ki * k_amp*k_sense*(kp_pid+ np.divide(ks, ki*k_amp*k_sense))\n # c = ki*k_amp*kd_pid*k_sense\n\n # Get the parameters from k and c\n if np.isscalar(k):\n # If k is scalar, symmetry is assumed\n kxx = k\n kyy = k\n else:\n kxx = k[0]\n kyy = k[1]\n\n if np.isscalar(c):\n # If c is scalar, symmetry is assumed\n cxx = c\n cyy = c\n else:\n cxx = c[0]\n cyy = c[1]\n\n super().__init__(\n n=n,\n frequency=None,\n kxx=kxx,\n kxy=0.0,\n kyx=0.0,\n kyy=kyy,\n cxx=cxx,\n cxy=0.0,\n cyx=0.0,\n cyy=cyy,\n tag=tag,\n n_link=n_link,\n scale_factor=scale_factor,\n )\n\n\nclass BearingElement6DoF(BearingElement):\n \"\"\"A generalistic 6 DoF bearing element.\n\n This class will create a bearing\n element based on the user supplied stiffness and damping coefficients. These\n are determined alternatively, via purposefully built codes.\n\n Parameters\n ----------\n kxx: float, array, pint.Quantity\n Direct stiffness in the x direction.\n cxx: float, array, pint.Quantity\n Direct damping in the x direction.\n kyy: float, array, pint.Quantity, optional\n Direct stiffness in the y direction.\n Defaults to kxx\n cyy: float, array, pint.Quantity, optional\n Direct damping in the y direction.\n Default is to cxx\n kxy: float, array, pint.Quantity, optional\n Cross stiffness between xy directions.\n Default is 0\n kyx: float, array, pint.Quantity, optional\n Cross stiffness between yx directions.\n Default is 0\n kzz: float, array, pint.Quantity, optional\n Direct stiffness in the z direction.\n Default is 0\n cxy: float, array, pint.Quantity, optional\n Cross damping between xy directions.\n Default is 0\n cyx: float, array, pint.Quantity, optional\n Cross damping between yx directions.\n Default is 0\n czz: float, array, pint.Quantity, optional\n Direct damping in the z direction.\n Default is 0\n frequency: array, pint.Quantity, optional\n Array with the frequencies (rad/s).\n tag : str, optional\n A tag to name the element\n Default is None\n n_link: int, optional\n Node to which the bearing will connect. If None the bearing is\n connected to ground.\n Default is None.\n scale_factor: float, optional\n The scale factor is used to scale the bearing drawing.\n Default is 1.\n\n Examples\n --------\n >>> n = 0\n >>> kxx = 1.0e7\n >>> kyy = 1.5e7\n >>> kzz = 5.0e5\n >>> bearing = BearingElement6DoF(n=n, kxx=kxx, kyy=kyy, kzz=kzz,\n ... cxx=0, cyy=0)\n >>> bearing.K(0)\n array([[10000000., 0., 0.],\n [ 0., 15000000., 0.],\n [ 0., 0., 500000.]])\n \"\"\"\n\n @check_units\n def __init__(\n self,\n n,\n kxx,\n cxx,\n kyy=None,\n cyy=None,\n kxy=0.0,\n kyx=0.0,\n kzz=0.0,\n cxy=0.0,\n cyx=0.0,\n czz=0.0,\n frequency=None,\n tag=None,\n n_link=None,\n scale_factor=1,\n color=\"#355d7a\",\n ):\n super().__init__(\n n=n,\n kxx=kxx,\n cxx=cxx,\n kyy=kyy,\n kxy=kxy,\n kyx=kyx,\n cyy=cyy,\n cxy=cxy,\n cyx=cyx,\n frequency=frequency,\n tag=tag,\n n_link=n_link,\n scale_factor=scale_factor,\n color=color,\n )\n\n new_args = [\"kzz\", \"czz\"]\n\n args_dict = locals()\n coefficients = {}\n\n if kzz is None:\n args_dict[\"kzz\"] = (\n kxx * 0.6\n ) # NSK manufacturer sugestion for deep groove ball bearings\n if czz is None:\n args_dict[\"czz\"] = cxx\n\n for arg in new_args:\n if arg[0] == \"k\":\n coefficients[arg] = _Stiffness_Coefficient(\n coefficient=args_dict[arg], frequency=None\n )\n else:\n coefficients[arg] = _Damping_Coefficient(args_dict[arg], None)\n\n coefficients_len = [len(v.coefficient) for v in coefficients.values()]\n\n for c in coefficients_len:\n if c != 1:\n raise ValueError(\n \"Arguments (coefficients and frequency)\"\n \" must have the same dimension\"\n )\n\n for k, v in coefficients.items():\n setattr(self, k, v)\n\n def __hash__(self):\n return hash(self.tag)\n\n def __repr__(self):\n \"\"\"Return a string representation of a bearing element.\n\n Returns\n -------\n A string representation of a bearing element object.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing # doctest: +ELLIPSIS\n BearingElement(n=0, n_link=None,\n kxx=[...\n \"\"\"\n return (\n f\"{self.__class__.__name__}\"\n f\"(n={self.n}, n_link={self.n_link},\\n\"\n f\" kxx={self.kxx}, kxy={self.kxy},\\n\"\n f\" kyx={self.kyx}, kyy={self.kyy},\\n\"\n f\" kzz={self.kzz}, cxx={self.cxx},\\n\"\n f\" cxy={self.cxy}, cyx={self.cyx},\\n\"\n f\" cyy={self.cyy}, czz={self.czz},\\n\"\n f\" frequency={self.frequency}, tag={self.tag!r})\"\n )\n\n def __eq__(self, other):\n \"\"\"Equality method for comparasions.\n\n Parameters\n ----------\n other : object\n The second object to be compared with.\n\n Returns\n -------\n bool\n True if the comparison is true; False otherwise.\n\n Examples\n --------\n >>> bearing1 = bearing_example()\n >>> bearing2 = bearing_example()\n >>> bearing1 == bearing2\n True\n \"\"\"\n compared_attributes = [\n \"kxx\",\n \"kyy\",\n \"kxy\",\n \"kyx\",\n \"cxx\",\n \"cyy\",\n \"cxy\",\n \"cyx\",\n \"kzz\",\n \"czz\",\n \"frequency\",\n \"n\",\n \"n_link\",\n ]\n if isinstance(other, self.__class__):\n return all(\n (\n np.array(getattr(self, attr)).all()\n == np.array(getattr(other, attr)).all()\n for attr in compared_attributes\n )\n )\n return False\n\n def save(self, file_name=Path(os.getcwd())):\n \"\"\"Save a bearing element in a toml format.\n\n It works as an auxiliary function of the save function in the Rotor class.\n\n Parameters\n ----------\n file_name : string\n The name of the file the bearing element will be saved in.\n\n Examples\n --------\n >>> bearing = bearing_6dof_example()\n >>> bearing.save(Path(os.getcwd()))\n \"\"\"\n data = self.get_data(Path(file_name) / \"BearingElement6DoF.toml\")\n\n if type(self.frequency) == np.ndarray:\n try:\n self.frequency[0]\n frequency = list(self.frequency)\n except IndexError:\n frequency = None\n\n data[\"BearingElement6DoF\"][str(self.n)] = {\n \"n\": self.n,\n \"kxx\": self.kxx.coefficient,\n \"cxx\": self.cxx.coefficient,\n \"kyy\": self.kyy.coefficient,\n \"kxy\": self.kxy.coefficient,\n \"kyx\": self.kyx.coefficient,\n \"kzz\": self.kzz.coefficient,\n \"cyy\": self.cyy.coefficient,\n \"cxy\": self.cxy.coefficient,\n \"cyx\": self.cyx.coefficient,\n \"czz\": self.czz.coefficient,\n \"frequency\": frequency,\n \"tag\": self.tag,\n \"n_link\": self.n_link,\n \"scale_factor\": self.scale_factor,\n }\n self.dump_data(data, Path(file_name) / \"BearingElement6DoF.toml\")\n\n @staticmethod\n def load(file_name=\"\"):\n \"\"\"Load a list of bearing elements saved in a toml format.\n\n Parameters\n ----------\n file_name : string\n The name of the file of the bearing element to be loaded.\n\n Returns\n -------\n A list of bearing elements.\n\n Examples\n --------\n >>> bearing1 = bearing_6dof_example()\n >>> bearing1.save(os.getcwd())\n >>> list_of_bearings = BearingElement6DoF.load(os.getcwd())\n >>> bearing1 == list_of_bearings[0]\n True\n \"\"\"\n bearing_elements = []\n bearing_elements_dict = BearingElement.get_data(\n file_name=Path(file_name) / \"BearingElement6DoF.toml\"\n )\n for element in bearing_elements_dict[\"BearingElement6DoF\"]:\n bearing = BearingElement6DoF(\n **bearing_elements_dict[\"BearingElement6DoF\"][element]\n )\n data = bearing_elements_dict[\"BearingElement6DoF\"]\n bearing.kxx.coefficient = data[element][\"kxx\"]\n\n bearing.kxy.coefficient = data[element][\"kxy\"]\n\n bearing.kyx.coefficient = data[element][\"kyx\"]\n\n bearing.kyy.coefficient = data[element][\"kyy\"]\n\n bearing.kzz.coefficient = data[element][\"kzz\"]\n\n bearing.cxx.coefficient = data[element][\"cxx\"]\n\n bearing.cxy.coefficient = data[element][\"cxy\"]\n\n bearing.cyx.coefficient = data[element][\"cyx\"]\n\n bearing.cyy.coefficient = data[element][\"cyy\"]\n\n bearing.czz.coefficient = data[element][\"czz\"]\n\n bearing_elements.append(bearing)\n return bearing_elements\n\n def dof_mapping(self):\n \"\"\"Degrees of freedom mapping.\n\n Returns a dictionary with a mapping between degree of freedom and its index.\n\n Returns\n -------\n dof_mapping : dict\n A dictionary containing the degrees of freedom and their indexes.\n\n Examples\n --------\n The numbering of the degrees of freedom for each node.\n\n Being the following their ordering for a node:\n\n x_0 - horizontal translation\n y_0 - vertical translation\n z_0 - axial translation\n\n >>> bearing = bearing_6dof_example()\n >>> bearing.dof_mapping()\n {'x_0': 0, 'y_0': 1, 'z_0': 2}\n \"\"\"\n return dict(x_0=0, y_0=1, z_0=2)\n\n def K(self, frequency):\n \"\"\"Stiffness matrix for an instance of a bearing element.\n\n This method returns the stiffness matrix for an instance of a bearing element.\n\n Parameters\n ----------\n frequency : float\n The excitation frequency.\n\n Returns\n -------\n K : np.ndarray\n A 3x3 matrix of floats containing the kxx, kxy, kyx, kyy and kzz values.\n\n Examples\n --------\n >>> bearing = bearing_6dof_example()\n >>> bearing.K(0)\n array([[1000000., 0., 0.],\n [ 0., 800000., 0.],\n [ 0., 0., 100000.]])\n \"\"\"\n kxx = self.kxx.interpolated(frequency)\n kyy = self.kyy.interpolated(frequency)\n kxy = self.kxy.interpolated(frequency)\n kyx = self.kyx.interpolated(frequency)\n kzz = self.kzz.interpolated(frequency)\n\n K = np.array([[kxx, kxy, 0], [kyx, kyy, 0], [0, 0, kzz]])\n\n return K\n\n def C(self, frequency):\n \"\"\"Damping matrix for an instance of a bearing element.\n\n This method returns the damping matrix for an instance of a bearing element.\n\n Parameters\n ----------\n frequency : float\n The excitation frequency.\n\n Returns\n -------\n C: np.ndarray\n A 3x3 matrix of floats containing the cxx, cxy, cyx, cyy, and czz values.\n\n Examples\n --------\n >>> bearing = bearing_6dof_example()\n >>> bearing.C(0)\n array([[200., 0., 0.],\n [ 0., 150., 0.],\n [ 0., 0., 50.]])\n \"\"\"\n cxx = self.cxx.interpolated(frequency)\n cyy = self.cyy.interpolated(frequency)\n cxy = self.cxy.interpolated(frequency)\n cyx = self.cyx.interpolated(frequency)\n czz = self.czz.interpolated(frequency)\n\n C = np.array([[cxx, cxy, 0], [cyx, cyy, 0], [0, 0, czz]])\n\n return C\n\n\ndef bearing_example():\n \"\"\"Create an example of bearing element.\n\n This function returns an instance of a simple seal. The purpose is to make\n available a simple model so that doctest can be written using it.\n\n Returns\n -------\n An instance of a bearing object.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.frequency[0]\n 0.0\n \"\"\"\n w = np.linspace(0, 200, 11)\n bearing = BearingElement(n=0, kxx=1e6, kyy=0.8e6, cxx=2e2, cyy=1.5e2, frequency=w)\n return bearing\n\n\ndef seal_example():\n \"\"\"Create an example of seal element.\n\n This function returns an instance of a simple seal. The purpose is to make\n available a simple model so that doctest can be written using it.\n\n Returns\n -------\n seal : ross.SealElement\n An instance of a bearing object.\n\n Examples\n --------\n >>> seal = bearing_example()\n >>> seal.frequency[0]\n 0.0\n \"\"\"\n w = np.linspace(0, 200, 11)\n seal = SealElement(n=0, kxx=1e6, kyy=0.8e6, cxx=2e2, cyy=1.5e2, frequency=w)\n return seal\n\n\ndef bearing_6dof_example():\n \"\"\"Create an example of bearing element.\n\n This function returns an instance of a simple bearing. The purpose is to make\n available a simple model so that doctest can be written using it.\n\n Returns\n -------\n bearing : ross.BearingElement6DoF\n An instance of a bearing object.\n\n Examples\n --------\n >>> bearing = bearing_example()\n >>> bearing.frequency[0]\n 0.0\n \"\"\"\n bearing = BearingElement6DoF(\n n=0, kxx=1e6, kyy=0.8e6, cxx=2e2, cyy=1.5e2, kzz=1e5, czz=0.5e2\n )\n return bearing\n" ]
[ [ "numpy.hstack", "scipy.interpolate.UnivariateSpline", "numpy.allclose", "numpy.linspace", "numpy.cos", "scipy.interpolate.interp1d", "numpy.insert", "numpy.isscalar", "numpy.array", "numpy.divide" ] ]
Niels-NTG/GDMC2022
[ "515f4b7dd6f04af9714e7773f36cc9b3f1da1b95" ]
[ "SettlementBuilder.py" ]
[ "import numpy as np\nimport mapUtils\nfrom Node import Node\n\n\nclass SettlementBuilder:\n\n def __init__(self):\n\n # DEBUG\n # central RNG generator\n rng = np.random.default_rng()\n\n buildArea = mapUtils.getBuildArea()\n startingPos = (10, 10)\n\n # DEBUG\n mapUtils.fill(\n buildArea[0],\n 69,\n buildArea[1],\n buildArea[0] + buildArea[2],\n 69 + 10,\n buildArea[1] + buildArea[3],\n \"minecraft:air\"\n )\n\n # Height map of the build area.\n heightMap = mapUtils.calcGoodHeightmap(buildArea)\n\n # Map of structures built in the build area.\n mapOfStructures = np.full(shape=heightMap.shape, fill_value=0)\n\n startingNode = Node(\n x=buildArea[0] + startingPos[0],\n y=73,\n z=buildArea[1] + startingPos[1],\n buildArea=buildArea,\n heightMap=heightMap,\n mapOfStructures=mapOfStructures,\n nodeStructureType='lab_a/hub',\n rng=rng\n )\n startingNode.place()\n" ]
[ [ "numpy.random.default_rng", "numpy.full" ] ]
ShaneSmiskol/Konverter
[ "76995e1b30a1cdf3fb1568f8aa468e68a15aad69" ]
[ "tests/test_konverter.py" ]
[ "import warnings\nimport os\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\nwarnings.filterwarnings('ignore', category=FutureWarning)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport konverter\nimport importlib\nimport numpy as np\nimport tensorflow as tf\nfrom packaging import version\nfrom utils.BASEDIR import BASEDIR\nfrom tests.build_test_models import create_model\n\nos.chdir(BASEDIR)\n\n\ndef test_models():\n tests = {'Dense': {'max_mae': 1e-5, 'max_mse': 1e-11},\n 'SimpleRNN': {'max_mae': 1e-4, 'max_mse': 1e-9}, # RNN models have higher error/variance for some reason\n 'GRU': {'max_mae': 1e-4, 'max_mse': 1e-9}}\n if version.parse(tf.__version__) < version.parse('2.0.0a0'):\n del tests['GRU']\n samples = 1000\n for test in tests:\n print(f'\\nCreating trained {test} model', flush=True)\n ker_model, data_shape = create_model(test)\n konverter.konvert(ker_model, f'tests/{test.lower()}_model', silent=True)\n kon_model = importlib.import_module(f'tests.{test.lower()}_model')\n\n x_train = np.random.uniform(0, 10, (samples, *data_shape[1:])).astype('float32')\n konverter_preds = []\n keras_preds = []\n\n print('Comparing model outputs\\n', flush=True)\n for sample in x_train:\n konverter_preds.append(kon_model.predict(sample)[0])\n keras_preds.append(ker_model.predict_on_batch(np.array([sample]))[0][0])\n\n mae = np.abs(np.subtract(keras_preds, konverter_preds)).mean()\n mse = np.square(np.subtract(keras_preds, konverter_preds)).mean()\n assert mae < tests[test]['max_mae']\n assert mse < tests[test]['max_mse']\n print(f'Mean absolute error: {mae} < {tests[test][\"max_mae\"]}')\n print(f'Mean squared error: {mse} < {tests[test][\"max_mse\"]}')\n print(f'{test} model passed!')\n" ]
[ [ "numpy.random.uniform", "numpy.array", "numpy.subtract" ] ]
rantahar/Growing_neural_network
[ "1cc9ff6b7b96c8386f32a003b2a594d5e71e0f3f" ]
[ "train_dynamic.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport time\n\nfrom dynamic_networks import (\n DynamicModel,\n DynamicDenseLayer,\n DynamicConv2DLayer,\n DynamicConv2DToDenseLayer,\n)\n\n#################################################\n# A simple test for training the dynamic network\n# Builds a standard convolutional model following\n# https://www.tensorflow.org/tutorials/images/cnn.\n#\n# At a constant interval, we update the network\n# using the stochastic update step.\n#################################################\n\n\n# General optimization parameters\nEPOCHS = 50\nIMG_SIZE = 32\nbatch_size = 100\n\n# Network update parameters\nnetwork_updates_every = 10\nweight_penalty = 1e-9\nstart_features = 4\nnew_weight_std = 0.1\n\n\n# Download and process the CIFAR dataset\n(train_images, train_labels), (\n valid_images,\n valid_labels,\n) = tf.keras.datasets.cifar10.load_data()\nn_labels = 10\n\n# Rescale to between 0 and 1\ntrain_images, valid_images = train_images / 255.0, valid_images / 255.0\ntraining_data = (train_images.astype(np.float32), train_labels.astype(np.int32))\nvalid_data = (valid_images.astype(np.float32), valid_labels.astype(np.int32))\n\n# Build shuffled and batched datasets\ntrain_dataset = (\n tf.data.Dataset.from_tensor_slices(training_data).shuffle(60000).batch(batch_size)\n)\nvalid_dataset = (\n tf.data.Dataset.from_tensor_slices(valid_data).shuffle(10000).batch(batch_size)\n)\n\n\n# Create two dynamic dense layers\nlayers = [\n DynamicConv2DLayer(3, 3, start_features, new_weight_std),\n DynamicConv2DLayer(3, start_features, start_features, new_weight_std),\n DynamicConv2DLayer(3, start_features, start_features, new_weight_std),\n DynamicConv2DLayer(3, start_features, start_features, new_weight_std),\n DynamicConv2DToDenseLayer(2 * 2, start_features, start_features, new_weight_std),\n DynamicDenseLayer(start_features, start_features, new_weight_std),\n DynamicDenseLayer(start_features, 10, new_weight_std),\n]\nclassifier = DynamicModel(layers, new_weight_std=new_weight_std)\n\n\n# The loss function\n# This is the full loss for the gradient descent.\n# the network update step includes a further weight\n# penalty\ndef compute_loss(data):\n predictions = classifier(data[0])\n loss = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(data[1][:, 0], predictions)\n )\n return loss\n\n\n# Update weights using Adam\noptimizer = tf.optimizers.Adam()\n\n\ndef gradient_train_step(data):\n trainable_variables = classifier.trainable_variables()\n\n with tf.GradientTape() as tape:\n loss = compute_loss(data)\n\n gradients = tape.gradient(loss, trainable_variables)\n\n classifier.apply_adam(gradients)\n return loss\n\n\ntime_elapsed = 0\n\n# The update loop\nfor epoch in range(1, EPOCHS + 1):\n start_time = time.time()\n network_changes = 0\n\n # Run training over all batches.\n train_loss = 0\n for i, element in enumerate(train_dataset):\n if (i + 1) % network_updates_every == 0:\n # network update step\n network_changes += classifier.update_features(\n element, compute_loss, weight_penalty\n )\n else:\n # standard gradient update step\n loss = gradient_train_step(element)\n train_loss += loss.numpy()\n train_loss *= batch_size / train_images.shape[0]\n end_time = time.time()\n\n # Print the state of the network\n classifier.summary()\n\n # Calculate validation loss.\n valid_loss = 0\n for element in valid_dataset:\n loss = compute_loss(element)\n valid_loss += loss.numpy()\n valid_loss *= batch_size / valid_images.shape[0]\n print(\n \"Epoch {} done in {} seconds, loss {}, validation loss {}, network changes {}\".format(\n epoch, end_time - start_time, train_loss, valid_loss, network_changes\n )\n )\n\n time_elapsed += end_time - start_time\n print(\"Time elapsed {}\".format(time_elapsed))\n" ]
[ [ "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.keras.datasets.cifar10.load_data", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.optimizers.Adam", "tensorflow.GradientTape" ] ]
j-bac/skcontrib-id-estimators
[ "b8f60c8aca7382cdd11ea910714f762fac5910f6" ]
[ "skdim/id/_DANCo.py" ]
[ "#\n# BSD 3-Clause License\n#\n# Copyright (c) 2020, Jonathan Bac\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\n\nfrom sklearn.utils.validation import check_array, check_random_state\n\nimport sys\nimport warnings\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.special import i0, i1, digamma\nfrom scipy.interpolate import interp1d\nfrom ..datasets import hyperBall\nfrom .._commonfuncs import (\n binom_coeff,\n get_nn,\n lens,\n indnComb,\n GlobalEstimator,\n)\n\n\nclass DANCo(GlobalEstimator):\n # SPDX-License-Identifier: MIT, 2017 Kerstin Johnsson [IDJohnsson]_\n \"\"\"Intrinsic dimension estimation using the Dimensionality from Angle and Norm Concentration algorithm. [Ceruti2012]_ [IDLombardi]_ [IDJohnsson]_ \n\n Parameters\n ----------\n k: int, default=10\n Neighborhood parameter.\n D: int, default=None\n Maximal dimension\n ver: str, default='DANCo'\n Version to use. possible values: 'DANCo', 'MIND_MLi', 'MIND_MLk'.\n calibration_data: dict, default=None\n Precomputed calibration data. \n fractal: bool, default=True\n Whether to return fractal rather than integer dimension\n verbose: bool, default=False\n \"\"\"\n\n def __init__(\n self,\n k=10,\n D=None,\n calibration_data=None,\n ver=\"DANCo\",\n fractal=True,\n verbose=False,\n random_state=None,\n ):\n self.k = k\n self.D = D\n self.calibration_data = calibration_data\n self.ver = ver\n self.verbose = verbose\n self.fractal = fractal\n self.random_state = random_state\n\n def fit(self, X, y=None):\n \"\"\"A reference implementation of a fitting function.\n \n Parameters\n ----------\n X : {array-like}, shape (n_samples, n_features)\n A data set for which the intrinsic dimension is estimated.\n y : dummy parameter to respect the sklearn API\n\n Returns\n -------\n self : object\n Returns self.\n self.dimension_ : int (or float if fractal is True)\n The estimated intrinsic dimension\n self.kl_divergence : float\n The KL divergence between data and reference data for the estimated dimension (if ver == 'DANCo').\n self.calibration_data : dict\n Calibration data that can be reused when applying DANCo to data sets of the same size with the same neighborhood parameter k.\n \"\"\"\n X = check_array(X, ensure_min_samples=self.k + 1, ensure_min_features=2)\n\n if self.k >= len(X):\n warnings.warn(\"k larger or equal to len(X), using len(X)-2\")\n self._k = len(X) - 2\n else:\n self._k = self.k\n\n self._D = X.shape[1] if self.D is None else self.D\n\n self.random_state_ = check_random_state(self.random_state)\n\n if self.ver not in [\"DANCo\", \"DANCoFit\"]:\n self.dimension_ = self._dancoDimEst(X)\n else:\n (\n self.dimension_,\n self.kl_divergence_,\n self.calibration_data_,\n ) = self._dancoDimEst(X)\n\n self.is_fitted_ = True\n # `fit` should always return `self`\n return self\n\n def _KL(self, nocal, caldat):\n kld = self._KLd(nocal[\"dhat\"], caldat[\"dhat\"])\n klnutau = self._KLnutau(\n nocal[\"mu_nu\"], caldat[\"mu_nu\"], nocal[\"mu_tau\"], caldat[\"mu_tau\"]\n )\n # print(klnutau)\n return kld + klnutau\n\n def _KLd(self, dhat, dcal):\n H_k = np.sum(1 / np.arange(1, self._k + 1))\n quo = dcal / dhat\n a = (\n np.power(-1, np.arange(self._k + 1))\n * np.array(list(binom_coeff(self._k, i) for i in range(self._k + 1)))\n * digamma(1 + np.arange(self._k + 1) / quo)\n )\n return H_k * quo - np.log(quo) - (self._k - 1) * np.sum(a)\n\n @staticmethod\n def _KLnutau(nu1, nu2, tau1, tau2):\n return np.log(\n min(sys.float_info.max, i0(tau2)) / min(sys.float_info.max, i0(tau1))\n ) + min(sys.float_info.max, i1(tau1)) / min(sys.float_info.max, i0(tau1)) * (\n tau1 - tau2 * np.cos(nu1 - nu2)\n )\n\n def _nlld(self, d, rhos, N):\n return -self._lld(d, rhos, N)\n\n def _lld(self, d, rhos, N):\n if d == 0:\n return np.array([-1e30])\n else:\n return (\n N * np.log(self._k * d)\n + (d - 1) * np.sum(np.log(rhos))\n + (self._k - 1) * np.sum(np.log(1 - rhos ** d))\n )\n\n def _nlld_gr(self, d, rhos, N):\n if d == 0:\n return np.array([-1e30])\n else:\n return -(\n N / d\n + np.sum(\n np.log(rhos)\n - (self._k - 1) * (rhos ** d) * np.log(rhos) / (1 - rhos ** d)\n )\n )\n\n def _MIND_MLi(self, rhos, D):\n N = len(rhos)\n d_lik = np.array([np.nan] * D)\n for d in range(D):\n d_lik[d] = self._lld(d + 1, rhos, N)\n return np.argmax(d_lik) + 1\n\n def _MIND_MLk(self, rhos, D, dinit):\n res = minimize(\n fun=self._nlld,\n x0=np.array([dinit]),\n jac=self._nlld_gr,\n args=(rhos, len(rhos)),\n method=\"L-BFGS-B\",\n bounds=[(0, D)],\n )\n return res[\"x\"][0]\n\n def _MIND_MLx(self, X, D):\n nbh_data, idx = get_nn(X, self._k + 1)\n rhos = nbh_data[:, 0] / nbh_data[:, -1]\n\n d_MIND_MLi = self._MIND_MLi(rhos, D)\n if self.ver == \"MIND_MLi\":\n return d_MIND_MLi\n\n d_MIND_MLk = self._MIND_MLk(rhos, D, d_MIND_MLi)\n if self.ver == \"MIND_MLk\":\n return d_MIND_MLk\n else:\n raise ValueError(\"Unknown version: \", self.ver)\n\n @staticmethod\n def _Ainv(eta):\n if eta < 0.53:\n return 2 * eta + eta ** 3 + 5 * (eta ** 5) / 6\n elif eta < 0.85:\n return -0.4 + 1.39 * eta + 0.43 / (1 - eta)\n else:\n return 1 / ((eta ** 3) - 4 * (eta ** 2) + 3 * eta)\n\n def _loc_angles(self, pt, nbs):\n vec = nbs - pt\n # if(len(pt) == 1):\n # vec = vec.T\n vec_len = lens(vec)\n combs = indnComb(len(nbs), 2).T\n sc_prod = np.sum(vec[combs[0, :]] * vec[combs[1, :]], axis=1)\n # if (length(pt) == 1) {\n # print(sc.prod)\n # print((vec.len[combs[1, ]]*vec.len[combs[2, ]]))\n # }\n cos_th = sc_prod / (vec_len[combs[0, :]] * vec_len[combs[1, :]])\n\n if np.any(np.abs(cos_th) > 1):\n np.clip(cos_th, a_min=None, a_max=1, out=cos_th)\n if not hasattr(self, \"_warned\"):\n self._warned = True\n print(\n \"Warning: your data might contain duplicate rows, which can affect results\"\n )\n return np.arccos(cos_th)\n\n def _angles(self, X, nbs):\n N = len(X)\n\n thetas = np.zeros((N, binom_coeff(self._k, 2)))\n for i in range(N):\n nb_data = X[\n nbs[i,],\n ]\n thetas[i,] = self._loc_angles(X[i,], nb_data)\n return thetas\n\n def _ML_VM(self, thetas):\n sinth = np.sin(thetas)\n costh = np.cos(thetas)\n nu = np.arctan(np.sum(sinth) / np.sum(costh))\n eta = np.sqrt(np.mean(costh) ** 2 + np.mean(sinth) ** 2)\n tau = self._Ainv(eta)\n return dict(nu=nu, tau=tau)\n\n def _dancoDimEstNoCalibration(self, X, D, n_jobs=1):\n nbh_data, idx = get_nn(X, self._k + 1, n_jobs=n_jobs)\n rhos = nbh_data[:, 0] / nbh_data[:, -1]\n d_MIND_MLi = self._MIND_MLi(rhos, D)\n d_MIND_MLk = self._MIND_MLk(rhos, D, d_MIND_MLi)\n\n thetas = self._angles(X, idx[:, : self._k])\n ml_vm = list(map(self._ML_VM, thetas))\n mu_nu = np.mean([i[\"nu\"] for i in ml_vm])\n mu_tau = np.mean([i[\"tau\"] for i in ml_vm])\n if X.shape[1] == 1:\n mu_tau = 1\n\n return dict(dhat=d_MIND_MLk, mu_nu=mu_nu, mu_tau=mu_tau)\n\n def _DancoCalibrationData(self, N):\n me = dict(k=self._k, N=N, calibration_data=list(), maxdim=0)\n return me\n\n def _increaseMaxDimByOne(self, dancoCalDat):\n newdim = dancoCalDat[\"maxdim\"] + 1\n MIND_MLx_maxdim = newdim * 2 + 5\n dancoCalDat[\"calibration_data\"].append(\n self._dancoDimEstNoCalibration(\n hyperBall(\n dancoCalDat[\"N\"],\n newdim,\n 1,\n center=[0] * newdim,\n random_state=self.random_state_,\n ),\n dancoCalDat[\"k\"],\n MIND_MLx_maxdim,\n )\n )\n dancoCalDat[\"maxdim\"] = newdim\n return dancoCalDat\n\n # @staticmethod\n # def increaseMaxDimByOne_precomputedSpline(dancoCalDat,DANCo_splines):\n # newdim = dancoCalDat['maxdim'] + 1\n # dancoCalDat['calibration_data'].append({'dhat':DANCo_splines['spline_dhat'](newdim,dancoCalDat['N']),\n # 'mu_nu':DANCo_splines['spline_mu'](newdim,dancoCalDat['N']),\n # 'mu_tau':DANCo_splines['spline_tau'](newdim,dancoCalDat['N'])})\n # dancoCalDat['maxdim'] = newdim\n # return(dancoCalDat)\n\n def _computeDANCoCalibrationData(self, N):\n print(\"Computing calibration X...\\nCurrent dimension: \", end=\" \")\n cal = self._DancoCalibrationData(self._k, N)\n while cal[\"maxdim\"] < self._D:\n if cal[\"maxdim\"] % 10 == 0:\n print(cal[\"maxdim\"], end=\" \")\n cal = self._increaseMaxDimByOne(cal)\n return cal\n\n def _dancoDimEst(self, X):\n\n cal = self.calibration_data\n N = len(X)\n\n if cal is not None:\n if cal[\"k\"] != self._k:\n raise ValueError(\n \"Neighborhood parameter k = %s does not agree with neighborhood parameter of calibration data, cal$k = %s\",\n self._k,\n cal[\"k\"],\n )\n if cal[\"N\"] != N:\n raise ValueError(\n \"Number of data points N = %s does not agree with number of data points of calibration data, cal$N = %s\",\n N,\n cal[\"N\"],\n )\n\n if self.ver not in [\"DANCo\", \"DANCoFit\"]:\n return self._MIND_MLx(X, self._D)\n\n nocal = self._dancoDimEstNoCalibration(X, self._D)\n if any(np.isnan(val) for val in nocal.values()):\n return np.nan, np.nan, cal\n\n if cal is None:\n cal = self._DancoCalibrationData(N)\n\n if cal[\"maxdim\"] < self._D:\n\n if self.ver == \"DANCoFit\":\n if self.verbose:\n print(\n \"Generating DANCo calibration data from precomputed spline interpolation for cardinality 50 to 5000, k = 10, dimensions 1 to 100\"\n )\n raise ValueError(\"DANCoFit not yet implemented\")\n # load precomputed splines as a function of dimension and dataset cardinality\n # DANCo_splines = {}\n # for spl in ['spline_dhat','spline_mu','spline_tau']:\n # with open('DANCoFit/DANCo_'+spl+'.pkl', 'rb') as f:\n # DANCo_splines[spl]=pickle.load(f)\n ##compute interpolated statistics\n # while (cal['maxdim'] < self._D):\n # cal = self.increaseMaxDimByOne_precomputedSpline(cal,DANCo_splines)\n\n else:\n if self.verbose:\n print(\n \"Computing DANCo calibration data for N = {}, k = {} for dimensions {} to {}\".format(\n N, self._k, cal[\"maxdim\"] + 1, self._D\n )\n )\n\n # compute statistics\n while cal[\"maxdim\"] < self._D:\n cal = self._increaseMaxDimByOne(cal)\n\n kl = np.array([np.nan] * self._D)\n for d in range(self._D):\n kl[d] = self._KL(nocal, cal[\"calibration_data\"][d])\n\n de = np.argmin(kl) + 1\n\n if self.fractal:\n # Fitting with a cubic smoothing spline:\n if X.shape[1] > 3:\n kind = \"cubic\"\n elif X.shape[1] == 3:\n kind = \"quadratic\"\n elif X.shape[1] == 2:\n kind = \"linear\"\n\n f = interp1d(\n np.arange(1, self._D + 1),\n kl,\n kind=kind,\n bounds_error=False,\n fill_value=(1, self._D + 1),\n )\n # Locating the minima:\n de_fractal = minimize(f, de, bounds=[(1, self._D + 1)], tol=1e-3)[\"x\"]\n return de_fractal[0], kl[de - 1], cal\n else:\n return de, kl[de - 1], cal\n" ]
[ [ "numpy.log", "scipy.special.i1", "numpy.abs", "sklearn.utils.validation.check_array", "numpy.clip", "numpy.isnan", "numpy.arange", "scipy.special.i0", "numpy.arccos", "numpy.cos", "numpy.sin", "numpy.argmax", "numpy.mean", "sklearn.utils.validation.check_random_state", "numpy.argmin", "scipy.optimize.minimize", "numpy.array", "numpy.sum" ] ]
j9ac9k/signalworks
[ "ca1c9ea77f6fc6d26c1e1b3a21eb9d9465041fb5" ]
[ "signalworks/dsp.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nDigital Signal Processing\n\"\"\"\nfrom math import ceil, log2\nfrom typing import Tuple, Union\n\nimport numba\nimport numpy as np\nfrom numpy.fft import fft, ifft, irfft, rfft\nfrom scipy import signal, stats\nfrom signalworks.tracking import TimeValue, Wave\n\n# TODO: make this \"tracking\"-free (?), and all times are in samples\n\n# def segment_talkbox(a: np.ndarray,\n# length: int,\n# overlap: int = 0) -> np.ndarray:\n# # originally from talkbox.segmentaxis\n# a = np.ravel(a) # may copy\n# l = a.shape[0]\n# if overlap >= length:\n# raise ValueError(\"frames cannot overlap by more than 100%\")\n# if overlap < 0 or length <= 0:\n# raise ValueError(\"overlap must be nonnegative and length must be positive\")\n# if l < length or (l - length) % (length - overlap):\n# if l > length:\n# roundup = length + (1 + (l - length) //\n# (length - overlap)) * (length - overlap)\n# # TODO: further optimization possible\n# rounddown = length + ((l - length) // (length - overlap)) * (length - overlap)\n# else:\n# roundup = length\n# rounddown = 0\n# assert rounddown < l < roundup\n# assert roundup == rounddown + (length - overlap) or (roundup == length and rounddown == 0)\n# a = a.swapaxes(-1, 0)\n# a = a[..., :rounddown]\n# a = a.swapaxes(-1, 0)\n# l = a.shape[0]\n# if l == 0:\n# raise ValueError(\"Not enough data points to segment array\")\n# assert l >= length\n# assert (l - length) % (length - overlap) == 0\n# n = 1 + (l - length) // (length - overlap)\n# s = a.strides[0]\n# newshape = a.shape[:0] + (n, length) + a.shape[1:]\n# newstrides = a.strides[:0] + ((length - overlap) * s, s) + a.strides[1:]\n# try:\n# return np.ndarray.__new__(np.ndarray, strides=newstrides,\n# shape=newshape, buffer=a, dtype=a.dtype)\n# except TypeError:\n# import warnings\n# warnings.warn(\"Problem with ndarray creation forces copy.\")\n# a = a.copy()\n# # Shape doesn't change but strides does\n# newstrides = a.strides[:0] + ((length - overlap) * s, s) + a.strides[1:]\n# return np.ndarray.__new__(np.ndarray,\n# strides=newstrides,\n# shape=newshape,\n# buffer=a,\n# dtype=a.dtype)\n\n\n# @numba.jit((numba.int16[:], numba.int64, numba.int32), nopython=True, cache=True)\n@numba.jit(nopython=True, cache=True) # we need polymorphism here\ndef segment(x, nsize, nrate):\n if len(x) < nsize:\n F = 0\n else:\n F = (len(x) - nsize) // nrate # the number of full frames\n assert F >= 0\n X = np.empty((F, nsize), dtype=x.dtype)\n a = 0\n for f in range(F):\n X[f, :] = x[a : a + nsize]\n a += nrate\n return X\n\n\ndef frame(wav: Wave, frame_size: float, frame_rate: float) -> TimeValue:\n \"\"\"\n Given a waveform, return a timeValue track with each frame as the value and times of the center of each frame.\n times point to the center of the frame.\n Each frame will have the specified size, and t[i+1] = t[i] + rate.\n this will return as much of the signal as possible in full frames\n \"\"\"\n # def unsigned int a, f, nrate, nsize\n assert wav.duration > 0\n nsize = int(round(frame_size * wav.fs))\n nrate = int(round(frame_rate * wav.fs))\n # import time\n # tic = time.time()\n # print(\"frame timing...\")\n # if 0: # TODO: unfortunately segment doesn't allow for negative overlap, i.e. jumps\n # value = segment_talkbox(wav.value, nsize, nsize - nrate) # because overlap = nsize - nrate\n value = segment(wav.value, nsize, nrate)\n # print(f\"frame took time: {time.time() - tic}\")\n assert value.shape[1] == nsize\n time = np.array(np.arange(value.shape[0]) * nrate, dtype=np.int64) + nsize // 2\n return TimeValue(\n time, value, wav.fs, wav.duration, path=wav.path\n ) # adjust path name here?\n\n\n# @numba.jit(nopython=True, cache=True) # we need polymorphism here\ndef frame_centered(signal: np.ndarray, time: np.ndarray, frame_size: int) -> np.ndarray:\n assert time.ndim == 1\n # no further assumptions on time - doesn't have to be sorted or inside signal\n value = np.zeros((len(time), frame_size), dtype=signal.dtype)\n left_frame_size = frame_size // 2\n right_frame_size = frame_size - left_frame_size\n S = len(signal)\n for f, center in enumerate(time):\n left = center - left_frame_size\n right = center + right_frame_size\n if left >= 0 and right <= S: # make the common case fast\n value[f, :] = signal[left:right]\n else: # deal with edges on possibly both sides\n # left\n if left < 0:\n left_avail = left_frame_size + left\n else:\n left_avail = left_frame_size\n # right\n right_over = right - S\n if right_over > 0:\n right_avail = right_frame_size - right_over\n else:\n right_avail = right_frame_size\n if 0 <= center <= S:\n value[\n f, left_frame_size - left_avail : left_frame_size + right_avail\n ] = signal[center - left_avail : center + right_avail]\n assert value.shape[0] == len(time)\n assert value.shape[1] == frame_size\n return value # adjust path name here?\n\n\n@numba.jit(nopython=True, cache=True) # we need polymorphism here\ndef ola(\n frame: np.ndarray, fs: int, duration: int, frame_size: float, frame_rate: float\n) -> np.ndarray:\n nsize = int(round(frame_size * fs))\n nrate = int(round(frame_rate * fs))\n y = np.zeros(duration, dtype=np.float64)\n a = 0\n for f in range(len(frame)):\n y[a : a + nsize] += frame[f]\n a += nrate\n return y\n\n\ndef spectral_subtract(inp: Wave, frame_rate: int, silence_percentage: int) -> Wave:\n assert 0 < silence_percentage < 100\n ftr = frame(inp, frame_rate * 2, frame_rate)\n x = ftr.value * signal.hann(ftr.value.shape[1])\n X = fft(x, 2 ** nextpow2(x.shape[1]))\n M = np.abs(X)\n E = np.mean(M ** 2, axis=1)\n threshold = stats.scoreatpercentile(E, silence_percentage)\n index = np.where(E < threshold)[0]\n noise_profile = np.median(M[index], axis=0)\n M -= noise_profile\n np.clip(\n M, 0, None, out=M\n ) # limit this to a value greater than 0 to avoid -inf due to the following log\n Y = M * np.exp(1j * np.angle(X)) # DEBUG\n y = ifft(Y).real\n s = ola(y, inp.fs, inp.duration, frame_rate * 2, frame_rate)\n return Wave(s, inp.fs)\n\n\ndef spectrogram(\n wav: Wave,\n frame_size: float,\n frame_rate: float,\n window: signal.hann = signal.hann,\n NFFT: str = \"nextpow2\",\n normalized: bool = False,\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"return log-magnitude spectrogram in dB\"\"\"\n ftr = frame(wav, frame_size, frame_rate)\n x = ftr.value * window(ftr.value.shape[1])\n if NFFT == \"nextpow2\":\n NFFT = 2 ** nextpow2(x.shape[1])\n M = np.abs(rfft(x, NFFT))\n np.clip(M, 1e-12, None, out=M)\n M = np.log10(M) * 20\n if normalized:\n M = (M.T - np.min(M, axis=1)).T\n M = (M.T / np.max(M, axis=1)).T\n assert np.all(M.min(axis=1) == 0)\n assert np.all(M.max(axis=1) == 1)\n frequency = np.arange(M.shape[1]) / M.shape[1] * wav.fs / 2\n return M, ftr.time, frequency\n\n\ndef spectrogram_centered(\n wav: Wave, # used by rendering\n frame_size: float,\n time: np.ndarray,\n window: signal.hann = signal.hann,\n NFFT: str = \"nextpow2\",\n normalized: bool = False,\n) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"return log-magnitude spectrogram in dB\"\"\"\n s = wav.value / np.abs(\n np.max(wav.value)\n ) # make float by normalizing and later clipping is more uniform\n assert s.max() == 1\n ftr = frame_centered(s, time, int(round(frame_size * wav.fs)))\n assert ftr.dtype == np.float\n ftr *= window(ftr.shape[1])\n if NFFT == \"nextpow2\":\n NFFT = 2 ** nextpow2(ftr.shape[1])\n M = np.abs(rfft(ftr, NFFT))\n np.clip(M, 1e-16, None, out=M)\n M[:] = np.log10(M) * 20\n if normalized:\n M[:] = (M.T - np.min(M, axis=1)).T\n M[:] = (M.T / np.max(M, axis=1)).T\n # assert np.all(M.min(axis=1) == 0)\n # assert np.all(M.max(axis=1) == 1)\n frequency = np.arange(M.shape[1]) / M.shape[1] * wav.fs / 2\n return M, frequency\n\n\ndef correlate_fft(X: np.ndarray) -> np.ndarray:\n \"\"\"correlation for feature matrix\"\"\"\n assert X.ndim == 2\n D = X.shape[1]\n R = irfft(np.abs(rfft(X, 2 ** nextpow2(2 * D - 1))) ** 2)[:, :D]\n # show relationship to related methods\n assert np.allclose(R[0], np.correlate(X[0], X[0], mode=\"full\")[D - 1 :])\n # assert np.allclose(r, np.convolve(x, x[::-1], mode='full')[n - 1:])\n # from scipy.signal import fftconvolve\n # assert np.allclose(r, fftconvolve(x, x[::-1], mode='full')[n - 1:])\n return R\n\n\ndef correlogram(\n wav: Wave, frame_size: float, frame_rate: float, normalize: bool = True\n) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n assert wav.dtype == np.float64\n # t, x = frame(wav, frame_size, frame_rate)\n ftr = frame(wav, frame_size, frame_rate)\n M, D = ftr.value.shape\n R = correlate_fft(ftr.value)\n # if 1:\n # # FFT order must be at least 2*len(x)-1 and should be a power of 2\n # R = irfft(np.abs(rfft(ftr.value, 2 ** nextpow2(2 * D - 1))) ** 2)[:, D]\n # else:\n # index = np.arange(int(np.round(D / 2)), D)\n # R = np.empty((M, len(index)), dtype=np.float64)\n # for m in range(M):\n # signal = ftr.value[m]\n # R[m, :] = np.correlate(signal, signal, mode='same')[index] # TODO: use fft2 here instead\n if normalize:\n R[:, 1:] /= np.tile(\n R[:, 0], (R.shape[1] - 1, 1)\n ).T # keep energy in zero-th coeff?\n frequency = np.r_[np.nan, wav.fs / np.arange(1, R.shape[1])]\n return R, ftr.time, frequency\n\n\ndef nextpow2(i: Union[int, float]) -> int:\n \"\"\"returns the first P such that 2**P >= abs(N)\"\"\"\n return int(ceil(log2(i)))\n\n\n#\n#\n# def world(wave: Wave) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n# x = wave.value / (2 ** 15)\n# fs = wave.fs\n# _f0, t = pw.dio(x, fs) # raw pitch extractor\n# f0 = pw.stonemask(x, _f0, t, fs) # pitch refinement\n# sp = pw.cheaptrick(x, f0, t, fs) # extract smoothed spectrogram\n# return sp, f0, t\n" ]
[ [ "numpy.abs", "numpy.fft.rfft", "numpy.clip", "numpy.min", "numpy.arange", "numpy.median", "numpy.tile", "numpy.fft.ifft", "numpy.max", "scipy.stats.scoreatpercentile", "numpy.mean", "numpy.log10", "scipy.signal.hann", "numpy.angle", "numpy.correlate", "numpy.zeros", "numpy.where", "numpy.empty" ] ]
pha-nguyen/siam-mot
[ "868c244a8d0d6aa79b1fbaf09c226fa0335307f3" ]
[ "siammot/modelling/track_head/EMM/xcorr.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef xcorr_slow(x, kernel):\n \"\"\"for loop to calculate cross correlation, slow version\n \"\"\"\n batch = x.size()[0]\n out = []\n for i in range(batch):\n px = x[i]\n pk = kernel[i]\n px = px.view(1, -1, px.size()[1], px.size()[2])\n pk = pk.view(1, -1, pk.size()[1], pk.size()[2])\n po = F.conv2d(px, pk)\n out.append(po)\n out = torch.cat(out, 0)\n return out\n\n\ndef xcorr_fast(x, kernel):\n \"\"\"group conv2d to calculate cross correlation, fast version\n \"\"\"\n batch = kernel.size()[0]\n pk = kernel.view(-1, x.size()[1], kernel.size()[2], kernel.size()[3])\n px = x.view(1, -1, x.size()[2], x.size()[3])\n po = F.conv2d(px, pk, groups=batch)\n po = po.view(batch, -1, po.size()[2], po.size()[3])\n return po\n\n\ndef xcorr_depthwise(x, kernel):\n \"\"\"depthwise cross correlation\n \"\"\"\n batch = kernel.size(0)\n channel = kernel.size(1)\n x = x.view(1, batch*channel, x.size(2), x.size(3))\n kernel = kernel.view(batch*channel, 1, kernel.size(2), kernel.size(3))\n out = F.conv2d(x, kernel, groups=batch*channel)\n out = out.view(batch, channel, out.size(2), out.size(3))\n return out" ]
[ [ "torch.nn.functional.conv2d", "torch.cat" ] ]
wilsonjwcsu/contrastive-unpaired-translation
[ "d08a4b08ed8247a2cc897ba4d9bfbdb3487db7fa" ]
[ "models/cut_model.py" ]
[ "import numpy as np\nimport torch\nfrom .base_model import BaseModel\nfrom . import networks\nfrom .patchnce import PatchNCELoss\nimport util.util as util\nfrom scipy.stats import pearsonr\n\n\nclass CUTModel(BaseModel):\n \"\"\" This class implements CUT and FastCUT model, described in the paper\n Contrastive Learning for Unpaired Image-to-Image Translation\n Taesung Park, Alexei A. Efros, Richard Zhang, Jun-Yan Zhu\n ECCV, 2020\n\n The code borrows heavily from the PyTorch implementation of CycleGAN\n https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\n \"\"\"\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n \"\"\" Configures options specific for CUT model\n \"\"\"\n parser.add_argument('--CUT_mode', type=str, default=\"CUT\", choices='(CUT, cut, FastCUT, fastcut)')\n\n parser.add_argument('--lambda_GAN', type=float, default=1.0, help='weight for GAN loss:GAN(G(X))')\n parser.add_argument('--lambda_NCE', type=float, default=1.0, help='weight for NCE loss: NCE(G(X), X)')\n parser.add_argument('--nce_idt', type=util.str2bool, nargs='?', const=True, default=False, help='use NCE loss for identity mapping: NCE(G(Y), Y))')\n parser.add_argument('--nce_paired', type=util.str2bool, nargs='?', const=True, default=False, help='calculate NCE loss between fake_B and real_B')\n parser.add_argument('--nce_layers', type=str, default='0,4,8,12,16', help='compute NCE loss on which layers')\n parser.add_argument('--nce_includes_all_negatives_from_minibatch',\n type=util.str2bool, nargs='?', const=True, default=False,\n help='(used for single image translation) If True, include the negatives from the other samples of the minibatch when computing the contrastive loss. Please see models/patchnce.py for more details.')\n parser.add_argument('--netF', type=str, default='mlp_sample', choices=['sample', 'reshape', 'mlp_sample'], help='how to downsample the feature map')\n parser.add_argument('--netF_nc', type=int, default=256)\n parser.add_argument('--nce_T', type=float, default=0.07, help='temperature for NCE loss')\n parser.add_argument('--num_patches', type=int, default=256, help='number of patches per layer')\n parser.add_argument('--flip_equivariance',\n type=util.str2bool, nargs='?', const=True, default=False,\n help=\"Enforce flip-equivariance as additional regularization. It's used by FastCUT, but not CUT\")\n parser.add_argument('--selective_backprop', type=float, default=1.0, help='Pearson correlation threshold for witholding a training sample from backprop. Applies to paired image training only.')\n parser.add_argument('--conditional_D', type=util.str2bool, nargs='?', const=True, default=False, help='condition discriminator on X. Similar to pix2pix.')\n parser.add_argument('--lambda_L1', type=float, default=0.0, help='weight for L1 loss: L1(G(X), Y)')\n parser.add_argument('--lambda_PAN', type=float, default=0.0, help='weight for perceptual loss (discriminator embedding) for paired datasets')\n parser.add_argument('--pan_layers', type=str, default='2,11,17,23', help='compute perceptual loss on which layers')\n parser.add_argument('--pan_lambdas', type=str, default='5,1.5,1.5,1', help='weighting of each perceptual loss feature')\n\n parser.set_defaults(pool_size=0) # no image pooling\n\n opt, _ = parser.parse_known_args()\n\n # Set default parameters for CUT and FastCUT\n if opt.CUT_mode.lower() == \"cut\":\n parser.set_defaults(nce_idt=True, lambda_NCE=1.0)\n elif opt.CUT_mode.lower() == \"fastcut\":\n parser.set_defaults(\n nce_idt=False, lambda_NCE=10.0, flip_equivariance=True,\n n_epochs=150, n_epochs_decay=50\n )\n else:\n raise ValueError(opt.CUT_mode)\n\n return parser\n\n def __init__(self, opt):\n BaseModel.__init__(self, opt)\n\n # specify the training losses you want to print out.\n # The training/test scripts will call <BaseModel.get_current_losses>\n if opt.netD == 'none':\n self.loss_names = ['NCE']\n else:\n self.loss_names = ['G_GAN', 'D_real', 'D_fake', 'G', 'NCE']\n self.visual_names = ['real_A', 'fake_B', 'real_B']\n self.nce_layers = [int(i) for i in self.opt.nce_layers.split(',')]\n self.pan_layers = [int(i) for i in self.opt.pan_layers.split(',')]\n self.pan_lambdas = [float(i) for i in self.opt.pan_lambdas.split(',')]\n\n if opt.nce_idt and self.isTrain:\n self.loss_names += ['NCE_Y']\n self.visual_names += ['idt_B']\n\n if opt.selective_backprop < 1.0:\n self.loss_names += ['R']\n\n if opt.lambda_L1 > 0.0:\n self.loss_names += ['L1']\n\n if opt.lambda_PAN > 0.0:\n self.loss_names += ['PAN']\n self.loss_names += ['PAN_D']\n \n\n if self.isTrain:\n if opt.netD == 'none':\n self.model_names = ['G','F']\n else:\n self.model_names = ['G', 'F', 'D']\n else: # during test time, only load G\n self.model_names = ['G']\n\n # define networks (both generator and discriminator)\n self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.normG, not opt.no_dropout, opt.init_type, opt.init_gain, opt.no_antialias, opt.no_antialias_up, self.gpu_ids, opt)\n self.netF = networks.define_F(opt.input_nc, opt.netF, opt.normG, not opt.no_dropout, opt.init_type, opt.init_gain, opt.no_antialias, self.gpu_ids, opt)\n\n if self.isTrain:\n if opt.conditional_D:\n d_nc = opt.input_nc + opt.output_nc\n else:\n d_nc = opt.output_nc\n\n if not opt.netD=='none':\n self.netD = networks.define_D(d_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.normD, opt.init_type, opt.init_gain, opt.no_antialias, self.gpu_ids, opt)\n\n # define loss functions\n self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)\n self.criterionNCE = []\n\n for nce_layer in self.nce_layers:\n self.criterionNCE.append(PatchNCELoss(opt).to(self.device))\n\n self.criterionIdt = torch.nn.L1Loss().to(self.device)\n \n if opt.lambda_L1 > 0.0:\n self.criterionL1 = torch.nn.L1Loss().to(self.device)\n\n self.criterionPAN = []\n for pan_layer in self.pan_layers:\n self.criterionPAN.append(torch.nn.L1Loss().to(self.device))\n \n if opt.optim_G=='adam':\n self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr_G, betas=(opt.beta1, opt.beta2), weight_decay=opt.weight_decay)\n elif opt.optim_G=='sgd':\n self.optimizer_G = torch.optim.SGD(self.netG.parameters(), lr=opt.lr_G, momentum=opt.beta1, weight_decay=opt.weight_decay, nesterov = (not (opt.beta1==0 )) )\n self.optimizers.append(self.optimizer_G)\n\n if not opt.netD=='none':\n self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=opt.lr_D, betas=(opt.beta1, opt.beta2))\n self.optimizers.append(self.optimizer_D)\n\n def data_dependent_initialize(self, data):\n \"\"\"\n The feature network netF is defined in terms of the shape of the intermediate, extracted\n features of the encoder portion of netG. Because of this, the weights of netF are\n initialized at the first feedforward pass with some input images.\n Please also see PatchSampleF.create_mlp(), which is called at the first forward() call.\n \"\"\"\n self.set_input(data)\n bs_per_gpu = self.real_A.size(0) // max(len(self.opt.gpu_ids), 1)\n self.real_A = self.real_A[:bs_per_gpu]\n self.real_B = self.real_B[:bs_per_gpu]\n self.forward() # compute fake images: G(A)\n if self.opt.isTrain:\n if not self.opt.netD=='none':\n self.compute_D_loss().backward() # calculate gradients for D\n self.compute_G_loss().backward() # calculate graidents for G\n if self.opt.lambda_NCE > 0.0:\n self.optimizer_F = torch.optim.Adam(self.netF.parameters(), lr=self.opt.lr_G, betas=(self.opt.beta1, self.opt.beta2))\n self.optimizers.append(self.optimizer_F)\n\n def optimize_parameters(self):\n # forward\n self.forward()\n\n if self.opt.selective_backprop < 1.0:\n r, p = pearsonr(self.fake_B.detach().flatten().cpu().numpy(), self.real_B.detach().flatten().cpu().numpy())\n self.loss_R = r\n else:\n r = 0.0\n\n\n if r < self.opt.selective_backprop:\n # update D\n if not self.opt.netD=='none':\n self.set_requires_grad(self.netD, True)\n self.optimizer_D.zero_grad()\n self.loss_D = self.compute_D_loss()\n self.loss_D.backward()\n self.optimizer_D.step()\n\n # update G\n if not self.opt.netD=='none':\n self.set_requires_grad(self.netD, False)\n self.optimizer_G.zero_grad()\n if self.opt.netF == 'mlp_sample' and self.opt.lambda_NCE > 0.0:\n self.optimizer_F.zero_grad()\n self.loss_G = self.compute_G_loss()\n self.loss_G.backward()\n self.optimizer_G.step()\n if self.opt.netF == 'mlp_sample' and self.opt.lambda_NCE > 0.0:\n self.optimizer_F.step()\n\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n Parameters:\n input (dict): include the data itself and its metadata information.\n The option 'direction' can be used to swap domain A and domain B.\n \"\"\"\n AtoB = self.opt.direction == 'AtoB'\n self.real_A = input['A' if AtoB else 'B'].to(self.device)\n self.real_B = input['B' if AtoB else 'A'].to(self.device)\n self.image_paths = input['A_paths' if AtoB else 'B_paths']\n\n if self.opt.instance_noise_x > 0.0:\n #self.real_A += torch.normal(mean=0, std=self.opt.instance_noise_x, size=self.real_A.shape).to(self.device)\n self.real_A += torch.normal(mean=0, std=np.random.rand()*self.opt.instance_noise_x, size=self.real_A.shape).to(self.device)\n\n def forward(self):\n \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\"\"\"\n self.real = torch.cat((self.real_A, self.real_B), dim=0) if self.opt.nce_idt and self.opt.isTrain else self.real_A\n if self.opt.flip_equivariance:\n self.flipped_for_equivariance = self.opt.isTrain and (np.random.random() < 0.5)\n if self.flipped_for_equivariance:\n self.real = torch.flip(self.real, [3])\n\n self.fake = self.netG(self.real)\n self.fake_B = self.fake[:self.real_A.size(0)]\n if self.opt.nce_idt:\n self.idt_B = self.fake[self.real_A.size(0):]\n\n def compute_D_loss(self):\n \"\"\"Calculate GAN loss for the discriminator\"\"\"\n if self.opt.conditional_D:\n fake = torch.cat((self.real_A, self.fake_B.detach()),1)\n else:\n fake = self.fake_B.detach()\n # Fake; stop backprop to the generator by detaching fake_B\n pred_fake = self.netD(fake)\n self.loss_D_fake = self.criterionGAN(pred_fake, False).mean()\n\n # Real\n if self.opt.conditional_D:\n real = torch.cat((self.real_A, self.real_B),1)\n else:\n real = self.real_B\n self.pred_real = self.netD(real)\n loss_D_real = self.criterionGAN(self.pred_real, True)\n self.loss_D_real = loss_D_real.mean()\n\n # combine loss and calculate gradients\n self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5\n\n\n # PAN loss / contrastive update\n if self.opt.lambda_PAN > 0.0:\n self.loss_PAN_D = torch.nn.functional.relu(3.0 - self.calculate_PAN_loss(real, fake))\n self.loss_D += self.loss_PAN_D\n\n return self.loss_D\n\n def compute_G_loss(self):\n \"\"\"Calculate GAN and NCE loss for the generator\"\"\"\n # First, G(A) should fake the discriminator\n if not self.opt.netD=='none':\n if self.opt.lambda_GAN > 0.0:\n \n if self.opt.conditional_D:\n fake = torch.cat((self.real_A, self.fake_B),1)\n else:\n fake = self.fake_B\n\n pred_fake = self.netD(fake)\n self.loss_G_GAN = self.criterionGAN(pred_fake, True).mean() * self.opt.lambda_GAN\n else:\n self.loss_G_GAN = 0.0\n else:\n self.loss_G_GAN= 0.0\n\n if self.opt.lambda_NCE > 0.0:\n if self.opt.nce_paired:\n self.loss_NCE = self.calculate_NCE_loss(self.real_B, self.fake_B)\n else:\n self.loss_NCE = self.calculate_NCE_loss(self.real_A, self.fake_B)\n else:\n self.loss_NCE, self.loss_NCE_bd = 0.0, 0.0\n\n if self.opt.nce_idt and self.opt.lambda_NCE > 0.0:\n self.loss_NCE_Y = self.calculate_NCE_loss(self.real_B, self.idt_B)\n loss_NCE_both = (self.loss_NCE + self.loss_NCE_Y) * 0.5\n else:\n loss_NCE_both = self.loss_NCE\n\n self.loss_G = self.loss_G_GAN + loss_NCE_both\n\n if self.opt.lambda_L1 > 0.0:\n self.loss_L1 = self.criterionL1(self.real_B, self.fake_B)*self.opt.lambda_L1\n\n self.loss_G += self.loss_L1\n\n if self.opt.lambda_PAN > 0.0:\n self.loss_PAN = self.calculate_PAN_loss(self.real_B, self.fake_B)\n\n self.loss_G += self.loss_PAN\n\n return self.loss_G\n\n def calculate_NCE_loss(self, src, tgt):\n n_layers = len(self.nce_layers)\n feat_q = self.netG(tgt, self.nce_layers, encode_only=True)\n\n if self.opt.flip_equivariance and self.flipped_for_equivariance:\n feat_q = [torch.flip(fq, [3]) for fq in feat_q]\n\n feat_k = self.netG(src, self.nce_layers, encode_only=True)\n feat_k_pool, sample_ids = self.netF(feat_k, self.opt.num_patches, None)\n feat_q_pool, _ = self.netF(feat_q, self.opt.num_patches, sample_ids)\n\n total_nce_loss = 0.0\n for f_q, f_k, crit, nce_layer in zip(feat_q_pool, feat_k_pool, self.criterionNCE, self.nce_layers):\n loss = crit(f_q, f_k) * self.opt.lambda_NCE\n total_nce_loss += loss.mean()\n\n return total_nce_loss / n_layers\n\n def calculate_PAN_loss(self, src, tgt):\n n_layers = len(self.pan_layers)\n feat_q = self.netD(tgt, self.pan_layers, encode_only=True)\n\n if self.opt.flip_equivariance and self.flipped_for_equivariance:\n feat_q = [torch.flip(fq, [3]) for fq in feat_q]\n\n feat_k = self.netD(src, self.pan_layers, encode_only=True)\n \n total_pan_loss = 0.0\n for f_q, f_k, crit, pan_layer, pan_lambda in zip(feat_q, feat_k, self.criterionPAN, self.nce_layers, self.pan_lambdas):\n #print('f_q: ' + str(f_q.shape))\n #print('f_k: ' + str(f_k.shape))\n loss = crit(f_q, f_k) * self.opt.lambda_PAN * pan_lambda\n total_pan_loss += loss\n\n return total_pan_loss / n_layers\n" ]
[ [ "numpy.random.random", "torch.cat", "numpy.random.rand", "torch.flip", "torch.nn.L1Loss" ] ]
zhuangzi926/KnowledgeDistillation-pytorch
[ "4785bd9afa5d79a744c127851e316caf8469a10e" ]
[ "nets/resnet.py" ]
[ "\"\"\"\n Ref: https://github.com/huyvnphan/PyTorch_CIFAR10\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport os\nimport sys\n\nsys.path.append(\"..\")\nimport settings\nimport utils\n\n__all__ = [\n \"ResNet\",\n \"resnet18\",\n \"resnet34\",\n \"resnet50\",\n \"resnet101\",\n \"resnet152\",\n \"resnext50_32x4d\",\n \"resnext101_32x8d\",\n]\n\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(\n in_planes,\n out_planes,\n kernel_size=3,\n stride=stride,\n padding=dilation,\n groups=groups,\n bias=False,\n dilation=dilation,\n )\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(\n self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n groups=1,\n base_width=64,\n dilation=1,\n norm_layer=None,\n ):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError(\"BasicBlock only supports groups=1 and base_width=64\")\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(\n self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n groups=1,\n base_width=64,\n dilation=1,\n norm_layer=None,\n ):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.0)) * groups\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = conv3x3(width, width, stride, groups, dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = conv1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(\n self,\n block,\n layers,\n num_classes=10,\n zero_init_residual=False,\n groups=1,\n width_per_group=64,\n replace_stride_with_dilation=None,\n norm_layer=None,\n ):\n super(ResNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\n \"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation)\n )\n self.groups = groups\n self.base_width = width_per_group\n\n ## CIFAR10: kernel_size 7 -> 3, stride 2 -> 1, padding 3->1\n ## MNIST: input channel num 3 -> 1\n self.conv1 = nn.Conv2d(\n settings.IMG_CHANNEL, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False\n )\n ## END\n\n self.bn1 = norm_layer(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer1.register_forward_hook(self.get_activation(\"layer1\"))\n self.layer2 = self._make_layer(\n block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]\n )\n \n # Get intermediate output\n self.layer2.register_forward_hook(self.get_activation(\"layer2\"))\n\n self.layer3 = self._make_layer(\n block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]\n )\n\n self.layer3.register_forward_hook(self.get_activation(\"layer3\"))\n\n self.layer4 = self._make_layer(\n block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]\n )\n\n self.layer4.register_forward_hook(self.get_activation(\"layer4\"))\n\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode=\"fan_out\", nonlinearity=\"relu\")\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n self.activation = {}\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(\n block(\n self.inplanes,\n planes,\n stride,\n downsample,\n self.groups,\n self.base_width,\n previous_dilation,\n norm_layer,\n )\n )\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(\n block(\n self.inplanes,\n planes,\n groups=self.groups,\n base_width=self.base_width,\n dilation=self.dilation,\n norm_layer=norm_layer,\n )\n )\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.reshape(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n def get_activation(self, name):\n def hook(model, input, output):\n self.activation[name] = output.detach()\n\n return hook\n\n\ndef _resnet(arch, block, layers, pretrained, progress, device, **kwargs):\n model = ResNet(block, layers, **kwargs)\n if pretrained:\n script_dir = os.path.dirname(__file__)\n state_dict = torch.load(\n script_dir + \"/state_dicts/\" + arch + \".pt\", map_location=device\n )\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet18(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet(\n \"resnet18\", BasicBlock, [2, 2, 2, 2], pretrained, progress, device, **kwargs\n )\n\n\ndef resnet34(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet(\n \"resnet34\", BasicBlock, [3, 4, 6, 3], pretrained, progress, device, **kwargs\n )\n\n\ndef resnet50(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet(\n \"resnet50\", Bottleneck, [3, 4, 6, 3], pretrained, progress, device, **kwargs\n )\n\n\ndef resnet101(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet(\n \"resnet101\", Bottleneck, [3, 4, 23, 3], pretrained, progress, device, **kwargs\n )\n\n\ndef resnet152(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet(\n \"resnet152\", Bottleneck, [3, 8, 36, 3], pretrained, progress, device, **kwargs\n )\n\n\ndef resnext50_32x4d(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNeXt-50 32x4d model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n kwargs[\"groups\"] = 32\n kwargs[\"width_per_group\"] = 4\n return _resnet(\n \"resnext50_32x4d\",\n Bottleneck,\n [3, 4, 6, 3],\n pretrained,\n progress,\n device,\n **kwargs\n )\n\n\ndef resnext101_32x8d(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n \"\"\"Constructs a ResNeXt-101 32x8d model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n kwargs[\"groups\"] = 32\n kwargs[\"width_per_group\"] = 8\n return _resnet(\n \"resnext101_32x8d\",\n Bottleneck,\n [3, 4, 23, 3],\n pretrained,\n progress,\n device,\n **kwargs\n )\n\n\nif __name__ == \"__main__\":\n device = utils.config_gpu()\n model = resnet50().to(device)\n data = torch.arange(3*32*32, dtype=torch.float).view(1, 3, 32, 32).to(device)\n # data = torch.arange(28*28*1, dtype=torch.float).view(1, 1, 28, 28).to(device)\n model(data)\n print(model.activation[\"layer1\"].shape)\n print(model.activation[\"layer2\"].shape)\n print(model.activation[\"layer3\"].shape)\n print(model.activation[\"layer4\"].shape)" ]
[ [ "torch.nn.Sequential", "torch.load", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.AdaptiveAvgPool2d", "torch.arange", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
seinsinnes/pynndescent
[ "e71d8e7ad5d7749d3e22ac969e6b7a9391d14c20" ]
[ "pynndescent/tests/test_pynndescent_.py" ]
[ "import os\nimport io\nimport re\nimport pytest\nfrom contextlib import redirect_stdout\n\nimport numpy as np\nfrom sklearn.neighbors import KDTree\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import normalize\nimport pickle\nimport joblib\n\nfrom pynndescent import NNDescent, PyNNDescentTransformer\n\n\ndef test_nn_descent_neighbor_accuracy(nn_data, seed):\n knn_indices, _ = NNDescent(\n nn_data, \"euclidean\", {}, 10, random_state=np.random.RandomState(seed)\n )._neighbor_graph\n\n tree = KDTree(nn_data)\n true_indices = tree.query(nn_data, 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(nn_data.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (nn_data.shape[0] * 10)\n assert percent_correct >= 0.98, (\n \"NN-descent did not get 99% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_angular_nn_descent_neighbor_accuracy(nn_data, seed):\n knn_indices, _ = NNDescent(\n nn_data, \"cosine\", {}, 10, random_state=np.random.RandomState(seed)\n )._neighbor_graph\n\n angular_data = normalize(nn_data, norm=\"l2\")\n tree = KDTree(angular_data)\n true_indices = tree.query(angular_data, 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(nn_data.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (nn_data.shape[0] * 10)\n assert percent_correct >= 0.98, (\n \"NN-descent did not get 99% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_sparse_nn_descent_neighbor_accuracy(sparse_nn_data, seed):\n knn_indices, _ = NNDescent(\n sparse_nn_data, \"euclidean\", n_neighbors=20, random_state=None\n )._neighbor_graph\n\n tree = KDTree(sparse_nn_data.toarray())\n true_indices = tree.query(sparse_nn_data.toarray(), 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(sparse_nn_data.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (sparse_nn_data.shape[0] * 10)\n assert percent_correct >= 0.85, (\n \"Sparse NN-descent did not get 95% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_sparse_angular_nn_descent_neighbor_accuracy(sparse_nn_data):\n knn_indices, _ = NNDescent(\n sparse_nn_data, \"cosine\", {}, 20, random_state=None\n )._neighbor_graph\n\n angular_data = normalize(sparse_nn_data, norm=\"l2\").toarray()\n tree = KDTree(angular_data)\n true_indices = tree.query(angular_data, 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(sparse_nn_data.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (sparse_nn_data.shape[0] * 10)\n assert percent_correct >= 0.85, (\n \"Sparse angular NN-descent did not get 98% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_nn_descent_query_accuracy(nn_data):\n nnd = NNDescent(nn_data[200:], \"euclidean\", n_neighbors=10, random_state=None)\n knn_indices, _ = nnd.query(nn_data[:200], k=10, epsilon=0.2)\n\n tree = KDTree(nn_data[200:])\n true_indices = tree.query(nn_data[:200], 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(true_indices.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (true_indices.shape[0] * 10)\n assert percent_correct >= 0.95, (\n \"NN-descent query did not get 95% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_nn_descent_query_accuracy_angular(nn_data):\n nnd = NNDescent(nn_data[200:], \"cosine\", n_neighbors=30, random_state=None)\n knn_indices, _ = nnd.query(nn_data[:200], k=10, epsilon=0.32)\n\n nn = NearestNeighbors(metric=\"cosine\").fit(nn_data[200:])\n true_indices = nn.kneighbors(nn_data[:200], n_neighbors=10, return_distance=False)\n\n num_correct = 0.0\n for i in range(true_indices.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (true_indices.shape[0] * 10)\n assert percent_correct >= 0.95, (\n \"NN-descent query did not get 95% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_sparse_nn_descent_query_accuracy(sparse_nn_data):\n nnd = NNDescent(\n sparse_nn_data[200:], \"euclidean\", n_neighbors=15, random_state=None\n )\n knn_indices, _ = nnd.query(sparse_nn_data[:200], k=10, epsilon=0.24)\n\n tree = KDTree(sparse_nn_data[200:].toarray())\n true_indices = tree.query(sparse_nn_data[:200].toarray(), 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(true_indices.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (true_indices.shape[0] * 10)\n assert percent_correct >= 0.95, (\n \"Sparse NN-descent query did not get 95% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_sparse_nn_descent_query_accuracy_angular(sparse_nn_data):\n nnd = NNDescent(sparse_nn_data[200:], \"cosine\", n_neighbors=50, random_state=None)\n knn_indices, _ = nnd.query(sparse_nn_data[:200], k=10, epsilon=0.36)\n\n nn = NearestNeighbors(metric=\"cosine\").fit(sparse_nn_data[200:].toarray())\n true_indices = nn.kneighbors(\n sparse_nn_data[:200].toarray(), n_neighbors=10, return_distance=False\n )\n\n num_correct = 0.0\n for i in range(true_indices.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (true_indices.shape[0] * 10)\n assert percent_correct >= 0.95, (\n \"Sparse NN-descent query did not get 95% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_transformer_equivalence(nn_data):\n N_NEIGHBORS = 15\n EPSILON = 0.15\n train = nn_data[:400]\n test = nn_data[:200]\n\n # Note we shift N_NEIGHBORS to conform to sklearn's KNeighborTransformer defn\n nnd = NNDescent(\n data=train, n_neighbors=N_NEIGHBORS + 1, random_state=42, compressed=False\n )\n indices, dists = nnd.query(test, k=N_NEIGHBORS, epsilon=EPSILON)\n sort_idx = np.argsort(indices, axis=1)\n indices_sorted = np.vstack(\n [indices[i, sort_idx[i]] for i in range(sort_idx.shape[0])]\n )\n dists_sorted = np.vstack([dists[i, sort_idx[i]] for i in range(sort_idx.shape[0])])\n\n # Note we shift N_NEIGHBORS to conform to sklearn' KNeighborTransformer defn\n transformer = PyNNDescentTransformer(\n n_neighbors=N_NEIGHBORS, search_epsilon=EPSILON, random_state=42\n ).fit(train, compress_index=False)\n Xt = transformer.transform(test).sorted_indices()\n\n assert np.all(Xt.indices == indices_sorted.flatten())\n assert np.allclose(Xt.data, dists_sorted.flat)\n\n\ndef test_random_state_none(nn_data, spatial_data):\n knn_indices, _ = NNDescent(\n nn_data, \"euclidean\", {}, 10, random_state=None\n )._neighbor_graph\n\n tree = KDTree(nn_data)\n true_indices = tree.query(nn_data, 10, return_distance=False)\n\n num_correct = 0.0\n for i in range(nn_data.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n percent_correct = num_correct / (spatial_data.shape[0] * 10)\n assert percent_correct >= 0.99, (\n \"NN-descent did not get 99% \" \"accuracy on nearest neighbors\"\n )\n\n\ndef test_deterministic():\n seed = np.random.RandomState(42)\n\n x1 = seed.normal(0, 100, (1000, 50))\n x2 = seed.normal(0, 100, (1000, 50))\n\n index1 = NNDescent(x1, random_state=np.random.RandomState(42))\n neighbors1, distances1 = index1.query(x2)\n\n index2 = NNDescent(x1, random_state=np.random.RandomState(42))\n neighbors2, distances2 = index2.query(x2)\n\n np.testing.assert_equal(neighbors1, neighbors2)\n np.testing.assert_equal(distances1, distances2)\n\n\n# This tests a recursion error on cosine metric reported at:\n# https://github.com/lmcinnes/umap/issues/99\n# graph_data used is a cut-down version of that provided by @scharron\n# It contains lots of all-zero vectors and some other duplicates\ndef test_rp_trees_should_not_stack_overflow_with_duplicate_data(seed, cosine_hang_data):\n\n n_neighbors = 10\n knn_indices, _ = NNDescent(\n cosine_hang_data,\n \"cosine\",\n {},\n n_neighbors,\n random_state=np.random.RandomState(seed),\n n_trees=20,\n )._neighbor_graph\n\n for i in range(cosine_hang_data.shape[0]):\n assert len(knn_indices[i]) == len(\n np.unique(knn_indices[i])\n ), \"Duplicate graph_indices in knn graph\"\n\n\ndef test_deduplicated_data_behaves_normally(seed, cosine_hang_data):\n\n data = np.unique(cosine_hang_data, axis=0)\n data = data[~np.all(data == 0, axis=1)]\n data = data[:1000]\n\n n_neighbors = 10\n knn_indices, _ = NNDescent(\n data,\n \"cosine\",\n {},\n n_neighbors,\n random_state=np.random.RandomState(seed),\n n_trees=20,\n )._neighbor_graph\n\n for i in range(data.shape[0]):\n assert len(knn_indices[i]) == len(\n np.unique(knn_indices[i])\n ), \"Duplicate graph_indices in knn graph\"\n\n angular_data = normalize(data, norm=\"l2\")\n tree = KDTree(angular_data)\n true_indices = tree.query(angular_data, n_neighbors, return_distance=False)\n\n num_correct = 0\n for i in range(data.shape[0]):\n num_correct += np.sum(np.in1d(true_indices[i], knn_indices[i]))\n\n proportion_correct = num_correct / (data.shape[0] * n_neighbors)\n assert proportion_correct >= 0.95, (\n \"NN-descent did not get 95%\" \" accuracy on nearest neighbors\"\n )\n\n\ndef test_output_when_verbose_is_true(spatial_data, seed):\n out = io.StringIO()\n with redirect_stdout(out):\n _ = NNDescent(\n data=spatial_data,\n metric=\"euclidean\",\n metric_kwds={},\n n_neighbors=4,\n random_state=np.random.RandomState(seed),\n n_trees=5,\n n_iters=2,\n verbose=True,\n )\n output = out.getvalue()\n assert re.match(\"^.*5 trees\", output, re.DOTALL)\n assert re.match(\"^.*2 iterations\", output, re.DOTALL)\n\n\ndef test_no_output_when_verbose_is_false(spatial_data, seed):\n out = io.StringIO()\n with redirect_stdout(out):\n _ = NNDescent(\n data=spatial_data,\n metric=\"euclidean\",\n metric_kwds={},\n n_neighbors=4,\n random_state=np.random.RandomState(seed),\n n_trees=5,\n n_iters=2,\n verbose=False,\n )\n output = out.getvalue().strip()\n assert len(output) == 0\n\n\n# same as the previous two test, but this time using the PyNNDescentTransformer\n# interface\ndef test_transformer_output_when_verbose_is_true(spatial_data, seed):\n out = io.StringIO()\n with redirect_stdout(out):\n _ = PyNNDescentTransformer(\n n_neighbors=4,\n metric=\"euclidean\",\n metric_kwds={},\n random_state=np.random.RandomState(seed),\n n_trees=5,\n n_iters=2,\n verbose=True,\n ).fit_transform(spatial_data)\n output = out.getvalue()\n assert re.match(\"^.*5 trees\", output, re.DOTALL)\n assert re.match(\"^.*2 iterations\", output, re.DOTALL)\n\n\ndef test_transformer_output_when_verbose_is_false(spatial_data, seed):\n out = io.StringIO()\n with redirect_stdout(out):\n _ = PyNNDescentTransformer(\n n_neighbors=4,\n metric=\"standardised_euclidean\",\n metric_kwds={\"sigma\": np.ones(spatial_data.shape[1])},\n random_state=np.random.RandomState(seed),\n n_trees=5,\n n_iters=2,\n verbose=False,\n ).fit_transform(spatial_data)\n output = out.getvalue().strip()\n assert len(output) == 0\n\n\ndef test_pickle_unpickle():\n seed = np.random.RandomState(42)\n\n x1 = seed.normal(0, 100, (1000, 50))\n x2 = seed.normal(0, 100, (1000, 50))\n\n index1 = NNDescent(\n x1,\n \"euclidean\",\n {},\n 10,\n random_state=None,\n )\n neighbors1, distances1 = index1.query(x2)\n\n pickle.dump(index1, open(\"test_tmp.pkl\", \"wb\"))\n index2 = pickle.load(open(\"test_tmp.pkl\", \"rb\"))\n os.remove(\"test_tmp.pkl\")\n\n neighbors2, distances2 = index2.query(x2)\n\n np.testing.assert_equal(neighbors1, neighbors2)\n np.testing.assert_equal(distances1, distances2)\n\n\ndef test_compressed_pickle_unpickle():\n seed = np.random.RandomState(42)\n\n x1 = seed.normal(0, 100, (1000, 50))\n x2 = seed.normal(0, 100, (1000, 50))\n\n index1 = NNDescent(\n x1,\n \"euclidean\",\n {},\n 10,\n random_state=None,\n compressed=True,\n )\n neighbors1, distances1 = index1.query(x2)\n\n pickle.dump(index1, open(\"test_tmp.pkl\", \"wb\"))\n index2 = pickle.load(open(\"test_tmp.pkl\", \"rb\"))\n os.remove(\"test_tmp.pkl\")\n\n neighbors2, distances2 = index2.query(x2)\n\n np.testing.assert_equal(neighbors1, neighbors2)\n np.testing.assert_equal(distances1, distances2)\n\n\ndef test_transformer_pickle_unpickle():\n seed = np.random.RandomState(42)\n\n x1 = seed.normal(0, 100, (1000, 50))\n x2 = seed.normal(0, 100, (1000, 50))\n\n index1 = PyNNDescentTransformer(n_neighbors=10).fit(x1)\n result1 = index1.transform(x2)\n\n pickle.dump(index1, open(\"test_tmp.pkl\", \"wb\"))\n index2 = pickle.load(open(\"test_tmp.pkl\", \"rb\"))\n os.remove(\"test_tmp.pkl\")\n\n result2 = index2.transform(x2)\n\n np.testing.assert_equal(result1.indices, result2.indices)\n np.testing.assert_equal(result1.data, result2.data)\n\n\ndef test_joblib_dump():\n seed = np.random.RandomState(42)\n\n x1 = seed.normal(0, 100, (1000, 50))\n x2 = seed.normal(0, 100, (1000, 50))\n\n index1 = NNDescent(\n x1,\n \"euclidean\",\n {},\n 10,\n random_state=None,\n )\n neighbors1, distances1 = index1.query(x2)\n\n joblib.dump(index1, \"test_tmp.dump\")\n index2 = joblib.load(\"test_tmp.dump\")\n os.remove(\"test_tmp.dump\")\n\n neighbors2, distances2 = index2.query(x2)\n\n np.testing.assert_equal(neighbors1, neighbors2)\n np.testing.assert_equal(distances1, distances2)\n" ]
[ [ "numpy.testing.assert_equal", "numpy.allclose", "numpy.unique", "numpy.in1d", "sklearn.neighbors.KDTree", "numpy.ones", "numpy.all", "sklearn.preprocessing.normalize", "sklearn.neighbors.NearestNeighbors", "numpy.argsort", "numpy.random.RandomState" ] ]
peterger8y/Airbnb-rental-price-predictor
[ "32175783292a044b0cfab1c7274ff15c2eea4fd4" ]
[ "neighbors_model.py" ]
[ "from sklearn.pipeline import make_pipeline\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.impute import SimpleImputer\nfrom category_encoders import OneHotEncoder\nfrom sklearn.preprocessing import StandardScaler\n\ndef bathroom_text_encoder(df):\n df1 = df.copy()\n df1['bathrooms_text'] = df['bathrooms_text'].astype('string')\n shared = []\n private = []\n for x in df1['bathrooms_text']:\n\n try:\n x = x.split()\n if x[0] == 'shared' or x[0] == 'Shared':\n shared.append(1)\n private.append(0)\n elif x[0] == 'private' or x[0] == 'Private':\n shared.append(0)\n private.append(1)\n elif x[1] == 'shared' or x[1] == 'Shared':\n shared.append(float(x[0]))\n private.append(0)\n else:\n shared.append(0)\n private.append(float(x[0]))\n except:\n shared.append(0)\n private.append(0)\n\n return shared, private\n\ndef pipeline_model(df, cols_to_keep):\n\n #handles bathroom_text:\n df_copy = df[cols_to_keep]\n\n shared, private = bathroom_text_encoder(df_copy)\n\n alpha = []\n\n for x in df_copy['price']:\n x = x.strip('$')\n x = x.replace(',', '')\n x = float(x)\n alpha.append(x)\n\n df_copy['price'] = alpha\n\n if shared:\n df_copy.drop(columns='bathrooms_text', inplace=True)\n df_copy['shared_bathrooms'] = shared\n df_copy['private_bathrooms'] = private\n cols_to_keep.remove('bathrooms_text')\n\n X = df_copy.drop(columns=['price'])\n y = df_copy['price']\n\n pipe = make_pipeline(OneHotEncoder(cols=['room_type']), StandardScaler(), SimpleImputer(strategy='most_frequent'), KNeighborsRegressor(algorithm='brute', n_neighbors=20))\n\n pipe.fit(X, y)\n oh = pipe.named_steps['onehotencoder']\n stand = pipe.named_steps['standardscaler']\n simp = pipe.named_steps['simpleimputer']\n kneigh = pipe.named_steps['kneighborsregressor']\n\n return pipe, oh, stand, simp, kneigh\n" ]
[ [ "sklearn.neighbors.KNeighborsRegressor", "sklearn.preprocessing.StandardScaler", "sklearn.impute.SimpleImputer" ] ]
xiaojingyi/embedView
[ "1078f77cd4f452be528c361fee8f11f720bb54f0" ]
[ "t-sne.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: 2015 Jingyi Xiao\n# FileName: t-sne.py\n# Date: 2019 2019年06月10日 14:33:51\n# Encoding: utf-8\n# Author: Jingyi Xiao\n\n__author__=\"Jingyi\"\n\nimport os, sys, time\nimport argparse\nimport numpy as np\nfrom tensorflow.contrib.tensorboard.plugins import projector\nimport tensorflow as tf\nFLAGS = None\n\ndef embeddingShow():\n data = np.load(FLAGS.input)\n idx = np.arange(len(data))\n if FLAGS.random:\n np.random.shuffle(idx)\n idx = idx[:FLAGS.nmax]\n\n tsv_data = None\n if FLAGS.tsv and os.path.exists(FLAGS.tsv):\n with open(FLAGS.tsv, 'r') as f:\n d = f.read()\n tsv_data = d.split('\\n')\n tsv_data = list(filter(lambda x: x, tsv_data))\n assert(len(data) == len(tsv_data)-1), (data.shape, len(tsv_data))\n\n tsv_data = np.array(tsv_data)\n tsv_choose = tsv_data[idx+1]\n tsv_data = np.concatenate((np.array([tsv_data[0]]), tsv_choose), axis=0)\n\n data = data[idx]\n sess = tf.InteractiveSession()\n\n with tf.device(\"/cpu:0\"):\n embedding = tf.Variable(tf.stack(data, axis=0),\n trainable=False, name='embedding')\n\n tf.global_variables_initializer().run()\n\n saver = tf.train.Saver()\n writer = tf.summary.FileWriter(FLAGS.logdir + '/projector', sess.graph)\n\n config = projector.ProjectorConfig()\n embed= config.embeddings.add()\n embed.tensor_name = 'embedding:0'\n embed.metadata_path = 'metadata.tsv'\n\n projector.visualize_embeddings(writer, config)\n\n saver.save(sess, os.path.join(\n FLAGS.logdir, 'projector/model.ckpt'), global_step=1)\n with open(FLAGS.logdir + \"/projector/metadata.tsv\", 'w') as f:\n nloop = FLAGS.nmax\n if tsv_data is not None:\n nloop += 1\n for i in range(nloop):\n if tsv_data is None: s = '_'+str(i)\n else: s = tsv_data[i]\n f.write(\"%s\\n\" % s)\n\ndef main(_):\n global FLAGS\n if tf.gfile.Exists(FLAGS.logdir + '/projector'):\n tf.gfile.DeleteRecursively(FLAGS.logdir + '/projector')\n tf.gfile.MkDir(FLAGS.logdir + '/projector')\n tf.gfile.MakeDirs(FLAGS.logdir + '/projector')\n embeddingShow()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', type=str, default='', help='input numpy data')\n parser.add_argument('--tsv', type=str, default='', help='tsv file for labels')\n parser.add_argument('--logdir', type=str, default='summary', help='Summaries log dir')\n parser.add_argument('--nmax', type=int, default=1000, help='max size of show')\n parser.add_argument('--random', type=int, default=1, help='random choose idx')\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main)\n\n" ]
[ [ "tensorflow.device", "tensorflow.summary.FileWriter", "tensorflow.InteractiveSession", "tensorflow.gfile.DeleteRecursively", "tensorflow.gfile.Exists", "tensorflow.gfile.MkDir", "tensorflow.stack", "numpy.random.shuffle", "tensorflow.global_variables_initializer", "tensorflow.contrib.tensorboard.plugins.projector.visualize_embeddings", "tensorflow.contrib.tensorboard.plugins.projector.ProjectorConfig", "tensorflow.gfile.MakeDirs", "tensorflow.train.Saver", "numpy.load", "numpy.array", "tensorflow.app.run" ] ]
evalf/povplot
[ "c74e2767387d8c2e591932f6b2db574ffa024418" ]
[ "tests.py" ]
[ "import unittest, tempfile, io, collections, pathlib\nimport numpy, matplotlib.image, matplotlib.cm, matplotlib.figure, matplotlib.backends.backend_agg\nimport povplot\n\nclass common:\n\n def render_square(self, *, focal_length=50, **kwargs):\n defaults = dict(vertices=[[-9,-9,focal_length],[-9,9,focal_length],[9,-9,focal_length],[9,9,focal_length]],\n triangles=[[0,1,2],[1,3,2]],\n values=[0,0,2,2],\n size=(36,24),\n camera=dict(location=(0,0,0),look_at=(0,0,focal_length),focal_point=(0,0,focal_length),focal_length=focal_length))\n return self.render(**collections.ChainMap(kwargs, defaults))\n\n def render_triangle(self, *, focal_length=50, **kwargs):\n defaults = dict(vertices=[[-9,-9,focal_length],[-9,9,focal_length],[9,0,focal_length]],\n triangles=[[0,1,2]], values=[0,1,2],\n size=(36,24),\n camera=dict(location=(0,0,0),look_at=(0,0,focal_length),focal_point=(0,0,focal_length),focal_length=focal_length))\n return self.render(**collections.ChainMap(kwargs, defaults))\n\n def test_focal_length(self):\n for focal_length in 25, 50:\n with self.subTest(focal_length=focal_length):\n im = self.render_square(focal_length=focal_length)[:,:,:3]\n mask = numpy.zeros([24,36], dtype=bool)\n mask[3:21,9:27] = True\n self.assertTrue(numpy.equal(im[~mask], [[0,0,0]]).all())\n self.assertFalse(numpy.equal(im[mask], [[0,0,0]]).all())\n\n def test_transparent(self):\n for transparent in True, False:\n with self.subTest(transparent=transparent):\n im = self.render_square(transparent=transparent)\n self.assertEqual(im[0,0,3], 0 if transparent else 255)\n self.assertEqual(im[12,18,3], 255)\n\n def test_antialias(self):\n for antialias in True, False:\n with self.subTest(antialias=antialias):\n im = self.render_triangle(antialias=antialias, transparent=True)\n if antialias:\n self.assertGreater(len(numpy.unique(im[:,:,3].ravel())), 2)\n else:\n self.assertEqual(numpy.unique(im[:,:,3].ravel()).tolist(), [0, 255])\n\n def test_cmap_jet(self):\n im = self.render_square(cmap='jet')\n cmap = matplotlib.cm.get_cmap('jet')\n self.assertLess(abs((im[12,9:-9])-cmap((numpy.arange(18)+0.5)/18)*255).max(), 5)\n\n def test_vmin_vmax(self):\n im = self.render_square(vmin=-1, vmax=3)\n cmap = matplotlib.cm.get_cmap(None)\n self.assertLess(abs((im[12,9:-9])-cmap((numpy.arange(9,27)+0.5)/36)*255).max(), 5)\n\n def test_auto_camera(self):\n im = self.render_square(camera=None)\n mask = numpy.ones(im.shape[:2], dtype=bool)\n mask[1:-1,1:-1] = False\n self.assertGreater(numpy.max(im[:,:,:3]), 0, msg='object out of sight')\n self.assertTrue(numpy.equal(im[mask][:,:3], [[0,0,0]]).all(), msg='object partly out of sight')\n\n def test_nprocs(self):\n im = self.render_square(nprocs=2)\n\nclass render_tripcolor(unittest.TestCase, common):\n\n test_args = dict(vertices=[[-9,-9,50],[-9,9,50],[9,-9,50],[9,9,50]],\n triangles=[[0,1,2],[1,3,2]], values=[0,1,2,3],\n size=(36,24))\n\n png_header = b'\\x89\\x50\\x4e\\x47\\x0d\\x0a\\x1a\\x0a'\n jpg_header = b'\\xff\\xd8\\xff'\n\n def render(self, **kwargs):\n with tempfile.TemporaryFile('w+b') as f:\n povplot.render_tripcolor(f, imgtype='png', **kwargs)\n f.flush()\n f.seek(0)\n im = (matplotlib.image.imread(f, format='png')*255).round().astype(numpy.uint8)\n if im.shape[2] == 3:\n im = numpy.concatenate([im, numpy.full_like(im[:,:,:1], 255)], axis=2)\n return im\n\n def test_guess_imgtype_known(self):\n for header, *suffixes in (self.png_header, '.png', b'.png'),:# (self.jpg_header, '.jpg'):\n for suffix in suffixes:\n with self.subTest(suffix=suffix):\n with tempfile.NamedTemporaryFile('w+b', suffix=suffix) as f:\n povplot.render_tripcolor(f, **self.test_args)\n f.flush()\n f.seek(0)\n self.assertEqual(f.read(len(header)), header)\n\n def test_guess_imgtype_unknown(self):\n with tempfile.NamedTemporaryFile('wb', suffix='.unknown') as f:\n with self.assertRaises(ValueError):\n povplot.render_tripcolor(f, **self.test_args)\n\n def test_guess_imgtype_no_name(self):\n with io.BytesIO() as f:\n with self.assertRaises(ValueError):\n povplot.render_tripcolor(f, **self.test_args)\n\n def test_write_stringio(self):\n with io.BytesIO() as f:\n povplot.render_tripcolor(f, imgtype='png', **self.test_args)\n f.flush()\n f.seek(0)\n self.assertEqual(f.read(len(self.png_header)), self.png_header)\n\n def test_write_str(self):\n with tempfile.NamedTemporaryFile('w+b', suffix='.png') as f:\n povplot.render_tripcolor(f.name, **self.test_args)\n f.flush()\n f.seek(0)\n self.assertEqual(f.read(len(self.png_header)), self.png_header)\n\nclass tripcolor(unittest.TestCase, common):\n\n def render(self, *, size, **kwargs):\n dpi = 100\n figsize = size[0]/dpi, size[1]/dpi\n with tempfile.TemporaryFile('w+b') as f:\n fig = matplotlib.figure.Figure(figsize=figsize, dpi=dpi)\n matplotlib.backends.backend_agg.FigureCanvas(fig) # sets reference via fig.set_canvas\n ax = fig.add_axes([0,0,1,1])\n ax.axis('off')\n povplot.tripcolor(ax, **kwargs)\n savefig_kwargs = dict(facecolor='none', edgecolor='none') if kwargs.get('transparent', False) else {}\n fig.savefig(f, format='png', **savefig_kwargs)\n fig.set_canvas(None) # break circular reference\n f.flush()\n f.seek(0)\n return (matplotlib.image.imread(f, format='png')*255).round().astype(numpy.uint8)\n\nclass render(unittest.TestCase):\n\n def test_error(self):\n with tempfile.TemporaryFile('wb') as f:\n with self.assertRaisesRegex(povplot.PovrayError, '^Povray failed with code -?[0-9]+$') as cm:\n povplot.render(f, scene='invalid', size=(36,24), imgtype='png')\n with self.subTest('rendered script'):\n self.assertEqual(cm.exception.rendered_script, 'invalid')\n\nclass overlay_colorbar(unittest.TestCase):\n\n def test(self):\n # Test if code runs only.\n dpi = 100\n with tempfile.TemporaryFile('w+b') as f:\n fig = matplotlib.figure.Figure()\n matplotlib.backends.backend_agg.FigureCanvas(fig) # sets reference via fig.set_canvas\n ax = fig.add_axes([0,0,1,1])\n im = povplot.tripcolor(ax,\n hide_frame=True,\n vertices=[[-9,-9,50],[-9,9,50],[9,-9,50],[9,9,50]],\n triangles=[[0,1,2],[1,3,2]], values=[0,1,2,3])\n povplot.overlay_colorbar(fig, im)\n fig.savefig(f, format='png', facecolor='none', edgecolor='none')\n fig.set_canvas(None) # break circular reference\n f.flush()\n f.seek(0)\n\nclass sphinx(unittest.TestCase):\n\n def test(self):\n with tempfile.TemporaryDirectory(prefix='povplot-') as tmpdir:\n tmpdir = pathlib.Path(tmpdir)\n root = pathlib.Path(__file__).parent\n try:\n from sphinx.application import Sphinx\n except ImportError:\n self.skipTest()\n raise ValueError\n app = Sphinx(srcdir=str(root/'docs'),\n confdir=str(root/'docs'),\n outdir=str(tmpdir/'html'),\n doctreedir=str(tmpdir/'doctree'),\n buildername='html',\n freshenv=True,\n warningiserror=True,\n confoverrides=dict(nitpicky=True))\n app.build()\n if app.statuscode:\n self.fail('sphinx build failed with code {}'.format(app.statuscode))\n\n# vim: sts=2:sw=2:et\n" ]
[ [ "numpy.arange", "numpy.ones", "numpy.full_like", "numpy.max", "numpy.equal", "numpy.zeros" ] ]
askamenik/PyGromosTools
[ "1aacfb87e4b3368f4fbf1dec74f83ec3806a5ca2" ]
[ "pygromos/files/trajectory/_general_trajectory.py" ]
[ "\"\"\"\nFUNCTIONLIB: trajectory template with pandas\nDescription:\n in this parent class for all trajectories the general parsing to a pandas database is handeled.\n This class is intended as quick data evaluation in python without gromos++ programs like ene_ana\n\n Specific block structures are handeled in the respectve classes (trc/tre/trf/...)\n\nAuthor: Marc Thierry Lehner\n\nRemark: WIP\n\n###########################\nATTENTION: NOT FULLY TESTET\nATTENTION: WORK IN PROGRESS\n###########################\n\nTODO: MTL: implement, check, test\n\n\"\"\"\n\n#imports\nimport collections, os, re\nimport pandas\nimport pathlib\n\nfrom pygromos.files.trajectory.blocks import trajectory_blocks as blocks\nfrom pygromos.utils import bash\n\nclass _General_Trajectory():\n\n #attribute annotation:\n database:pandas.DataFrame\n path:str\n _future_file:bool #if code is executed async, this helps organizing.\n\n def __init__(self, input_value:(str or None), auto_save=True, stride:int=1, skip:int=0):\n if input_value == None:\n self.TITLE = \"Empty Trajectory\"\n self.database = pandas.DataFrame({'' : []})\n\n elif isinstance(input_value, str):\n if(input_value.endswith(\".gz\")):\n tmp_input = bash.compress_gzip(input_value, extract=True)\n self._read_from_file(input_path=tmp_input, auto_save=auto_save, stride=stride, skip=skip)\n bash.compress_gzip(tmp_input)\n else:\n self._read_from_file(input_path=input_value, auto_save=auto_save, stride=stride, skip=skip)\n self.path = input_value\n\n elif isinstance(input_value, list) and all([x is str for x in input_value]):\n self._read_from_file(input_path=input_value[0], auto_save=False, stride=stride, skip=skip)\n\n for tmp_traj_file in input_value[1:]:\n self += __class__(tmp_traj_file, auto_save=False)\n\n if(auto_save):\n auto_save_path = input_value[0]+\".h5\"\n self.write(auto_save_path)\n\n elif isinstance(input_value.__class__, __class__) or issubclass(input_value.__class__, __class__):\n for attr in vars(input_value):\n setattr(self, attr, getattr(input_value, attr))\n self.database = input_value.database.copy(deep=True)\n else:\n raise IOError(\"Constructor not found\")\n\n def __str__(self)->str:\n if(isinstance(self.TITLE, str)):\n msg=\"Trajectory: \\n\\t\"+\"\\n\\t\".join(self.TITLE.split(\"\\n\"))+\"\\n\"\n elif(isinstance(self.TITLE, list)):\n msg=\"Trajectory: \\n\\t\"+\"\\n\\t\".join(self.TITLE)+\"\\n\"\n else:\n print(type(self.TITLE), self.TITLE)\n msg=\"Trajectory: \\n\\t\"+\"\\n\\t\".join(str(self.TITLE).split(\"\\n\"))+\"\\n\"\n\n\n msg+= \"Type: \\n\\t\" +str(self.__class__.__name__) + \"\\n\"\n msg+=\"Frames: \\t\"+str(self.database.shape[0])+\"\\t Columns:\\t\"+str(self.database.shape[1])+\"\\n\"\n msg+=\"\\n\"\n return msg\n\n def __repr__(self):\n return str(self)\n\n def __add__(self, traj):\n return self.add_traj(traj, skip_new_0=True)\n\n def __copy__(self):\n traj = type(self)(input_value=None)\n for attr in vars(self):\n setattr(traj, attr, getattr(self, attr))\n traj.database = self.database.copy(deep=False)\n return traj\n\n def __deepcopy__(self, memo):\n traj = type(self)(input_value=None)\n for attr in vars(self):\n setattr(traj, attr, getattr(self, attr))\n traj.database = self.database.copy(deep=True)\n return traj\n\n def add_traj(self, traj, skip_new_0=True):\n \"\"\"Combine (Catenate) two trajectories to a longer trajectory. Important: A+B!=B+A\n\n Parameters\n ----------\n traj : trajectory of the same format and type as the base class\n\n Returns\n -------\n traj\n trajA + trajB\n \"\"\"\n if type(traj) != type(self):\n raise Exception(\"Different types of trajectories can not be added (concatenated).\\nTry to add a \" + str(type(self)) + \" class of the same type\")\n if traj.database.shape[1] != self.database.shape[1]:\n raise Warning(\"trajectories database shapes do not match!\\n Please check if this is expected\\n\"\n \"first shape: \"+str(self.database.shape)+\"\\tsecond shape: \"+str(traj.database.shape)+\"\\n\")\n # get end data from first trajectory\n step_offset = int(self.database.TIMESTEP_step.iloc[-1])\n time_offset = float(self.database.TIMESTEP_time.iloc[-1])\n # copy and modify second trajectory\n new_data = traj.database.copy(deep=True)\n new_data.TIMESTEP_step += step_offset\n new_data.TIMESTEP_time += time_offset\n if skip_new_0:\n new_data = new_data.iloc[1:]\n # create output trajectory (copy of first traj) and combine trajectories\n new_traj = self.__class__(input_value=self)\n new_traj.database = self.database.append(new_data, ignore_index=True)\n return new_traj\n\n def _read_from_file(self, input_path:str, auto_save:bool=True, stride:int=1, skip:int=0):\n if(input_path.endswith(\".h5\")):\n self._read_db_from_hf5(input_path=input_path)\n elif(re.search( \"\\.tr.$\", input_path)): #\n self._read_trajectory(input_path=input_path, auto_save=auto_save, stride=stride, skip=skip)\n else:\n raise IOError(\"Did not understand the file ending of given file path: \", input_path)\n\n def _read_db_from_hf5(self, input_path:str, title: str=\"Read from hdf save \\nContains only database\\n\"):\n self.TITLE = title\n self.database = pandas.read_hdf(path_or_buf=input_path, key=input_path.split(\".\")[-1])\n\n def _raw_read_trajectory(self, input_path:str, stride:int=1, skip:int=0) -> collections.defaultdict:\n #define temp storage\n header = {}\n data = []\n dataInTimestep = {}\n block = []\n blockname = ''\n \n #set contorl bool\n isInTimeStep = False\n isInBlock = False\n timeStepCounter = 0-skip\n\n # start to read the trajectory\n with open(input_path, 'r') as infile:\n for line in infile:\n if isInTimeStep:\n if timeStepCounter >= 0 and timeStepCounter%stride==0:\n if isInBlock:\n if not line.strip().startswith(\"END\"):\n block.append(line)\n else:\n isInBlock = False\n dataInTimestep.update({blockname:block}) \n else:\n if line.strip().startswith('#') or line.strip() == '':\n continue\n blockname = line.strip()\n block = []\n isInBlock = True\n if blockname.startswith(\"TIMESTEP\"):\n data.append(dataInTimestep)\n dataInTimestep = {}\n timeStepCounter += 1\n else:\n if line.strip().startswith(\"TIMESTEP\"):\n timeStepCounter += 1 \n else:\n if isInBlock:\n if not line.strip().startswith(\"END\"):\n block.append(line)\n else:\n isInBlock = False\n header.update({blockname:block})\n else:\n if line.strip().startswith('#') or line.strip() == '':\n continue\n blockname = line.strip()\n block = []\n isInBlock = True\n if blockname.startswith(\"TIMESTEP\"):\n isInTimeStep = True\n if isInTimeStep:\n #final time step finish since no smarter way to detect end of Timestep\n data.append(dataInTimestep)\n else:\n raise ValueError(\"No timestep found\")\n del dataInTimestep, block, blockname\n return {\"header\":header, \"body\":data}\n\n def _read_trajectory(self, input_path:str, stride:int=1, skip:int=0, auto_save=True):\n if auto_save:\n # check if parsed file exists and is up to date\n if os.path.isfile(input_path+\".h5\"):\n if pathlib.Path(input_path).stat().st_ctime < pathlib.Path(input_path+\".h5\").stat().st_ctime:\n self._read_db_from_hf5(input_path=input_path+\".h5\", title=\"Reread from hdf save \\nContains only database\\nfor all other blocks please make a fresh import\")\n\n if (not os.path.exists(input_path)):\n raise IOError(\"Could not find File: \", input_path)\n else:\n table = []\n data = self._raw_read_trajectory(input_path=input_path, stride=stride, skip=skip)\n header = data[\"header\"]\n body = data[\"body\"]\n for key, block in header.items():\n setattr(self, key, block)\n for time_step_entry in body:\n table_entry = {}\n for blocktitle, block in time_step_entry.items():\n if not hasattr(blocks, blocktitle):\n raise IOError(\"No trajectory block found named: \"+blocktitle)\n tmp_block = getattr(blocks, blocktitle)(block)\n table_entry.update(tmp_block.to_dict())\n table.append(table_entry)\n db = pandas.DataFrame.from_dict(table)\n del table, table_entry, data, header, body\n self.database = db\n if auto_save:\n self.write(input_path+\".h5\")\n\n def write(self, output_path:str)->str:\n if(not output_path.endswith(\".h5\")):\n output_path += \".h5\"\n if(not os.path.exists(os.path.dirname(output_path))):\n raise IOError(\"Could not find target directory for outfile! target dir: \" + str(os.path.dirname(output_path)))\n self.database.to_hdf(path_or_buf=output_path, key=output_path.split(\".\")[-1]) #TODO: @Marc is the key arg here correct, or rather not using it?\n self.path = output_path\n return output_path\n\n\n \n \n \n\n \n \n\n\n\n\n" ]
[ [ "pandas.DataFrame", "pandas.DataFrame.from_dict" ] ]
not-jenni/iree-samples
[ "c726345c95cb3efa4ee622482c16c6ec4a3187d0" ]
[ "tflitehub/mobilebert_tf2_quant_test.py" ]
[ "# RUN: %PYTHON %s\n\nimport absl.testing\nimport numpy as np\nimport squad_test_data\nimport test_util\n\nmodel_path = \"https://storage.googleapis.com/iree-model-artifacts/mobilebert-baseline-tf2-quant.tflite\"\n\nclass MobileBertTest(test_util.TFLiteModelTest):\n def __init__(self, *args, **kwargs):\n super(MobileBertTest, self).__init__(model_path, *args, **kwargs)\n\n # Inputs modified to be useful mobilebert inputs.\n def generate_inputs(self, input_details):\n for input in input_details:\n absl.logging.info(\"\\t%s, %s\", str(input[\"shape\"]), input[\"dtype\"].__name__)\n\n input_0 = np.asarray(squad_test_data._INPUT_WORD_ID, dtype=input_details[0][\"dtype\"])\n input_1 = np.asarray(squad_test_data._INPUT_TYPE_ID, dtype=input_details[1][\"dtype\"])\n input_2 = np.asarray(squad_test_data._INPUT_MASK, dtype=input_details[2][\"dtype\"])\n return [\n input_0.reshape(input_details[0][\"shape\"]),\n input_1.reshape(input_details[1][\"shape\"]),\n input_2.reshape(input_details[2][\"shape\"])\n ]\n\n def compare_results(self, iree_results, tflite_results, details):\n super(MobileBertTest, self).compare_results(iree_results, tflite_results, details)\n # We have confirmed in large scale accuracy tests that differences this large is acceptable.\n self.assertTrue(np.isclose(iree_results[0], tflite_results[0], atol=5.0).all())\n self.assertTrue(np.isclose(iree_results[1], tflite_results[1], atol=5.0).all())\n\n def test_compile_tflite(self):\n self.compile_and_execute()\n\nif __name__ == '__main__':\n absl.testing.absltest.main()\n\n" ]
[ [ "numpy.asarray", "numpy.isclose" ] ]
Belhoussine/Moodzik
[ "0e7f85244e86d7f54d112742b38c3b8bcd0d925f" ]
[ "WebApp/GenerateSong/utils.py" ]
[ "\n\"\"\"Transform utilities.\"\"\"\nimport numpy as np\nimport tensorflow.compat.v1 as tf # pylint: disable=import-error\ntf.disable_v2_behavior()\n\nfrom tensor2tensor.data_generators import text_encoder\n\nimport magenta.music as mm \nfrom magenta.models.score2perf import score2perf\n\nLOGGER = tf.compat.v1.logging\n\n\nclass PianoPerformanceLanguageModelProblem(score2perf.Score2PerfProblem): # pylint: disable=missing-module-docstring, abstract-method, missing-class-docstring\n @property\n def add_eos_symbol(self):\n return True\n\n\nclass MelodyToPianoPerformanceProblem(score2perf.AbsoluteMelody2PerfProblem): # pylint: disable=missing-module-docstring, abstract-method, missing-class-docstring\n @property\n def add_eos_symbol(self):\n return True\n\n\ndef decode(ids, encoder):\n \"\"\"Decode a list of IDs.\"\"\"\n ids = list(ids)\n if text_encoder.EOS_ID in ids:\n ids = ids[:ids.index(text_encoder.EOS_ID)]\n return encoder.decode(ids)\n\n\ndef unconditional_input_generator(targets, decode_length):\n \"\"\"Estimator input function for unconditional Transformer.\"\"\"\n while True:\n yield {\n 'targets': np.array([targets], dtype=np.int32),\n 'decode_length': np.array(decode_length, dtype=np.int32)\n }\n\n\ndef melody_input_generator(inputs, decode_length):\n \"\"\"Estimator input function for melody Transformer.\"\"\"\n while True:\n yield {\n 'inputs': np.array([[inputs]], dtype=np.int32),\n 'targets': np.zeros([1, 0], dtype=np.int32),\n 'decode_length': np.array(decode_length, dtype=np.int32)\n }\n\n\ndef get_primer_ns(filename, max_length):\n \"\"\"\n Convert Midi file to note sequences for priming.\n :param filename: Midi file name.\n :param max_length: Maximum note sequence length for priming in seconds.\n :return:\n Note sequences for priming.\n \"\"\"\n primer_ns = mm.midi_file_to_note_sequence(filename)\n\n # Handle sustain pedal in primer.\n primer_ns = mm.apply_sustain_control_changes(primer_ns)\n\n # Trim to desired number of seconds.\n if primer_ns.total_time > max_length:\n LOGGER.warn(\n 'Primer duration %d is longer than max second %d, truncating.'\n % (primer_ns.total_time, max_length))\n primer_ns = mm.extract_subsequence(\n primer_ns, 0, max_length\n )\n\n # Remove drums from primer if present.\n if any(note.is_drum for note in primer_ns.notes):\n LOGGER.warn('Primer contains drums; they will be removed.')\n notes = [note for note in primer_ns.notes if not note.is_drum]\n del primer_ns.notes[:]\n primer_ns.notes.extend(notes)\n\n # Set primer instrument and program.\n for note in primer_ns.notes:\n note.instrument = 1\n note.program = 0\n\n return primer_ns\n\n\ndef get_melody_ns(filename):\n \"\"\"\n Convert melody Midi file to note sequence.\n :param filename: Midi file name.\n :return:\n Melody note sequences.\n \"\"\"\n melody_ns = mm.midi_file_to_note_sequence(filename)\n melody_instrument = mm.infer_melody_for_sequence(melody_ns)\n # pylint: disable=no-member\n notes = [note for note in melody_ns.notes if note.instrument == melody_instrument]\n del melody_ns.notes[:]\n melody_ns.notes.extend(\n sorted(notes, key=lambda note: note.start_time)\n )\n for i in range(len(melody_ns.notes) - 1):\n melody_ns.notes[i].end_time = melody_ns.notes[i + 1].start_time\n\n # pylint: disable=no-member\n\n return melody_ns" ]
[ [ "numpy.array", "numpy.zeros", "tensorflow.compat.v1.disable_v2_behavior" ] ]
stfcsciml/sciml-benchmarks
[ "636aefb0089f79f57be3025b3acb902571117e6f" ]
[ "sciml_bench/benchmarks/dms_classifier/data_loader.py" ]
[ "import h5py\nimport tensorflow as tf\nimport numpy as np\nfrom pathlib import Path\nimport horovod.tensorflow as hvd\n\nfrom sciml_bench.core.data_loader import DataLoader\nfrom sciml_bench.benchmarks.dms_classifier.constants import IMG_HEIGHT, IMG_WIDTH, N_CHANNELS\n\n\nclass DMSDataset(DataLoader):\n\n def __init__(self, data_dir, seed=None, batch_size: int=10, is_training_data: bool=True, **kwargs):\n self._seed = seed\n self._data_dir = Path(data_dir)\n self._batch_size = batch_size\n\n if is_training_data:\n self._image_name = 'data/train'\n self._label_name = 'labels/train'\n else:\n self._image_name = 'data/test'\n self._label_name = 'labels/test'\n\n def _load_data(self, path):\n path = path.decode()\n\n with h5py.File(path, \"r\") as hdf5_file:\n for i in range(0, len(hdf5_file[self._image_name]), self._batch_size):\n images = np.array(hdf5_file[self._image_name][i:i + self._batch_size])\n labels = np.array(hdf5_file[self._label_name][i:i + self._batch_size, 0])\n yield images, labels\n\n @property\n def input_shape(self):\n return (IMG_HEIGHT, IMG_WIDTH, N_CHANNELS)\n\n @property\n def output_shape(self):\n return (1,)\n\n def to_dataset(self):\n path = str(self._data_dir / 'dxs-data.hdf5')\n types = (tf.float32, tf.float32)\n shapes = (tf.TensorShape([None, IMG_HEIGHT, IMG_WIDTH, N_CHANNELS]),\n tf.TensorShape([None]))\n dataset = tf.data.Dataset.from_generator(self._load_data,\n output_types=types,\n output_shapes=shapes,\n args=(path, ))\n dataset = dataset.unbatch()\n dataset = dataset.shuffle(2000)\n dataset = dataset.shard(hvd.size(), hvd.rank())\n dataset = dataset.batch(self._batch_size)\n return dataset\n" ]
[ [ "tensorflow.TensorShape", "numpy.array", "tensorflow.data.Dataset.from_generator" ] ]
WoodoLee/TorchCraft
[ "999f68aab9e7d50ed3ae138297226dc95fefc458", "999f68aab9e7d50ed3ae138297226dc95fefc458", "c20483a437c82936cb0fb8080925e37b9c4bba87" ]
[ "3rdparty/pytorch/caffe2/python/operator_test/transpose_op_test.py", "3rdparty/pytorch/caffe2/python/onnx/test_onnxifi.py", "3rdparty/pytorch/caffe2/python/regularizer_test.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom caffe2.python import core, workspace\nfrom hypothesis import given\n\nimport caffe2.python.hypothesis_test_util as hu\nimport caffe2.python.serialized_test.serialized_test_util as serial\nimport hypothesis.strategies as st\n\nimport numpy as np\nimport unittest\n\n\nclass TestTransposeOp(serial.SerializedTestCase):\n @serial.given(\n X=hu.tensor(dtype=np.float32), use_axes=st.booleans(), **hu.gcs)\n def test_transpose(self, X, use_axes, gc, dc):\n ndim = len(X.shape)\n axes = np.arange(ndim)\n np.random.shuffle(axes)\n\n if (use_axes):\n op = core.CreateOperator(\n \"Transpose\", [\"X\"], [\"Y\"], axes=axes, device_option=gc)\n else:\n op = core.CreateOperator(\n \"Transpose\", [\"X\"], [\"Y\"], device_option=gc)\n\n def transpose_ref(X):\n if use_axes:\n return [np.transpose(X, axes=axes)]\n else:\n return [np.transpose(X)]\n\n self.assertReferenceChecks(gc, op, [X], transpose_ref)\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(gc, op, [X], 0, [0])\n\n @unittest.skipIf(not workspace.has_gpu_support, \"no gpu support\")\n @given(X=hu.tensor(dtype=np.float32), use_axes=st.booleans(),\n **hu.gcs_gpu_only)\n def test_transpose_cudnn(self, X, use_axes, gc, dc):\n ndim = len(X.shape)\n axes = np.arange(ndim)\n np.random.shuffle(axes)\n\n if (use_axes):\n op = core.CreateOperator(\n \"Transpose\", [\"X\"], [\"Y\"], axes=axes, engine=\"CUDNN\",\n device_option=hu.gpu_do)\n else:\n op = core.CreateOperator(\n \"Transpose\", [\"X\"], [\"Y\"], engine=\"CUDNN\",\n device_option=hu.gpu_do)\n\n def transpose_ref(X):\n if use_axes:\n return [np.transpose(X, axes=axes)]\n else:\n return [np.transpose(X)]\n\n self.assertReferenceChecks(hu.gpu_do, op, [X], transpose_ref)\n self.assertGradientChecks(hu.gpu_do, op, [X], 0, [0])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport json\nimport numpy as np\nimport os\nimport time\nimport unittest\n\nimport onnx\nimport onnx.defs\nfrom onnx.backend.base import namedtupledict\nfrom onnx.helper import make_node, make_graph, make_tensor, make_tensor_value_info, make_model\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import core, workspace\nfrom caffe2.python.models.download import downloadFromURLToFile, getURLFromName, deleteDirectory\nfrom caffe2.python.onnx.onnxifi import onnxifi_caffe2_net\nfrom caffe2.python.onnx.tests.test_utils import TestCase\n\nONNXIFI_DATATYPE_FLOAT32 = 1\n\n\ndef _print_net(net):\n for i in net.external_input:\n print(\"Input: {}\".format(i))\n for i in net.external_output:\n print(\"Output: {}\".format(i))\n for op in net.op:\n print(\"Op {}\".format(op.type))\n for x in op.input:\n print(\" input: {}\".format(x))\n for y in op.output:\n print(\" output: {}\".format(y))\n\n\nclass OnnxifiTest(TestCase):\n @unittest.skip(\"Need ONNXIFI backend support\")\n def test_relu_graph(self):\n batch_size = 1\n X = np.random.randn(batch_size, 1, 3, 2).astype(np.float32)\n graph_def = make_graph(\n [make_node(\"Relu\", [\"X\"], [\"Y\"])],\n name=\"test\",\n inputs=[make_tensor_value_info(\"X\", onnx.TensorProto.FLOAT,\n [batch_size, 1, 3, 2])],\n outputs=[make_tensor_value_info(\"Y\", onnx.TensorProto.FLOAT,\n [batch_size, 1, 3, 2])])\n model_def = make_model(graph_def, producer_name='relu-test')\n op = core.CreateOperator(\n \"Onnxifi\",\n [\"X\"],\n [\"Y\"],\n onnx_model=model_def.SerializeToString(),\n input_names=[\"X\"],\n output_names=[\"Y\"],\n output_shape_hint_0=[ONNXIFI_DATATYPE_FLOAT32, batch_size, 1, 3, 2])\n workspace.FeedBlob(\"X\", X)\n workspace.RunOperatorOnce(op)\n Y = workspace.FetchBlob(\"Y\")\n np.testing.assert_almost_equal(Y, np.maximum(X, 0))\n\n @unittest.skip(\"Need ONNXIFI backend support\")\n def test_conv_graph(self):\n X = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 5, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.]]]]).astype(np.float32)\n W = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n Y_without_padding = np.array([[[[54., 63., 72.], # (1, 1, 3, 3) output tensor\n [99., 108., 117.],\n [144., 153., 162.]]]]).astype(np.float32)\n graph_def = make_graph(\n [make_node(\n 'Conv',\n inputs=['X', 'W'],\n outputs=['Y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[0, 0, 0, 0],\n )],\n name=\"test\",\n inputs=[make_tensor_value_info(\"X\", onnx.TensorProto.FLOAT, [1, 1, 5, 5]),\n make_tensor_value_info(\"W\", onnx.TensorProto.FLOAT, [1, 1, 3, 3]),\n ],\n outputs=[make_tensor_value_info(\"Y\", onnx.TensorProto.FLOAT,\n [1, 1, 3, 3])])\n model_def = make_model(graph_def, producer_name='conv-test')\n # We intentional rewrite the input/output name so test that the\n # input/output binding of c2 op is positional\n op = core.CreateOperator(\n \"Onnxifi\",\n [\"X0\"],\n [\"Y0\"],\n onnx_model=model_def.SerializeToString(),\n initializers=[\"W\", \"W0\"],\n input_names=[\"X\"],\n output_names=[\"Y\"],\n output_shape_hint_0=[ONNXIFI_DATATYPE_FLOAT32, 1, 1, 3, 3])\n workspace.FeedBlob(\"X0\", X)\n workspace.FeedBlob(\"W0\", W)\n workspace.RunOperatorOnce(op)\n Y = workspace.FetchBlob(\"Y0\")\n np.testing.assert_almost_equal(Y, Y_without_padding)\n\n\nclass OnnxifiTransformTest(TestCase):\n def _model_dir(self, model):\n caffe2_home = os.path.expanduser(os.getenv('CAFFE2_HOME', '~/.caffe2'))\n models_dir = os.getenv('CAFFE2_MODELS', os.path.join(caffe2_home, 'models'))\n return os.path.join(models_dir, model)\n\n def _download(self, model):\n model_dir = self._model_dir(model)\n assert not os.path.exists(model_dir)\n os.makedirs(model_dir)\n for f in ['predict_net.pb', 'init_net.pb', 'value_info.json']:\n url = getURLFromName(model, f)\n dest = os.path.join(model_dir, f)\n try:\n try:\n downloadFromURLToFile(url, dest,\n show_progress=False)\n except TypeError:\n # show_progress not supported prior to\n # Caffe2 78c014e752a374d905ecfb465d44fa16e02a28f1\n # (Sep 17, 2017)\n downloadFromURLToFile(url, dest)\n except Exception as e:\n print(\"Abort: {reason}\".format(reason=e))\n print(\"Cleaning up...\")\n deleteDirectory(model_dir)\n exit(1)\n\n # TODO: we need to modulize this function\n def _get_c2_model(self, model_name):\n model_dir = self._model_dir(model_name)\n if not os.path.exists(model_dir):\n self._download(model_name)\n c2_predict_pb = os.path.join(model_dir, 'predict_net.pb')\n c2_predict_net = caffe2_pb2.NetDef()\n with open(c2_predict_pb, 'rb') as f:\n c2_predict_net.ParseFromString(f.read())\n c2_predict_net.name = model_name\n\n c2_init_pb = os.path.join(model_dir, 'init_net.pb')\n c2_init_net = caffe2_pb2.NetDef()\n with open(c2_init_pb, 'rb') as f:\n c2_init_net.ParseFromString(f.read())\n c2_init_net.name = model_name + '_init'\n\n value_info = json.load(open(os.path.join(model_dir, 'value_info.json')))\n return c2_init_net, c2_predict_net, value_info\n\n def _add_head_tail(self, pred_net, new_head, new_tail):\n orig_head = pred_net.external_input[0]\n orig_tail = pred_net.external_output[0]\n\n # Add head\n head = caffe2_pb2.OperatorDef()\n head.type = \"Copy\"\n head.input.append(new_head)\n head.output.append(orig_head)\n dummy = caffe2_pb2.NetDef()\n dummy.op.extend(pred_net.op)\n del pred_net.op[:]\n pred_net.op.extend([head])\n pred_net.op.extend(dummy.op)\n pred_net.external_input[0] = new_head\n\n # Add tail\n tail = caffe2_pb2.OperatorDef()\n tail.type = \"Copy\"\n tail.input.append(orig_tail)\n tail.output.append(new_tail)\n pred_net.op.extend([tail])\n pred_net.external_output[0] = new_tail\n\n @unittest.skip(\"Need ONNXIFI backend support\")\n def test_resnet50_core(self):\n N = 1\n repeat = 1\n print(\"Batch size: {}, repeat inference {} times\".format(N, repeat))\n init_net, pred_net, _ = self._get_c2_model('resnet50')\n self._add_head_tail(pred_net, 'real_data', 'real_softmax')\n input_blob_dims = (N, 3, 224, 224)\n input_name = \"real_data\"\n\n device_option = core.DeviceOption(caffe2_pb2.CPU, 0)\n init_net.device_option.CopyFrom(device_option)\n pred_net.device_option.CopyFrom(device_option)\n for op in pred_net.op:\n op.device_option.CopyFrom(device_option)\n net_outputs = pred_net.external_output\n Y_c2 = None\n data = np.random.randn(*input_blob_dims).astype(np.float32)\n c2_time = 1\n workspace.SwitchWorkspace(\"onnxifi_test\", True)\n with core.DeviceScope(device_option):\n workspace.FeedBlob(input_name, data)\n workspace.RunNetOnce(init_net)\n workspace.CreateNet(pred_net)\n start = time.time()\n for _ in range(repeat):\n workspace.RunNet(pred_net.name)\n end = time.time()\n c2_time = end - start\n output_values = [workspace.FetchBlob(name) for name in net_outputs]\n Y_c2 = namedtupledict('Outputs', net_outputs)(*output_values)\n workspace.ResetWorkspace()\n\n # Fill the workspace with the weights\n with core.DeviceScope(device_option):\n workspace.RunNetOnce(init_net)\n\n # Cut the graph\n start = time.time()\n pred_net_cut = onnxifi_caffe2_net(pred_net,\n {input_name: input_blob_dims},\n infer_shapes=True)\n del init_net, pred_net\n #_print_net(pred_net_cut)\n\n Y_trt = None\n input_name = pred_net_cut.external_input[0]\n print(\"C2 runtime: {}s\".format(c2_time))\n with core.DeviceScope(device_option):\n workspace.FeedBlob(input_name, data)\n workspace.CreateNet(pred_net_cut)\n end = time.time()\n print(\"Conversion time: {:.2f}s\".format(end - start))\n\n start = time.time()\n for _ in range(repeat):\n workspace.RunNet(pred_net_cut.name)\n end = time.time()\n trt_time = end - start\n print(\"Onnxifi runtime: {}s, improvement: {}%\".format(trt_time, (c2_time - trt_time) / c2_time * 100))\n output_values = [workspace.FetchBlob(name) for name in net_outputs]\n Y_trt = namedtupledict('Outputs', net_outputs)(*output_values)\n np.testing.assert_allclose(Y_c2, Y_trt, rtol=1e-3)\n\n\n", "from __future__ import absolute_import, division, print_function\n\nimport caffe2.python.hypothesis_test_util as hu\nimport hypothesis.strategies as st\nimport numpy as np\nimport numpy.testing as npt\nfrom caffe2.python import core, layer_model_instantiator, regularizer, schema, workspace\nfrom caffe2.python.layer_test_util import LayersTestCase\nfrom caffe2.python.optimizer import SgdOptimizer\nfrom caffe2.python.regularizer import L1Norm, RegularizationBy\nfrom caffe2.python.regularizer_context import RegularizerContext, UseRegularizer\nfrom hypothesis import given\n\n\nclass TestRegularizerContext(LayersTestCase):\n @given(X=hu.arrays(dims=[2, 5]))\n def test_regularizer_context(self, X):\n weight_reg_out = L1Norm(0.2)\n bias_reg_out = L1Norm(0)\n regularizers = {\"WEIGHT\": weight_reg_out, \"BIAS\": bias_reg_out}\n\n output_dims = 2\n input_record = self.new_record(schema.Scalar((np.float32, (5,))))\n schema.FeedRecord(input_record, [X])\n\n with UseRegularizer(regularizers):\n weight_reg = RegularizerContext.current().get_regularizer(\"WEIGHT\")\n bias_reg = RegularizerContext.current().get_regularizer(\"BIAS\")\n optim = SgdOptimizer(0.15)\n\n assert (\n weight_reg == weight_reg_out\n ), \"fail to get correct weight reg from context\"\n assert bias_reg == bias_reg_out, \"fail to get correct bias reg from context\"\n fc_output = self.model.FC(\n input_record,\n output_dims,\n weight_optim=optim,\n bias_optim=optim,\n weight_reg=weight_reg,\n bias_reg=bias_reg,\n )\n # model.output_schema has to a struct\n self.model.output_schema = schema.Struct((\"fc_output\", fc_output))\n\n self.assertEqual(schema.Scalar((np.float32, (output_dims,))), fc_output)\n\n _, train_net = layer_model_instantiator.generate_training_nets(self.model)\n ops = train_net.Proto().op\n ops_type_list = [ops[i].type for i in range(len(ops))]\n assert ops_type_list.count(\"LpNorm\") == 2\n assert ops_type_list.count(\"Scale\") == 4\n assert ops_type_list.count(\"LpNormGradient\") == 2\n\n\nclass TestRegularizer(LayersTestCase):\n @given(X=hu.arrays(dims=[2, 5], elements=st.floats(min_value=-1.0, max_value=1.0)))\n def test_log_barrier(self, X):\n param = core.BlobReference(\"X\")\n workspace.FeedBlob(param, X)\n train_init_net, train_net = self.get_training_nets()\n reg = regularizer.LogBarrier(1.0)\n output = reg(train_net, train_init_net, param, by=RegularizationBy.ON_LOSS)\n reg(\n train_net,\n train_init_net,\n param,\n grad=None,\n by=RegularizationBy.AFTER_OPTIMIZER,\n )\n workspace.RunNetOnce(train_init_net)\n workspace.RunNetOnce(train_net)\n\n def ref(X):\n return (\n np.array(np.sum(-np.log(np.clip(X, 1e-9, None))) * 0.5).astype(\n np.float32\n ),\n np.clip(X, 1e-9, None),\n )\n\n for x, y in zip(workspace.FetchBlobs([output, param]), ref(X)):\n npt.assert_allclose(x, y, rtol=1e-3)\n\n @given(\n X=hu.arrays(dims=[2, 5], elements=st.floats(min_value=-1.0, max_value=1.0)),\n left_open=st.booleans(),\n right_open=st.booleans(),\n eps=st.floats(min_value=1e-6, max_value=1e-4),\n ub=st.floats(min_value=-1.0, max_value=1.0),\n lb=st.floats(min_value=-1.0, max_value=1.0),\n **hu.gcs_cpu_only\n )\n def test_bounded_grad_proj(self, X, left_open, right_open, eps, ub, lb, gc, dc):\n if ub - (eps if right_open else 0.) < lb + (eps if left_open else 0.):\n return\n param = core.BlobReference(\"X\")\n workspace.FeedBlob(param, X)\n train_init_net, train_net = self.get_training_nets()\n reg = regularizer.BoundedGradientProjection(\n lb=lb, ub=ub, left_open=left_open, right_open=right_open, epsilon=eps\n )\n output = reg(train_net, train_init_net, param, by=RegularizationBy.ON_LOSS)\n reg(\n train_net,\n train_init_net,\n param,\n grad=None,\n by=RegularizationBy.AFTER_OPTIMIZER,\n )\n workspace.RunNetOnce(train_init_net)\n workspace.RunNetOnce(train_net)\n\n def ref(X):\n return np.clip(\n X, lb + (eps if left_open else 0.), ub - (eps if right_open else 0.)\n )\n\n assert output is None\n npt.assert_allclose(workspace.blobs[param], ref(X), atol=1e-7)\n\n @given(\n output_dim=st.integers(1, 10),\n input_num=st.integers(3, 30),\n reg_weight=st.integers(0, 10)\n )\n def test_group_l1_norm(self, output_dim, input_num, reg_weight):\n \"\"\"\n 1. create a weight blob\n 2. create random group splits\n 3. run group_l1_nrom with the weight blob\n 4. run equivalent np operations to calculate group l1 norm\n 5. compare if the results from 3 and 4 are equal\n \"\"\"\n def compare_reference(weight, group_boundaries, reg_lambda, output):\n group_splits = np.hsplit(weight, group_boundaries[1:-1])\n l2_reg = np.sqrt([np.sum(np.square(g)) for g in group_splits])\n l2_normalized = np.multiply(l2_reg,\n np.array([np.sqrt(g.shape[1]) for g in group_splits]))\n result = np.multiply(np.sum(l2_normalized), reg_lambda)\n npt.assert_almost_equal(result, workspace.blobs[output], decimal=2)\n\n weight = np.random.rand(output_dim, input_num).astype(np.float32)\n\n feature_num = np.random.randint(low=1, high=input_num - 1)\n group_boundaries = [0]\n group_boundaries = np.append(\n group_boundaries,\n np.sort(\n np.random.choice(range(1, input_num - 1), feature_num, replace=False)\n ),\n )\n group_boundaries = np.append(group_boundaries, [input_num])\n split_info = np.diff(group_boundaries)\n\n weight_blob = core.BlobReference(\"weight_blob\")\n workspace.FeedBlob(weight_blob, weight)\n\n train_init_net, train_net = self.get_training_nets()\n reg = regularizer.GroupL1Norm(reg_weight * 0.1, split_info.tolist())\n output = reg(\n train_net, train_init_net, weight_blob, by=RegularizationBy.ON_LOSS\n )\n\n workspace.RunNetOnce(train_init_net)\n workspace.RunNetOnce(train_net)\n\n compare_reference(weight, group_boundaries, reg_weight * 0.1, output)\n" ]
[ [ "numpy.arange", "numpy.random.shuffle", "numpy.transpose" ], [ "numpy.maximum", "numpy.testing.assert_almost_equal", "numpy.random.randn", "numpy.testing.assert_allclose", "numpy.array" ], [ "numpy.square", "numpy.sqrt", "numpy.clip", "numpy.hsplit", "numpy.testing.assert_almost_equal", "numpy.append", "numpy.diff", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.sum", "numpy.random.randint" ] ]
Hira63S/KnightRyder
[ "5eadc04f2fb056b04db59a658d5914ea847be7d2" ]
[ "models/regnet.py" ]
[ "import torch\nimport torch.nn as nn\n\n__all__ = ['regnetx_002', 'regnetx_004', 'regnetx_006', 'regnetx_008', 'regnetx_016', 'regnetx_032',\n 'regnetx_040', 'regnetx_064', 'regnetx_080', 'regnetx_120', 'regnetx_160', 'regnetx_320']\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n '''3x3 convolution with padding'''\n return nn.Conv2d(in_planes, out_planes,kernel_size=3,stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\ndef conv1x1(in_planes, out_planes, stride=1):\n '''1x1 convolution'''\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\nclass Bottleneck(nn.Module):\n expansion = 1\n __constants__ = ['downsample']\n \n def __init__(self, in_planes, planes, stride=1, downsample=None, group_width=1,\n dilation=1, norm_layer=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n \n width = planes * self.expansion\n self.conv1 = conv1x1(in_planes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = conv3x3(width, width, stride, width//min(width,group_width), dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = conv1x1(width, planes)\n self.bn3 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n \n def forward(self, x):\n identity = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n \n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n \n out = self.conv3(out)\n out = self.bn3(out)\n \n if self.downsample is not None:\n identity = self.downsample(x)\n \n out += identity\n out = self.relu(out)\n \n return out \n \n \nclass RegNet(nn.Module):\n \n def __init__(self, block, layers, widths, num_classes=1000, zero_init_residual=True,\n group_width=1, replace_stride_with_dilation=None,\n norm_layer=None):\n super(RegNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n \n self.in_planes = 32\n self.dilation = 1\n if replace_stride_with_dilation is None:\n replace_stride_with_dilation = [False, False, False, False]\n \n if len(replace_stride_with_dilation) != 4:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 4-element tuple, got {}\".format(replace_stride_with_dilation))\n \n self.group_width = group_width\n self.conv1 = nn.Conv2d(3, self.in_planes, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = norm_layer(self.in_planes)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self._make_layer(block, widths[0], layers[0], stride=2,\n dilate=replace_stride_with_dilation[0])\n self.layer2 = self._make_layer(block, widths[1], layers[1], stride=2,\n dilate=replace_stride_with_dilation[1])\n self.layer3 = self._make_layer(block, widths[2], layers[2], stride=2,\n dilate=replace_stride_with_dilation[2])\n self.layer3 = self._make_layer(block, widths[3], layers[3], stride=2,\n dilate=replace_stride_with_dilation[3])\n \n self.avgpool = nn.AdaptiveAvgPool2d((1,1))\n self.fc = nn.Linear(widths[-1] * block.expansion, num_classes)\n \n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n \n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n \n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample=None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *=stride\n stride = 1\n if stride != 1 or self.planes != planes:\n downsample = nn.Sequential(\n conv1x1(self.in_planes, planes, stride),\n norm_layer(planes),\n )\n layers = []\n layers.append(block(self.in_planes, planes, stride, downsample, self.group_width,\n previous_dilation, norm_layer))\n self.inplanes = planes\n for _ in range(1, blocks):\n layers.append(block(self.in_planes, planes, group_width=self.group_width,\n dilation = self.dilation,\n norm_layer=norm_layer))\n return nn.Sequential(*layers)\n\n def _forward_impl(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.fc(x)\n\n return x\n\n def forward(self, x):\n return self.forward_impl(x)\n\n \ndef regnetx_002(**kwargs):\n return RegNet(Bottleneck, [1,1,4,7], [24,56,152,368], group_width=8, **kwargs)\n\ndef regnetx_004(**kwargs):\n return RegNet(Bottleneck, [1,2,7,12], [32,64,160,384], group_width=16, **kwargs)\n\ndef regnetx_006(**kwargs):\n return RegNet(Bottleneck, [1,3,5,7], [48,96,240,528], group_width=24, **kwargs)\n\ndef regnetx_008(**kwargs):\n return RegNet(Bottleneck, [1,3,7,5], [64,128,288,672], group_width=16, **kwargs)\n\n\n\n \n \n \n " ]
[ [ "torch.nn.Sequential", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.AdaptiveAvgPool2d", "torch.flatten", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
mistermoutan/ModelsGenesis
[ "98af7075b93311fe655e9692773eb1ce015b8bd0" ]
[ "pytorch/ACSConv/experiments/mylib/utils.py" ]
[ "import os\nfrom sklearn.metrics import roc_auc_score\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nimport torch\nimport torch.nn as nn\nimport pandas as pd\nimport os\nimport time\nimport random\nimport torch.nn.functional as F\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport tarfile\nimport zipfile\nplt.switch_backend('agg')\n\nUSE_GPU = True\n# USE_GPU = False\nimport collections.abc\ncontainer_abcs = collections.abc\nfrom itertools import repeat\n\ndef _ntuple(n):\n def parse(x):\n if isinstance(x, container_abcs.Iterable):\n return x\n return tuple(repeat(x, n))\n return parse\n \n_single = _ntuple(1)\n_pair = _ntuple(2)\n_triple = _ntuple(3)\n_quadruple = _ntuple(4)\n\nif USE_GPU and torch.cuda.is_available():\n def to_var(x, requires_grad=False, gpu=None):\n x = x.cuda(gpu)\n return x.requires_grad_(requires_grad)\nelse:\n def to_var(x, requires_grad=False, gpu=None):\n return x.requires_grad_(requires_grad)\n\nif USE_GPU and torch.cuda.is_available():\n def to_device(x, gpu=None):\n x = x.cuda(gpu)\n return x\nelse:\n def to_device(x, gpu=None):\n return x\n\nclass AverageMeter(object):\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\nclass MultiAverageMeter(object):\n def __init__(self):\n self.meters = []\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 if len(self.meters) < len(val):\n for i in range(len(val)-len(self.meters)):\n self.meters.append(AverageMeter())\n for i, meter in enumerate(self.meters):\n meter.update(val[i],n)\n self.val = [meter.val for meter in self.meters]\n self.avg = [meter.avg for meter in self.meters]\n self.sum = [meter.sum for meter in self.meters]\n self.count = [meter.count for meter in self.meters]\n\n\n\ndef log_results(save, epoch, log_dict, writer):\n with open(os.path.join(save, 'logs.csv'), 'a') as f:\n f.write('%03d,'%((epoch + 1),))\n for value in log_dict.values():\n f.write('%0.6f,' % (value,))\n f.write('\\n')\n for key, value in log_dict.items():\n writer.add_scalar(key, value, epoch)\n\n\ndef one_hot_to_categorical(x, dim):\n return x.argmax(dim=dim)\n\ndef categorical_to_one_hot(x, dim=1, expand_dim=False, n_classes=None):\n '''Sequence and label.\n when dim = -1:\n b x 1 => b x n_classes\n when dim = 1:\n b x 1 x h x w => b x n_classes x h x w'''\n # assert (x - x.long().to(x.dtype)).max().item() < 1e-6\n if type(x)==np.ndarray:\n x = torch.Tensor(x)\n assert torch.allclose(x, x.long().to(x.dtype))\n x = x.long()\n if n_classes is None:\n n_classes = int(torch.max(x)) + 1\n if expand_dim:\n x = x.unsqueeze(dim)\n else:\n assert x.shape[dim] == 1\n shape = list(x.shape)\n shape[dim] = n_classes\n x_one_hot = torch.zeros(shape).to(x.device).scatter_(dim=dim, index=x, value=1.)\n return x_one_hot.long() \n\n\n\n\ndef plot_multi_voxels(*multi_voxels):\n multi_voxels = [np.array(voxels.cpu()) if isinstance(voxels, torch.Tensor) else np.array(voxels) for voxels in multi_voxels]\n multi_voxels = [np.expand_dims(voxels, 0) if voxels.ndim==3 else voxels for voxels in multi_voxels]\n\n rows = len(multi_voxels[0])\n columns = len(multi_voxels)\n fig = plt.figure(figsize=[10*columns,8*rows])\n for row in range(rows):\n for column in range(columns):\n if row<len(multi_voxels[column]):\n ax = fig.add_subplot(rows,columns,row*columns+column+1, projection='3d')\n ax.voxels(multi_voxels[column][row], edgecolor='k')\n\ndef plot_multi_shapes(*multi_shapes):\n multi_shapes = [np.array(shapes.cpu()) if isinstance(shapes, torch.Tensor) else np.array(shapes) for shapes in multi_shapes]\n multi_shapes = [np.expand_dims(shapes, 0) if shapes.ndim==2 else shapes for shapes in multi_shapes]\n\n rows = len(multi_shapes[0])\n columns = len(multi_shapes)\n fig = plt.figure(figsize=[10*columns,8*rows])\n for row in range(rows):\n for column in range(columns):\n if row<len(multi_shapes[column]):\n ax = fig.add_subplot(rows,columns,row*columns+column+1)\n ax.imshow(multi_shapes[column][row])\n\ndef save_model(model, save, valid_error, best_error, save_all):\n if save_all or valid_error < best_error:\n torch.save(model.state_dict(), os.path.join(save, 'model.dat'))\n if valid_error < best_error:\n best_error = valid_error\n print('New best error: %.4f' % best_error)\n\n return best_error\n\n\ndef set_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\ndef initialize(modules):\n for m in modules:\n if isinstance(m, nn.Conv3d) or isinstance(m, nn.ConvTranspose3d):\n nn.init.kaiming_uniform_(m.weight, mode='fan_in')\n elif isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_uniform_(m.weight, mode='fan_in')\n elif isinstance(m, nn.Linear):\n nn.init.kaiming_uniform_(m.weight, mode='fan_in')\n m.bias.data.zero_()\n\nimport sys, time\nclass Logger(object):\n def __init__(self, filename='terminal log.txt', stream=sys.stdout):\n self.terminal = stream\n self.log = open(filename, 'a')\n self.log.write(''.join([time.strftime(\"%y-%m-%d %H:%M:%S\", time.localtime(time.time())), '\\n\\n']))\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\n\n def __del__(self):\n self.log.write(''.join(['\\n', time.strftime(\"%y-%m-%d %H:%M:%S\", time.localtime(time.time()))]))\n self.log.close()\n\ndef redirect_stdout(save_path):\n sys.stdout = Logger(os.path.join(save_path, 'stdout.txt'), sys.stdout)\n sys.stderr = Logger(os.path.join(save_path, 'stderr.txt'), sys.stderr)\t\t# redirect std err, if necessary\n\ndef copy_file_backup(save):\n import shutil, sys, getpass, socket\n backup_dir = os.path.join(save, 'backup_code')\n os.makedirs(backup_dir)\n with open(os.path.join(backup_dir, 'CLI argument.txt'), 'w') as f:\n res = ''.join(['hostName: ', socket.gethostname(), '\\n',\n 'account: ', getpass.getuser(), '\\n',\n 'save_path: ', os.path.realpath(save), '\\n', \n 'CUDA_VISIBLE_DEVICES: ', str(os.environ.get('CUDA_VISIBLE_DEVICES')), '\\n'])\n f.write(res)\n\n for i, _ in enumerate(sys.argv):\n f.write(sys.argv[i] + '\\n')\n \n script_file = sys.argv[0]\n shutil.copy(script_file, backup_dir)\n shutil.copytree(os.path.join(sys.path[0], '../', 'mylib'), os.path.join(backup_dir, 'mylib'))\n shutil.copytree(os.path.join(sys.path[0], '../../', 'acsconv'), os.path.join(backup_dir, 'acsconv'))\n os.makedirs(os.path.join(backup_dir, 'current_experiment'))\n for file_path in os.listdir(sys.path[0]):\n if file_path not in ['tmp', 'data', '__pycache__']:\n shutil.copy(os.path.join(sys.path[0], file_path), os.path.join(backup_dir, 'current_experiment'))\n\n\nfrom .sync_batchnorm import SynchronizedBatchNorm3d, SynchronizedBatchNorm2d\ndef model_to_syncbn(model):\n preserve_state_dict = model.state_dict()\n _convert_module_from_bn_to_syncbn(model)\n model.load_state_dict(preserve_state_dict)\n return model\ndef _convert_module_from_bn_to_syncbn(module):\n for child_name, child in module.named_children(): \n if hasattr(nn, child.__class__.__name__) and \\\n 'batchnorm' in child.__class__.__name__.lower():\n TargetClass = globals()['Synchronized'+child.__class__.__name__]\n arguments = TargetClass.__init__.__code__.co_varnames[1:]\n kwargs = {k: getattr(child, k) for k in arguments}\n setattr(module, child_name, TargetClass(**kwargs))\n else:\n _convert_module_from_bn_to_syncbn(child)" ]
[ [ "numpy.expand_dims", "torch.max", "numpy.random.seed", "torch.cuda.manual_seed", "torch.Tensor", "matplotlib.pyplot.switch_backend", "torch.manual_seed", "torch.zeros", "torch.nn.init.kaiming_uniform_", "torch.cuda.is_available", "torch.cuda.manual_seed_all", "numpy.array", "matplotlib.pyplot.figure" ] ]
vb7401/pytorch-image-models
[ "d1d1115b1e07103cd97c21a63fb9dfe5af9c2047", "d1d1115b1e07103cd97c21a63fb9dfe5af9c2047" ]
[ "timm/optim/adafactor.py", "timm/models/hrnet.py" ]
[ "\"\"\" Adafactor Optimizer\n\nLifted from https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py\n\nOriginal header/copyright below.\n\n\"\"\"\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nimport torch\nimport math\n\n\nclass Adafactor(torch.optim.Optimizer):\n \"\"\"Implements Adafactor algorithm.\n This implementation is based on: `Adafactor: Adaptive Learning Rates with Sublinear Memory Cost`\n (see https://arxiv.org/abs/1804.04235)\n\n Note that this optimizer internally adjusts the learning rate depending on the\n *scale_parameter*, *relative_step* and *warmup_init* options.\n\n To use a manual (external) learning rate schedule you should set `scale_parameter=False` and\n `relative_step=False`.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining parameter groups\n lr (float, optional): external learning rate (default: None)\n eps (tuple[float, float]): regularization constants for square gradient\n and parameter scale respectively (default: (1e-30, 1e-3))\n clip_threshold (float): threshold of root mean square of final gradient update (default: 1.0)\n decay_rate (float): coefficient used to compute running averages of square gradient (default: -0.8)\n beta1 (float): coefficient used for computing running averages of gradient (default: None)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n scale_parameter (bool): if True, learning rate is scaled by root mean square of parameter (default: True)\n relative_step (bool): if True, time-dependent learning rate is computed\n instead of external learning rate (default: True)\n warmup_init (bool): time-dependent learning rate computation depends on\n whether warm-up initialization is being used (default: False)\n \"\"\"\n\n def __init__(self, params, lr=None, eps=1e-30, eps_scale=1e-3, clip_threshold=1.0,\n decay_rate=-0.8, betas=None, weight_decay=0.0, scale_parameter=True, warmup_init=False):\n relative_step = lr is None\n if warmup_init and not relative_step:\n raise ValueError('warmup_init requires relative_step=True')\n\n beta1 = None if betas is None else betas[0] # make it compat with standard betas arg\n defaults = dict(lr=lr, eps=eps, eps_scale=eps_scale, clip_threshold=clip_threshold, decay_rate=decay_rate,\n beta1=beta1, weight_decay=weight_decay, scale_parameter=scale_parameter,\n relative_step=relative_step, warmup_init=warmup_init)\n super(Adafactor, self).__init__(params, defaults)\n\n @staticmethod\n def _get_lr(param_group, param_state):\n if param_group['relative_step']:\n min_step = 1e-6 * param_state['step'] if param_group['warmup_init'] else 1e-2\n lr_t = min(min_step, 1.0 / math.sqrt(param_state['step']))\n param_scale = 1.0\n if param_group['scale_parameter']:\n param_scale = max(param_group['eps_scale'], param_state['RMS'])\n param_group['lr'] = lr_t * param_scale\n return param_group['lr']\n\n @staticmethod\n def _get_options(param_group, param_shape):\n factored = len(param_shape) >= 2\n use_first_moment = param_group['beta1'] is not None\n return factored, use_first_moment\n\n @staticmethod\n def _rms(tensor):\n return tensor.norm(2) / (tensor.numel() ** 0.5)\n\n def _approx_sq_grad(self, exp_avg_sq_row, exp_avg_sq_col):\n r_factor = (exp_avg_sq_row / exp_avg_sq_row.mean(dim=-1, keepdim=True)).rsqrt_().unsqueeze(-1)\n c_factor = exp_avg_sq_col.unsqueeze(-2).rsqrt()\n return torch.mul(r_factor, c_factor)\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 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.dtype in {torch.float16, torch.bfloat16}:\n grad = grad.float()\n if grad.is_sparse:\n raise RuntimeError('Adafactor does not support sparse gradients.')\n\n state = self.state[p]\n grad_shape = grad.shape\n\n factored, use_first_moment = self._get_options(group, grad_shape)\n # State Initialization\n if len(state) == 0:\n state['step'] = 0\n\n if use_first_moment:\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(grad)\n if factored:\n state['exp_avg_sq_row'] = torch.zeros(grad_shape[:-1]).to(grad)\n state['exp_avg_sq_col'] = torch.zeros(grad_shape[:-2] + grad_shape[-1:]).to(grad)\n else:\n state['exp_avg_sq'] = torch.zeros_like(grad)\n\n state['RMS'] = 0\n else:\n if use_first_moment:\n state['exp_avg'] = state['exp_avg'].to(grad)\n if factored:\n state['exp_avg_sq_row'] = state['exp_avg_sq_row'].to(grad)\n state['exp_avg_sq_col'] = state['exp_avg_sq_col'].to(grad)\n else:\n state['exp_avg_sq'] = state['exp_avg_sq'].to(grad)\n\n p_data_fp32 = p.data\n if p.data.dtype in {torch.float16, torch.bfloat16}:\n p_data_fp32 = p_data_fp32.float()\n\n state['step'] += 1\n state['RMS'] = self._rms(p_data_fp32)\n lr_t = self._get_lr(group, state)\n\n beta2t = 1.0 - math.pow(state['step'], group['decay_rate'])\n update = grad ** 2 + group['eps']\n if factored:\n exp_avg_sq_row = state['exp_avg_sq_row']\n exp_avg_sq_col = state['exp_avg_sq_col']\n\n exp_avg_sq_row.mul_(beta2t).add_(1.0 - beta2t, update.mean(dim=-1))\n exp_avg_sq_col.mul_(beta2t).add_(1.0 - beta2t, update.mean(dim=-2))\n #exp_avg_sq_row.mul_(beta2t).add_(update.mean(dim=-1), alpha=1.0 - beta2t) # pytorch 1.6+\n #exp_avg_sq_col.mul_(beta2t).add_(update.mean(dim=-2), alpha=1.0 - beta2t)\n\n # Approximation of exponential moving average of square of gradient\n update = self._approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col)\n update.mul_(grad)\n else:\n exp_avg_sq = state['exp_avg_sq']\n\n exp_avg_sq.mul_(beta2t).add_(1.0 - beta2t, update)\n #exp_avg_sq.mul_(beta2t).add_(update, alpha=1.0 - beta2t) # pytorch 1.6+\n update = exp_avg_sq.rsqrt().mul_(grad)\n\n update.div_((self._rms(update) / group['clip_threshold']).clamp_(min=1.0))\n update.mul_(lr_t)\n\n if use_first_moment:\n exp_avg = state['exp_avg']\n exp_avg.mul_(group[\"beta1\"]).add_(1 - group[\"beta1\"], update)\n #exp_avg.mul_(group['beta1']).add_(update, alpha=1 - group['beta1']) # pytorch 1.6+\n update = exp_avg\n\n if group['weight_decay'] != 0:\n p_data_fp32.add_(-group[\"weight_decay\"] * lr_t, p_data_fp32)\n #p_data_fp32.add_(p_data_fp32, alpha=-group['weight_decay'] * lr_t) # pytorch 1.6+\n\n p_data_fp32.add_(-update)\n\n if p.data.dtype in {torch.float16, torch.bfloat16}:\n p.data.copy_(p_data_fp32)\n\n return loss", "\"\"\" HRNet\n\nCopied from https://github.com/HRNet/HRNet-Image-Classification\n\nOriginal header:\n Copyright (c) Microsoft\n Licensed under the MIT License.\n Written by Bin Xiao (Bin.Xiao@microsoft.com)\n Modified by Ke Sun (sunk@mail.ustc.edu.cn)\n\"\"\"\nimport logging\nfrom typing import List\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD\nfrom .features import FeatureInfo\nfrom .helpers import build_model_with_cfg, default_cfg_for_features\nfrom .layers import create_classifier\nfrom .registry import register_model\nfrom .resnet import BasicBlock, Bottleneck # leveraging ResNet blocks w/ additional features like SE\n\n_BN_MOMENTUM = 0.1\n_logger = logging.getLogger(__name__)\n\n\ndef _cfg(url='', **kwargs):\n return {\n 'url': url,\n 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),\n 'crop_pct': 0.875, 'interpolation': 'bilinear',\n 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,\n 'first_conv': 'conv1', 'classifier': 'classifier',\n **kwargs\n }\n\n\ndefault_cfgs = {\n 'hrnet_w18_small': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnet_w18_small_v1-f460c6bc.pth'),\n 'hrnet_w18_small_v2': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnet_w18_small_v2-4c50a8cb.pth'),\n 'hrnet_w18': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w18-8cb57bb9.pth'),\n 'hrnet_w30': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w30-8d7f8dab.pth'),\n 'hrnet_w32': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w32-90d8c5fb.pth'),\n 'hrnet_w40': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w40-7cd397a4.pth'),\n 'hrnet_w44': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w44-c9ac8c18.pth'),\n 'hrnet_w48': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w48-abd2e6ab.pth'),\n 'hrnet_w64': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-hrnet/hrnetv2_w64-b47cc881.pth'),\n}\n\ncfg_cls = dict(\n hrnet_w18_small=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(1,),\n NUM_CHANNELS=(32,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(2, 2),\n NUM_CHANNELS=(16, 32),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(2, 2, 2),\n NUM_CHANNELS=(16, 32, 64),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(2, 2, 2, 2),\n NUM_CHANNELS=(16, 32, 64, 128),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w18_small_v2=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(2,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(2, 2),\n NUM_CHANNELS=(18, 36),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(2, 2, 2),\n NUM_CHANNELS=(18, 36, 72),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=2,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(2, 2, 2, 2),\n NUM_CHANNELS=(18, 36, 72, 144),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w18=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(18, 36),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(18, 36, 72),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(18, 36, 72, 144),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w30=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(30, 60),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(30, 60, 120),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(30, 60, 120, 240),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w32=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(32, 64),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(32, 64, 128),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(32, 64, 128, 256),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w40=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(40, 80),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(40, 80, 160),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(40, 80, 160, 320),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w44=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(44, 88),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(44, 88, 176),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(44, 88, 176, 352),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w48=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(48, 96),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(48, 96, 192),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(48, 96, 192, 384),\n FUSE_METHOD='SUM',\n ),\n ),\n\n hrnet_w64=dict(\n STEM_WIDTH=64,\n STAGE1=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=1,\n BLOCK='BOTTLENECK',\n NUM_BLOCKS=(4,),\n NUM_CHANNELS=(64,),\n FUSE_METHOD='SUM',\n ),\n STAGE2=dict(\n NUM_MODULES=1,\n NUM_BRANCHES=2,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4),\n NUM_CHANNELS=(64, 128),\n FUSE_METHOD='SUM'\n ),\n STAGE3=dict(\n NUM_MODULES=4,\n NUM_BRANCHES=3,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4),\n NUM_CHANNELS=(64, 128, 256),\n FUSE_METHOD='SUM'\n ),\n STAGE4=dict(\n NUM_MODULES=3,\n NUM_BRANCHES=4,\n BLOCK='BASIC',\n NUM_BLOCKS=(4, 4, 4, 4),\n NUM_CHANNELS=(64, 128, 256, 512),\n FUSE_METHOD='SUM',\n ),\n )\n)\n\n\nclass HighResolutionModule(nn.Module):\n def __init__(self, num_branches, blocks, num_blocks, num_inchannels,\n num_channels, fuse_method, multi_scale_output=True):\n super(HighResolutionModule, self).__init__()\n self._check_branches(\n num_branches, blocks, num_blocks, num_inchannels, num_channels)\n\n self.num_inchannels = num_inchannels\n self.fuse_method = fuse_method\n self.num_branches = num_branches\n\n self.multi_scale_output = multi_scale_output\n\n self.branches = self._make_branches(\n num_branches, blocks, num_blocks, num_channels)\n self.fuse_layers = self._make_fuse_layers()\n self.fuse_act = nn.ReLU(False)\n\n def _check_branches(self, num_branches, blocks, num_blocks, num_inchannels, num_channels):\n error_msg = ''\n if num_branches != len(num_blocks):\n error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(num_branches, len(num_blocks))\n elif num_branches != len(num_channels):\n error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(num_branches, len(num_channels))\n elif num_branches != len(num_inchannels):\n error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(num_branches, len(num_inchannels))\n if error_msg:\n _logger.error(error_msg)\n raise ValueError(error_msg)\n\n def _make_one_branch(self, branch_index, block, num_blocks, num_channels, stride=1):\n downsample = None\n if stride != 1 or self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(\n self.num_inchannels[branch_index], num_channels[branch_index] * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(num_channels[branch_index] * block.expansion, momentum=_BN_MOMENTUM),\n )\n\n layers = [block(self.num_inchannels[branch_index], num_channels[branch_index], stride, downsample)]\n self.num_inchannels[branch_index] = num_channels[branch_index] * block.expansion\n for i in range(1, num_blocks[branch_index]):\n layers.append(block(self.num_inchannels[branch_index], num_channels[branch_index]))\n\n return nn.Sequential(*layers)\n\n def _make_branches(self, num_branches, block, num_blocks, num_channels):\n branches = []\n for i in range(num_branches):\n branches.append(self._make_one_branch(i, block, num_blocks, num_channels))\n\n return nn.ModuleList(branches)\n\n def _make_fuse_layers(self):\n if self.num_branches == 1:\n return nn.Identity()\n\n num_branches = self.num_branches\n num_inchannels = self.num_inchannels\n fuse_layers = []\n for i in range(num_branches if self.multi_scale_output else 1):\n fuse_layer = []\n for j in range(num_branches):\n if j > i:\n fuse_layer.append(nn.Sequential(\n nn.Conv2d(num_inchannels[j], num_inchannels[i], 1, 1, 0, bias=False),\n nn.BatchNorm2d(num_inchannels[i], momentum=_BN_MOMENTUM),\n nn.Upsample(scale_factor=2 ** (j - i), mode='nearest')))\n elif j == i:\n fuse_layer.append(nn.Identity())\n else:\n conv3x3s = []\n for k in range(i - j):\n if k == i - j - 1:\n num_outchannels_conv3x3 = num_inchannels[i]\n conv3x3s.append(nn.Sequential(\n nn.Conv2d(num_inchannels[j], num_outchannels_conv3x3, 3, 2, 1, bias=False),\n nn.BatchNorm2d(num_outchannels_conv3x3, momentum=_BN_MOMENTUM)))\n else:\n num_outchannels_conv3x3 = num_inchannels[j]\n conv3x3s.append(nn.Sequential(\n nn.Conv2d(num_inchannels[j], num_outchannels_conv3x3, 3, 2, 1, bias=False),\n nn.BatchNorm2d(num_outchannels_conv3x3, momentum=_BN_MOMENTUM),\n nn.ReLU(False)))\n fuse_layer.append(nn.Sequential(*conv3x3s))\n fuse_layers.append(nn.ModuleList(fuse_layer))\n\n return nn.ModuleList(fuse_layers)\n\n def get_num_inchannels(self):\n return self.num_inchannels\n\n def forward(self, x: List[torch.Tensor]):\n if self.num_branches == 1:\n return [self.branches[0](x[0])]\n\n for i, branch in enumerate(self.branches):\n x[i] = branch(x[i])\n\n x_fuse = []\n for i, fuse_outer in enumerate(self.fuse_layers):\n y = x[0] if i == 0 else fuse_outer[0](x[0])\n for j in range(1, self.num_branches):\n if i == j:\n y = y + x[j]\n else:\n y = y + fuse_outer[j](x[j])\n x_fuse.append(self.fuse_act(y))\n\n return x_fuse\n\n\nblocks_dict = {\n 'BASIC': BasicBlock,\n 'BOTTLENECK': Bottleneck\n}\n\n\nclass HighResolutionNet(nn.Module):\n\n def __init__(self, cfg, in_chans=3, num_classes=1000, global_pool='avg', drop_rate=0.0, head='classification'):\n super(HighResolutionNet, self).__init__()\n self.num_classes = num_classes\n self.drop_rate = drop_rate\n\n stem_width = cfg['STEM_WIDTH']\n self.conv1 = nn.Conv2d(in_chans, stem_width, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(stem_width, momentum=_BN_MOMENTUM)\n self.act1 = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(stem_width, 64, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(64, momentum=_BN_MOMENTUM)\n self.act2 = nn.ReLU(inplace=True)\n\n self.stage1_cfg = cfg['STAGE1']\n num_channels = self.stage1_cfg['NUM_CHANNELS'][0]\n block = blocks_dict[self.stage1_cfg['BLOCK']]\n num_blocks = self.stage1_cfg['NUM_BLOCKS'][0]\n self.layer1 = self._make_layer(block, 64, num_channels, num_blocks)\n stage1_out_channel = block.expansion * num_channels\n\n self.stage2_cfg = cfg['STAGE2']\n num_channels = self.stage2_cfg['NUM_CHANNELS']\n block = blocks_dict[self.stage2_cfg['BLOCK']]\n num_channels = [num_channels[i] * block.expansion for i in range(len(num_channels))]\n self.transition1 = self._make_transition_layer([stage1_out_channel], num_channels)\n self.stage2, pre_stage_channels = self._make_stage(self.stage2_cfg, num_channels)\n\n self.stage3_cfg = cfg['STAGE3']\n num_channels = self.stage3_cfg['NUM_CHANNELS']\n block = blocks_dict[self.stage3_cfg['BLOCK']]\n num_channels = [num_channels[i] * block.expansion for i in range(len(num_channels))]\n self.transition2 = self._make_transition_layer(pre_stage_channels, num_channels)\n self.stage3, pre_stage_channels = self._make_stage(self.stage3_cfg, num_channels)\n\n self.stage4_cfg = cfg['STAGE4']\n num_channels = self.stage4_cfg['NUM_CHANNELS']\n block = blocks_dict[self.stage4_cfg['BLOCK']]\n num_channels = [num_channels[i] * block.expansion for i in range(len(num_channels))]\n self.transition3 = self._make_transition_layer(pre_stage_channels, num_channels)\n self.stage4, pre_stage_channels = self._make_stage(self.stage4_cfg, num_channels, multi_scale_output=True)\n\n self.head = head\n self.head_channels = None # set if _make_head called\n if head == 'classification':\n # Classification Head\n self.num_features = 2048\n self.incre_modules, self.downsamp_modules, self.final_layer = self._make_head(pre_stage_channels)\n self.global_pool, self.classifier = create_classifier(\n self.num_features, self.num_classes, pool_type=global_pool)\n elif head == 'incre':\n self.num_features = 2048\n self.incre_modules, _, _ = self._make_head(pre_stage_channels, True)\n else:\n self.incre_modules = None\n self.num_features = 256\n\n curr_stride = 2\n # module names aren't actually valid here, hook or FeatureNet based extraction would not work\n self.feature_info = [dict(num_chs=64, reduction=curr_stride, module='stem')]\n for i, c in enumerate(self.head_channels if self.head_channels else num_channels):\n curr_stride *= 2\n c = c * 4 if self.head_channels else c # head block expansion factor of 4\n self.feature_info += [dict(num_chs=c, reduction=curr_stride, module=f'stage{i + 1}')]\n\n self.init_weights()\n\n def _make_head(self, pre_stage_channels, incre_only=False):\n head_block = Bottleneck\n self.head_channels = [32, 64, 128, 256]\n\n # Increasing the #channels on each resolution\n # from C, 2C, 4C, 8C to 128, 256, 512, 1024\n incre_modules = []\n for i, channels in enumerate(pre_stage_channels):\n incre_modules.append(self._make_layer(head_block, channels, self.head_channels[i], 1, stride=1))\n incre_modules = nn.ModuleList(incre_modules)\n if incre_only:\n return incre_modules, None, None\n\n # downsampling modules\n downsamp_modules = []\n for i in range(len(pre_stage_channels) - 1):\n in_channels = self.head_channels[i] * head_block.expansion\n out_channels = self.head_channels[i + 1] * head_block.expansion\n downsamp_module = nn.Sequential(\n nn.Conv2d(\n in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(out_channels, momentum=_BN_MOMENTUM),\n nn.ReLU(inplace=True)\n )\n downsamp_modules.append(downsamp_module)\n downsamp_modules = nn.ModuleList(downsamp_modules)\n\n final_layer = nn.Sequential(\n nn.Conv2d(\n in_channels=self.head_channels[3] * head_block.expansion,\n out_channels=self.num_features, kernel_size=1, stride=1, padding=0\n ),\n nn.BatchNorm2d(self.num_features, momentum=_BN_MOMENTUM),\n nn.ReLU(inplace=True)\n )\n\n return incre_modules, downsamp_modules, final_layer\n\n def _make_transition_layer(self, num_channels_pre_layer, num_channels_cur_layer):\n num_branches_cur = len(num_channels_cur_layer)\n num_branches_pre = len(num_channels_pre_layer)\n\n transition_layers = []\n for i in range(num_branches_cur):\n if i < num_branches_pre:\n if num_channels_cur_layer[i] != num_channels_pre_layer[i]:\n transition_layers.append(nn.Sequential(\n nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False),\n nn.BatchNorm2d(num_channels_cur_layer[i], momentum=_BN_MOMENTUM),\n nn.ReLU(inplace=True)))\n else:\n transition_layers.append(nn.Identity())\n else:\n conv3x3s = []\n for j in range(i + 1 - num_branches_pre):\n inchannels = num_channels_pre_layer[-1]\n outchannels = num_channels_cur_layer[i] if j == i - num_branches_pre else inchannels\n conv3x3s.append(nn.Sequential(\n nn.Conv2d(inchannels, outchannels, 3, 2, 1, bias=False),\n nn.BatchNorm2d(outchannels, momentum=_BN_MOMENTUM),\n nn.ReLU(inplace=True)))\n transition_layers.append(nn.Sequential(*conv3x3s))\n\n return nn.ModuleList(transition_layers)\n\n def _make_layer(self, block, inplanes, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion, momentum=_BN_MOMENTUM),\n )\n\n layers = [block(inplanes, planes, stride, downsample)]\n inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def _make_stage(self, layer_config, num_inchannels, multi_scale_output=True):\n num_modules = layer_config['NUM_MODULES']\n num_branches = layer_config['NUM_BRANCHES']\n num_blocks = layer_config['NUM_BLOCKS']\n num_channels = layer_config['NUM_CHANNELS']\n block = blocks_dict[layer_config['BLOCK']]\n fuse_method = layer_config['FUSE_METHOD']\n\n modules = []\n for i in range(num_modules):\n # multi_scale_output is only used last module\n reset_multi_scale_output = multi_scale_output or i < num_modules - 1\n modules.append(HighResolutionModule(\n num_branches, block, num_blocks, num_inchannels, num_channels, fuse_method, reset_multi_scale_output)\n )\n num_inchannels = modules[-1].get_num_inchannels()\n\n return nn.Sequential(*modules), num_inchannels\n\n def init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(\n m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def get_classifier(self):\n return self.classifier\n\n def reset_classifier(self, num_classes, global_pool='avg'):\n self.num_classes = num_classes\n self.global_pool, self.classifier = create_classifier(\n self.num_features, self.num_classes, pool_type=global_pool)\n\n def stages(self, x) -> List[torch.Tensor]:\n x = self.layer1(x)\n\n xl = [t(x) for i, t in enumerate(self.transition1)]\n yl = self.stage2(xl)\n\n xl = [t(yl[-1]) if not isinstance(t, nn.Identity) else yl[i] for i, t in enumerate(self.transition2)]\n yl = self.stage3(xl)\n\n xl = [t(yl[-1]) if not isinstance(t, nn.Identity) else yl[i] for i, t in enumerate(self.transition3)]\n yl = self.stage4(xl)\n return yl\n\n def forward_features(self, x):\n # Stem\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.act1(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.act2(x)\n\n # Stages\n yl = self.stages(x)\n\n # Classification Head\n y = self.incre_modules[0](yl[0])\n for i, down in enumerate(self.downsamp_modules):\n y = self.incre_modules[i + 1](yl[i + 1]) + down(y)\n y = self.final_layer(y)\n return y\n\n def forward(self, x):\n x = self.forward_features(x)\n x = self.global_pool(x)\n if self.drop_rate > 0.:\n x = F.dropout(x, p=self.drop_rate, training=self.training)\n x = self.classifier(x)\n return x\n\n\nclass HighResolutionNetFeatures(HighResolutionNet):\n \"\"\"HighResolutionNet feature extraction\n\n The design of HRNet makes it easy to grab feature maps, this class provides a simple wrapper to do so.\n It would be more complicated to use the FeatureNet helpers.\n\n The `feature_location=incre` allows grabbing increased channel count features using part of the\n classification head. If `feature_location=''` the default HRNet features are returned. First stem\n conv is used for stride 2 features.\n \"\"\"\n\n def __init__(self, cfg, in_chans=3, num_classes=1000, global_pool='avg', drop_rate=0.0,\n feature_location='incre', out_indices=(0, 1, 2, 3, 4)):\n assert feature_location in ('incre', '')\n super(HighResolutionNetFeatures, self).__init__(\n cfg, in_chans=in_chans, num_classes=num_classes, global_pool=global_pool,\n drop_rate=drop_rate, head=feature_location)\n self.feature_info = FeatureInfo(self.feature_info, out_indices)\n self._out_idx = {i for i in out_indices}\n\n def forward_features(self, x):\n assert False, 'Not supported'\n\n def forward(self, x) -> List[torch.tensor]:\n out = []\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.act1(x)\n if 0 in self._out_idx:\n out.append(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.act2(x)\n x = self.stages(x)\n if self.incre_modules is not None:\n x = [incre(f) for f, incre in zip(x, self.incre_modules)]\n for i, f in enumerate(x):\n if i + 1 in self._out_idx:\n out.append(f)\n return out\n\n\ndef _create_hrnet(variant, pretrained, **model_kwargs):\n model_cls = HighResolutionNet\n features_only = False\n if model_kwargs.pop('features_only', False):\n model_cls = HighResolutionNetFeatures\n model_kwargs['num_classes'] = 0\n features_only = True\n model = build_model_with_cfg(\n model_cls, variant, pretrained, default_cfg=default_cfgs[variant],\n model_cfg=cfg_cls[variant], pretrained_strict=not features_only, **model_kwargs)\n if features_only:\n model.default_cfg = default_cfg_for_features(model.default_cfg)\n return model\n\n\n@register_model\ndef hrnet_w18_small(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w18_small', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w18_small_v2(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w18_small_v2', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w18(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w18', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w30(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w30', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w32(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w32', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w40(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w40', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w44(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w44', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w48(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w48', pretrained, **kwargs)\n\n\n@register_model\ndef hrnet_w64(pretrained=True, **kwargs):\n return _create_hrnet('hrnet_w64', pretrained, **kwargs)\n" ]
[ [ "torch.mul", "torch.zeros_like", "torch.zeros" ], [ "torch.nn.Sequential", "torch.nn.functional.dropout", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.Identity", "torch.nn.Upsample", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
Mesitis/luminoth
[ "8c334a7f7a105e7a6f79085dbc521d9cc4151786" ]
[ "sonnet/python/modules/layer_norm.py" ]
[ "# Copyright 2017 The Sonnet Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\"\"\"Layer normalization module for Sonnet.\n\nThis contains the module LayerNorm, which performs layer normalization on\nits inputs.\n\nOriginal paper: https://arxiv.org/abs/1607.06450.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nfrom sonnet.python.modules import base\nfrom sonnet.python.modules import util\n\nimport tensorflow as tf\n\n\nclass LayerNorm(base.AbstractModule):\n \"\"\"Layer normalization module.\n\n Implementation based on:\n https://arxiv.org/abs/1607.06450\n\n This module transforms input x into:\n\n outputs = gamma * (x - mu) / sigma + beta\n\n where mu and sigma are respectively the mean and standard deviation of x.\n Gamma and beta are trainable parameters for scaling and shifting respectively.\n\n \"\"\"\n\n GAMMA = \"gamma\" # Layer norm scaling.\n BETA = \"beta\" # Layer norm bias.\n\n POSSIBLE_INITIALIZER_KEYS = {GAMMA, BETA}\n # Keep old name for backwards compatibility\n\n POSSIBLE_KEYS = POSSIBLE_INITIALIZER_KEYS\n\n def __init__(\n self,\n eps=1e-5,\n initializers=None,\n partitioners=None,\n regularizers=None,\n name=\"layer_norm\",\n ):\n \"\"\"Constructs a LayerNorm module.\n\n Args:\n eps: small epsilon to avoid division by zero variance. Defaults to\n 1e-5 as used in the paper.\n initializers: Dict containing ops to initialize the scale\n (with key 'gamma') and bias (with key 'beta').\n partitioners: Optional dict containing partitioners to partition\n the scale (with key 'gamma') and bias (with key 'beta'). As a default,\n no partitioners are used.\n regularizers: Optional dict containing regularizers for the scale (with\n key 'gamma') and bias (with key 'beta').. As a default, no regularizers\n are used.\n name: name of the module.\n\n Raises:\n KeyError: If `initializers`, `partitioners` or `regularizers` contain\n any keys other than `gamma` or `beta`.\n TypeError: If any of the given initializers, partitioners or regularizers\n are not callable.\n \"\"\"\n super(LayerNorm, self).__init__(name=name)\n\n self._eps = eps\n\n self._initializers = util.check_initializers(initializers, self.POSSIBLE_INITIALIZER_KEYS)\n self._partitioners = util.check_partitioners(partitioners, self.POSSIBLE_INITIALIZER_KEYS)\n self._regularizers = util.check_regularizers(regularizers, self.POSSIBLE_INITIALIZER_KEYS)\n\n def _build(self, inputs):\n \"\"\"Connects the LayerNorm module into the graph.\n\n Args:\n inputs: a Tensor of shape `[batch_size, layer_dim]`.\n\n Returns:\n normalized: layer normalized outputs with same shape as inputs.\n\n Raises:\n base.NotSupportedError: If `inputs` has data type of `tf.float16`.\n \"\"\"\n\n if inputs.dtype == tf.float16:\n raise base.NotSupportedError(\n \"LayerNorm does not support `tf.float16`, insufficient \"\n \"precision for calculating sufficient statistics.\"\n )\n\n if inputs.get_shape().ndims != 2:\n raise base.NotSupportedError(\n \"Layer normalization expects inputs of rank 2.\"\n \" Got inputs of rank {}.\".format(inputs.get_shape().ndims)\n )\n\n hidden_size = inputs.get_shape()[1].value\n\n if self.GAMMA not in self._initializers:\n self._initializers[self.GAMMA] = create_gamma_initializer()\n self._gamma = tf.get_variable(\n self.GAMMA,\n shape=[hidden_size],\n dtype=inputs.dtype,\n initializer=self._initializers[self.GAMMA],\n partitioner=self._partitioners.get(self.GAMMA),\n regularizer=self._regularizers.get(self.GAMMA),\n )\n\n if self.BETA not in self._initializers:\n self._initializers[self.BETA] = create_beta_initializer()\n self._beta = tf.get_variable(\n self.BETA,\n shape=[hidden_size],\n dtype=inputs.dtype,\n initializer=self._initializers[self.BETA],\n partitioner=self._partitioners.get(self.BETA),\n regularizer=self._regularizers.get(self.BETA),\n )\n\n mean, var = tf.nn.moments(inputs, [1], keep_dims=True)\n\n normalized = tf.nn.batch_normalization(inputs, mean, var, self._beta, self._gamma, self._eps)\n return normalized\n\n @property\n def initializers(self):\n return self._initializers\n\n @property\n def partitioners(self):\n return self._partitioners\n\n @property\n def regularizers(self):\n return self._regularizers\n\n @property\n def beta(self):\n self._ensure_is_connected()\n return self._beta\n\n @property\n def gamma(self):\n self._ensure_is_connected()\n return self._gamma\n\n\ndef create_beta_initializer():\n \"\"\"Returns a default initializer for the `beta` in layer norm.\"\"\"\n return tf.zeros_initializer()\n\n\ndef create_gamma_initializer():\n \"\"\"Returns a default initializer for the `gamma` in layer norm.\"\"\"\n return tf.ones_initializer()\n" ]
[ [ "tensorflow.ones_initializer", "tensorflow.nn.moments", "tensorflow.zeros_initializer", "tensorflow.nn.batch_normalization" ] ]
yigitozgumus/IACV_Project
[ "0e012139a33c76ca88505c28270f1250181ec701" ]
[ "train.py" ]
[ "import tensorflow as tf\nfrom utils.utils import get_args\nfrom utils.config import process_config\nfrom utils.factory import create\nfrom utils.dirs import create_dirs\nfrom utils.logger import Logger\nfrom utils.copy_codebase import copy_codebase\nimport os\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"True\"\n\n\ndef run():\n # Get the arguments\n args = get_args()\n config = process_config(args.config, args.experiment)\n # create the experiments dirs\n create_dirs(\n [\n config.log.summary_dir,\n config.log.checkpoint_dir,\n config.log.step_generation_dir,\n config.log.log_file_dir,\n config.log.codebase_dir,\n ]\n )\n\n # Copy the model code and the trainer code to the experiment folder\n copy_codebase(config)\n\n l = Logger(config)\n logger = l.get_logger(__name__)\n # Create the tensorflow session\n sess = tf.Session()\n # Create the dataloader\n data = create(\"data_loader.\" + config.data_loader.name)(config)\n # Create the model instance\n model = create(\"models.\" + config.model.name)(config)\n # Create the summarizer Object\n summarizer = create(\"utils.\" + config.log.name)(sess, config)\n # Create the trainer\n trainer = create(\"trainers.\" + config.trainer.name)(sess, model, data, config, summarizer)\n # Load model if exists\n model.load(sess)\n # Train the model\n trainer.train()\n # Test the model\n if config.trainer.test_at_end:\n trainer.test()\n logger.info(\"Experiment has ended.\")\n\n\nif __name__ == \"__main__\":\n run()\n" ]
[ [ "tensorflow.Session" ] ]
qai222/ATMOxide
[ "42702c1ce299233569c8a3c0a9712b0e62ef6b16" ]
[ "Floats/Figure_1/amine_occurance_class.py" ]
[ "import pandas as pd\nfrom collections import Counter\nfrom AnalysisModule.routines.util import read_jsonfile\n\ninput_df = pd.read_csv(\"../../DataGeneration/5_SimpleInput/input.csv\")\nsmi2cluster = read_jsonfile(\"../../DataGeneration/6_AmineCluster/smiles_labeled_umap.json\")\n\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'font.size': 14})\nfig, ax1 = plt.subplots(figsize=(7, 7))\n\ncolor = 'black'\nax1.tick_params(axis='y', labelcolor=color)\n\n\ndef get_unique_amine_x_cumulative_y_numentries(input_df:pd.DataFrame):\n ncrystals = len(input_df)\n amine_counter = Counter(input_df[\"smiles\"])\n namines = len(amine_counter.keys())\n\n cumulative_x = sorted(amine_counter.keys(), key=lambda x: amine_counter[x], reverse=True)\n ys = []\n cumulative_y = []\n nx = 0\n for x in cumulative_x:\n nx += amine_counter[x]\n ys.append(amine_counter[x])\n cumulative_y.append(nx / ncrystals)\n\n xs = [x / namines for x in range(namines)]\n return xs, cumulative_y, ys\n\ncolors = [\"gray\", \"navy\", \"orchid\", \"orange\"]\nclusters = [\"total\", 0, 1, 2]\nmarkers= [\"x\", \"^\", \"o\", \"s\"]\nfor cluster, color, markertype in zip(clusters, colors, markers):\n df = input_df.copy()\n if isinstance(cluster, int):\n df[\"smi_cluster\"] = [smi2cluster[smi] for smi in input_df[\"smiles\"]]\n df = df[df[\"smi_cluster\"] == cluster]\n\n xs, c_y, ys = get_unique_amine_x_cumulative_y_numentries(df)\n # ax1.plot(xs, ys, \"o:\", markersize=3, label=str(cluster))\n if cluster == \"total\":\n lab = cluster\n else:\n lab = \"cluster: {}\".format(cluster)\n ax1.plot(xs, c_y, markertype, markersize=4, color=color, label=lab)\n\nax1.set_xlim([-0.05, 1.05])\nax1.set_xlabel('Cumulative proportion of unique amines')\nax1.set_ylabel('Cumulative proportion of structures', color=\"k\")\n# fig.legend(loc=\"lower right\")\nfig.legend(loc='lower right',\n bbox_to_anchor=(0.95, 0.2),\n )\nfig.tight_layout() # otherwise the right y-label is slightly clipped\nfig.savefig(\"amine_occurance_class.eps\")\nfig.savefig(\"amine_occurance_class.png\", dpi=300)\n\n\n" ]
[ [ "matplotlib.pyplot.rcParams.update", "pandas.read_csv", "matplotlib.pyplot.subplots" ] ]
ttumiel/interpret
[ "aeecb00bf65376668a48895cb707beb6dd8fb7ab" ]
[ "test/test_transforms.py" ]
[ "import pytest\nimport torch\nfrom PIL import Image\nimport numpy as np\n\nfrom interpret.transforms import scale, translate, shear, rotate, RandomTransform, _random_params\n\n@pytest.fixture(scope='module')\ndef tensor():\n d = 'cuda' if torch.cuda.is_available() else 'cpu'\n return torch.arange(4).view(2,2).float()[None, None].to(d)\n\n\ndef test_translate(tensor):\n trans_x = translate(1, 0)(tensor)\n out = torch.stack([tensor[...,0], tensor[...,0]]).permute((1,2,3,0))\n assert torch.all(trans_x == out)\n\n trans_y = translate(0, 1)(tensor)\n out = torch.stack([tensor[...,1,:], tensor[...,1,:]]).permute((1,2,0,3))\n assert torch.all(trans_y == out)\n\ndef test_rotate(tensor):\n rot_45 = rotate(45)(tensor)\n t = tensor.squeeze()\n out = torch.tensor([\n [(t[0,0]+t[0,1])/2, (t[0,1]+t[1,1])/2],\n [(t[0,0]+t[1,0])/2, (t[1,0]+t[1,1])/2],\n ]).to(rot_45.device)\n assert torch.all(rot_45 == out)\n\ndef test_scale(tensor):\n scale_2 = scale(2)(tensor)\n\n im = Image.fromarray(tensor.cpu().squeeze().numpy()).resize((4,4), resample=Image.BILINEAR)\n out = torch.tensor(np.array(im)[1:3,1:3]).to(tensor.device)\n assert torch.all(out == scale_2)\n\ndef test_shear(tensor):\n shear_1 = shear(1)(tensor)\n out = tensor.clone()\n out[...,0,1] = (out[...,0,0]+out[...,0,1])/2\n out[...,1,0] = (out[...,1,0]+out[...,1,1])/2\n assert torch.all(out == shear_1)\n\ndef test_random_transform():\n def raise_call():\n raise RuntimeError('This transform should not have run but did.')\n t = RandomTransform(raise_call, p=0)\n for _ in range(10):\n t(None)\n\ndef test_random_params():\n for _ in range(10):\n out = _random_params(1,2)\n assert -1 <= out[0] <= 1\n assert -2 <= out[1] <= 2\n\n out = _random_params([0,2],[-1,4])\n assert 0 <= out[0] <= 2\n assert -1 <= out[1] <= 4\n\n" ]
[ [ "torch.all", "torch.tensor", "torch.cuda.is_available", "torch.arange", "torch.stack", "numpy.array" ] ]
joshim5/CRISPR-Library-Designer
[ "2def1e4351c82056587620f7520ec922761ac8f3" ]
[ "static/data/pre_processed/additional_scripts/generation/compile_exome_2.py" ]
[ "# pool exome into single file\nimport os\nimport pandas as pd\nimport gzip\nfrom Bio import SeqIO\n\nAPP_STATIC = \"/home/joshm/GUIDES/CRISPR-Library-Designer/static\"\n\nccds_coords = os.path.join(APP_STATIC, 'data/pre_processed/CDS', 'CCDS_coords.csv')\n\nchrom_seq_base = os.path.join(APP_STATIC, \"data/GRCh37/Homo_sapiens.GRCh37.75.dna.chromosome.{}.fa.gz\")\n\noutput_path = os.path.join(APP_STATIC, \"data\", \"exome_hum_ccds.txt\")\n\nexome_output_str = \"\"\n\nrevcompl = lambda x: ''.join([{'N': 'N','A':'T','C':'G','G':'C','T':'A'}[B] for B in x][::-1])\n\ndef union_intervals(intervals):\n sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])\n merged = []\n for higher in sorted_by_lower_bound:\n if not merged:\n merged.append(higher)\n else:\n lower = merged[-1]\n # test for intersection between lower and higher:\n # we know via sorting that lower[0] <= higher[0]\n if higher[0] <= lower[1]:\n upper_bound = max(lower[1], higher[1])\n merged[-1] = (lower[0], upper_bound) # replace by merged interval\n else:\n merged.append(higher)\n return merged\n\nwith open(ccds_coords, 'r') as ccds_coords_file:\n ccds_df = pd.read_csv(ccds_coords_file, sep=\"\\t\", header=0)\n\nchroms = [str(i) for i in range(1, 23)]\nchroms += ['X', 'Y']\n\ntotal_len = 0\n\nfor chrom_sym in chroms:\n chrom = 'chr' + chrom_sym\n starts = ccds_df[ccds_df['chrom'] == chrom]['exonStarts']\n stops = ccds_df[ccds_df['chrom'] == chrom]['exonEnds']\n starts = ''.join(starts.tolist())\n stops = ''.join(stops.tolist())\n starts_nums = [int(num) for num in starts.split(',')[:-1]]\n stops_nums = [int(num) for num in stops.split(',')[:-1]]\n all_coords = union_intervals([(int(a),int(b)) for a, b in zip(starts_nums, stops_nums)])\n\n # get full chr sequence\n full_chr_seq_filename = chrom_seq_base.format(chrom_sym)\n handle = gzip.open(full_chr_seq_filename)\n seq = str(SeqIO.read(handle, \"fasta\").seq).upper()\n\n # add DNA between the coordinates to our output\n for coord_start, coord_stop in all_coords:\n to_output = seq[coord_start:coord_stop]\n total_len += 2 * len(to_output)\n exome_output_str += to_output\n exome_output_str += '=' * 20\n exome_output_str += revcompl(to_output)\n exome_output_str += '=' * 20\n\n# save the new exome\nwith open(output_path, 'w') as output:\n output.write(exome_output_str)\n" ]
[ [ "pandas.read_csv" ] ]
boxdot/xgboost
[ "1a0801238e06f64e0bcdd882081c36bb20e188b9" ]
[ "tests/python/test_predict.py" ]
[ "'''Tests for running inplace prediction.'''\nimport unittest\nfrom concurrent.futures import ThreadPoolExecutor\nimport numpy as np\nfrom scipy import sparse\n\nimport xgboost as xgb\n\n\ndef run_threaded_predict(X, rows, predict_func):\n results = []\n per_thread = 20\n with ThreadPoolExecutor(max_workers=10) as e:\n for i in range(0, rows, int(rows / per_thread)):\n if hasattr(X, 'iloc'):\n predictor = X.iloc[i:i+per_thread, :]\n else:\n predictor = X[i:i+per_thread, ...]\n f = e.submit(predict_func, predictor)\n results.append(f)\n\n for f in results:\n assert f.result()\n\n\nclass TestInplacePredict(unittest.TestCase):\n '''Tests for running inplace prediction'''\n def test_predict(self):\n rows = 1000\n cols = 10\n\n np.random.seed(1994)\n\n X = np.random.randn(rows, cols)\n y = np.random.randn(rows)\n dtrain = xgb.DMatrix(X, y)\n\n booster = xgb.train({'tree_method': 'hist'},\n dtrain, num_boost_round=10)\n\n test = xgb.DMatrix(X[:10, ...])\n predt_from_array = booster.inplace_predict(X[:10, ...])\n predt_from_dmatrix = booster.predict(test)\n\n np.testing.assert_allclose(predt_from_dmatrix, predt_from_array)\n\n def predict_dense(x):\n inplace_predt = booster.inplace_predict(x)\n d = xgb.DMatrix(x)\n copied_predt = booster.predict(d)\n return np.all(copied_predt == inplace_predt)\n\n for i in range(10):\n run_threaded_predict(X, rows, predict_dense)\n\n def predict_csr(x):\n inplace_predt = booster.inplace_predict(sparse.csr_matrix(x))\n d = xgb.DMatrix(x)\n copied_predt = booster.predict(d)\n return np.all(copied_predt == inplace_predt)\n\n for i in range(10):\n run_threaded_predict(X, rows, predict_csr)\n" ]
[ [ "numpy.random.seed", "scipy.sparse.csr_matrix", "numpy.all", "numpy.random.randn", "numpy.testing.assert_allclose" ] ]
tomeasure/gpt-2-Pytorch
[ "52ee85b212325b48c9db6913fe7df12226b939a9" ]
[ "GPT2/sample.py" ]
[ "'''\n code by TaeHwan Jung(@graykode)\n Original Paper and repository here : https://github.com/openai/gpt-2\n GPT2 Pytorch Model : https://github.com/huggingface/pytorch-pretrained-BERT\n'''\nimport torch\nimport torch.nn.functional as F\nfrom tqdm import trange\n\ndef top_k_logits(logits, k):\n if k == 0:\n return logits\n values, _ = torch.topk(logits, k)\n min_values = values[:, -1]\n return torch.where(logits < min_values, torch.ones_like(logits, dtype=logits.dtype) * -1e10, logits)\n\ndef sample_sequence(model, length, start_token=None, batch_size=None, context=None, temperature=1, top_k=0, device='cuda', sample=True):\n if start_token is None:\n assert context is not None, 'Specify exactly one of start_token and context!'\n context = torch.tensor(context, device=device, dtype=torch.long).unsqueeze(0).repeat(batch_size, 1)\n else:\n assert context is None, 'Specify exactly one of start_token and context!'\n context = torch.full((batch_size, 1), start_token, device=device, dtype=torch.long)\n prev = context # 2D, tensor, (batch_size, 1)\n output = context\n past = None\n with torch.no_grad():\n for i in trange(length):\n logits, past = model(prev, past=past)\n logits = logits[:, -1, :] / temperature\n logits = top_k_logits(logits, k=top_k)\n log_probs = F.softmax(logits, dim=-1)\n if sample:\n prev = torch.multinomial(log_probs, num_samples=1)\n else:\n _, prev = torch.topk(log_probs, k=1, dim=-1)\n output = torch.cat((output, prev), dim=1)\n return output\n" ]
[ [ "torch.nn.functional.softmax", "torch.full", "torch.cat", "torch.multinomial", "torch.tensor", "torch.no_grad", "torch.topk", "torch.ones_like" ] ]
jairocollante/sr
[ "f395c0f9aef804ec0100edcfe1a1c6ccab2494a1" ]
[ "webproject/taller1/algoritmosCII.py" ]
[ "import pandas as pd\nimport sqlalchemy\n\nclass SimilitudCosenoII():\n predictions = None\n def __init__(self):\n # Se cargan las predicciones\n engine = sqlalchemy.create_engine('postgresql://ugrupo06:grupo06@localhost:5432/t1')\n conn = engine.connect()\n\n sql_command = 'SELECT user_id, art_id, r_ui, est, details FROM public.taller1_pred_coseno_ii;'\n\n # Load the data\n predictions = pd.read_sql(sql_command, conn)\n print (predictions.shape)\n \n conn.close()\n\n def get_prediction_user(self, user_id):\n user_predictions = list(filter(lambda x: x[0]==user_id, predictions))\n #Ordenamos de mayor a menor estimación de relevancia\n user_predictions.sort(key=lambda x : x.est, reverse=True)\n #retorna las 10 primeras predicciones\n return user_predictions[0:10]" ]
[ [ "pandas.read_sql" ] ]
lqdev/DLWPython
[ "9d411b3e20c45e20b9f3641c58b7f5dcc2a2e439" ]
[ "Listings/5.py" ]
[ "\"\"\"\nListing 5.1 Instantiating a small convnet\n\"\"\"\n\nfrom keras import layers\nfrom keras import models\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1)))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(64,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(64,(3,3),activation='relu'))\n\nmodel.summary()\n\n\"\"\"\nListing 5.2 Adding a classifier on top of the convnet\n\"\"\"\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64,activation='relu'))\nmodel.add(layers.Dense(10,activation='softmax'))\n\nmodel.summary()\n\n\"\"\"\nListing 5.3 Training the convnet on MNIST images\n\"\"\"\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\n\n(train_images,train_labels),(test_images,test_labels) = mnist.load_data()\n\ntrain_images = train_images.reshape((60000,28,28,1))\ntrain_images = train_images.astype('float32') / 255\n\ntest_images = test_images.reshape((10000,28,28,1))\ntest_images = test_images.astype('float32') / 32\n\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)\n\nmodel.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])\n\nmodel.fit(train_images,train_labels,epochs=5,batch_size=64)\n\ntest_loss,test_acc = model.evaluate(test_images,test_labels)\n\ntest_acc\n\n\"\"\"\nListing 5.4 Copying images to training,validation, and test directories\n\"\"\"\n\nimport os, shutil\n\noriginal_dataset_dir = '/home/lqdev/Downloads/kaggle_original_data/train'\n\nbase_dir = '/home/lqdev/Downloads/cats_and_dogs_small'\n\n# Create Reduced Data Directory\nos.mkdir(base_dir)\n\n# Create Train/Validation/Test Directories\ntrain_dir = os.path.join(base_dir,'train')\nos.mkdir(train_dir)\nvalidation_dir = os.path.join(base_dir,'validation')\nos.mkdir(validation_dir)\ntest_dir = os.path.join(base_dir,'test')\nos.mkdir(test_dir)\n\n# Create Individual Tag Directories\ntrain_cats_dir = os.path.join(train_dir,'cats')\nos.mkdir(train_cats_dir)\n\ntrain_dogs_dir = os.path.join(train_dir,'dogs')\nos.mkdir(train_dogs_dir)\n\nvalidation_cats_dir = os.path.join(validation_dir,'cats')\nos.mkdir(validation_cats_dir)\n\nvalidation_dogs_dir = os.path.join(validation_dir,'dogs')\nos.mkdir(validation_dogs_dir)\n\ntest_cats_dir = os.path.join(test_dir,'cats')\nos.mkdir(test_cats_dir)\n\ntest_dogs_dir = os.path.join(test_dir,'dogs')\nos.mkdir(test_dogs_dir)\n\n# Copy Cat Files\nfnames = ['cat.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(train_cats_dir, fname)\n shutil.copyfile(src, dst)\n\nfnames = ['cat.{}.jpg'.format(i) for i in range(1000,1500)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(validation_cats_dir, fname)\n shutil.copyfile(src, dst)\n\nfnames = ['cat.{}.jpg'.format(i) for i in range(1500,2000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(test_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n# Copy Dog Files\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(train_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000,1500)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(validation_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\nfnames = ['dog.{}.jpg'.format(i) for i in range(1500,2000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n dst = os.path.join(test_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n\n# Check number of files in directories\nprint('total training cat images:', len(os.listdir(train_cats_dir)))\nprint('total training dog images:', len(os.listdir(train_dogs_dir)))\nprint('total validation cat images:', len(os.listdir(validation_cats_dir)))\nprint('total validation dog images:', len(os.listdir(validation_dogs_dir)))\nprint('total test cat images:', len(os.listdir(test_cats_dir)))\nprint('total test dog images:', len(os.listdir(test_dogs_dir)))\n\n\"\"\"\nListing 5.5 Instantiating a small convnet for dogs vs. cats classification\n\"\"\"\n\nfrom keras import layers\nfrom keras import models\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Conv2D(64,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.summary()\n\n\"\"\"\nListing 5.6 Configuring the model for training\n\"\"\"\n\nfrom keras import optimizers\n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=1e-4),metrics=['acc'])\n\n\"\"\"\nListing 5.7 Using ImageDataGenerator to read images from directories\n\"\"\"\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\n#Rescale Images by 1/255\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(150,150),\n batch_size=20,\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size=(150,150),\n batch_size=20,\n class_mode='binary')\n\n# See shape of generator\nfor data_batch,labels_batch in train_generator:\n print('data batch shape:', data_batch.shape)\n print('labels batch shape:', labels_batch.shape)\n break\n\n\"\"\"\nListing 5.8 Fiting the model using a batch generator\n\"\"\" \n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=30,\n validation_data=validation_generator,\n validation_steps=50)\n\n\"\"\"\nListing 5.9 Saving the model\n\"\"\"\n\nmodel.save('cats_and_dogs_small_1.h5')\n\n\"\"\"\nListing 5.10 Displaying curves of loss and accuracy during training\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\nplt.clf()\n\nplt.plot(epochs,acc,'bo',label='Training acc')\nplt.plot(epochs,val_acc,'b',label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs,loss,'bo',label='Training loss')\nplt.plot(epochs,val_loss,'b',label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n\"\"\"\nListing 5.11 Setting up a data augmentation configuration via ImageDataGenerator\n\"\"\"\n\ndatagen = ImageDataGenerator(\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\n\"\"\"\nListing 5.12 Displaying some randomly augmented training images\n\"\"\" \n\nfrom keras.preprocessing import image\n\nfnames = [os.path.join(train_cats_dir,fname) for fname in os.listdir(train_cats_dir)]\n\nimg_path = fnames[3]\n\nimg = image.load_img(img_path,target_size=(150,150))\n\nx = image.img_to_array(img)\n\nx = x.reshape((1,) + x.shape)\n\ni = 0\n\nfor batch in datagen.flow(x,batch_size=1):\n plt.figure(i)\n imgplot = plt.imshow(image.array_to_img(batch[0]))\n i += 1\n if i %4 == 0:\n break\n\nplt.show()\n\n\"\"\"\nListing 5.13 Defining a new convnet that includes dropout\n\"\"\"\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(64,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(512,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=1e-4),metrics=['acc'])\n\nmodel.summary()\n\n\"\"\"\nListing 5.14 Training the convnet using data-augmentation generators\n\"\"\"\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True\n)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(150,150),\n batch_size=32,\n class_mode='binary'\n)\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size=(150,150),\n batch_size=32,\n class_mode='binary'\n)\n\n# Should be this\n# history = model.fit_generator(\n# train_generator,\n# steps_per_epoch=100,\n# epochs=100,\n# validation_data=validation_generator,\n# validation_steps=50\n# )\n\n# Added to make it run quicker on CPU\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=5,\n validation_data=validation_generator,\n validation_steps=50\n)\n\n\"\"\"\nListing 5.15 Saving the model\n\"\"\"\n\nmodel.save('cats_and_dogs_small_2.h5')\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\nplt.clf()\n\nplt.plot(epochs,acc,'bo',label='Training acc')\nplt.plot(epochs,val_acc,'b',label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs,loss,'bo',label='Training loss')\nplt.plot(epochs,val_loss,'b',label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n\"\"\"\nListing 5.16 Instantiating the VGG16 convolutional base\n\"\"\"\n\nfrom keras.applications import VGG16\n\nconv_base = VGG16(weights='imagenet',include_top=False,input_shape=(150,150,3))\n\nconv_base.summary()\n\n\"\"\"\nListing 5.17 Extracting features using the pretrained convolutional base\n\"\"\"\n\nimport os\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\n\nbase_dir = '/home/lqdev/Downloads/cats_and_dogs_small'\ntrain_dir = os.path.join(base_dir,'train')\nvalidation_dir = os.path.join(base_dir,'validation')\ntest_dir = os.path.join(base_dir,'test')\n\ndatagen = ImageDataGenerator(rescale=1./255)\n\nbatch_size = 20\n\ndef extract_features(directory,sample_count):\n features = np.zeros(shape=(sample_count,4,4,512))\n labels = np.zeros(shape=(sample_count))\n generator = datagen.flow_from_directory(\n directory,\n target_size=(150,150),\n batch_size=batch_size,\n class_mode='binary'\n )\n i = 0\n for inputs_batch,labels_batch in generator:\n features_batch = conv_base.predict(inputs_batch)\n features[i * batch_size:(i + 1) * batch_size] = features_batch\n labels[i * batch_size:(i + 1) * batch_size] = labels_batch\n i += 1\n if i * batch_size >= sample_count:\n break\n return features,labels\n\ntrain_features,train_labels = extract_features(train_dir,2000)\nvalidation_features,validation_labels = extract_features(validation_dir,1000)\ntest_features,test_labels = extract_features(test_dir,1000)\n\ntrain_features = np.reshape(train_features,(2000, 4 * 4 * 512))\nvalidation_features = np.reshape(validation_features,(1000, 4 * 4 * 512))\ntest_features = np.reshape(test_features,(1000, 4 * 4 * 512))\n\n\"\"\"\nListing 5.18 Defining and training the densely connected classifier\n\"\"\"\n\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(256,activation='relu',input_dim=4*4*512))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.compile(optimizer=optimizers.RMSprop(lr=2e-5),loss='binary_crossentropy',metrics=['acc'])\n\nhistory = model.fit(train_features,train_labels,epochs=30,batch_size=20,validation_data=(validation_features,validation_labels))\n\n\"\"\"\nListing 5.19 Plotting the results\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\nplt.plot(epochs,acc,'bo',label='Training acc')\nplt.plot(epochs,val_acc,'b',label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs,loss,'bo',label='Training loss')\nplt.plot(epochs,val_loss,'b',label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n\"\"\"\nListing 5.20 Adding a densely connected classifier on top of the convolutional base\n\"\"\"\n\nfrom keras import models\nfrom keras import layers\n\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.summary()\n\n# Freeze weights (prevent weights of convolutional base from being updated on training. This must be done before compilation)\nprint('This is the number of trainable weights before freezing the conv base:', len(model.trainable_weights))\nconv_base.trainable = False\nprint('This is the number of trainable weights before freezing the conv base:', len(model.trainable_weights))\n\n\"\"\"\nListing 5.21 Training the model end to end with a frozen convolutional base\n\"\"\"\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest'\n)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(150,150),\n batch_size=20,\n class_mode='binary'\n)\n\nvalidation_generator = train_datagen.flow_from_directory(\n validation_dir,\n target_size=(150,150),\n batch_size=20,\n class_mode='binary'\n)\n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=2e-5),metrics=['acc'])\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=30,\n validation_data=validation_generator,\n validation_steps=50\n)\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\nplt.plot(epochs,acc,'bo',label='Training acc')\nplt.plot(epochs,val_acc,'b',label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs,loss,'bo',label='Training loss')\nplt.plot(epochs,val_loss,'b',label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n\"\"\"\nListing 5.22 Freezing all layers up to a specific one\n\"\"\"\n\n# This step takes place after training frozen conv base with newly added Dense layers\n\nconv_base.trainable = True\n\nset_trainable = False\nfor layer in conv_base.layers:\n if layer.name == 'block5_conv1':\n set_trainable = True\n if set_trainable:\n layer.trainable = True\n else:\n layer.trainable = False\n\n\"\"\"\nListing 5.23 Fine-tuning the model\n\"\"\" \n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=1e-5),metrics=['acc'])\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n epochs=100,\n validation_data=validation_generator,\n validation_steps=50\n)\n\n\"\"\"\nListing 5.24 Smoothing the plots\n\"\"\"\n\ndef smooth_curve(points, factor=0.8):\n smoothed_points = []\n for point in points:\n if smoothed_points:\n previous = smoothed_points[-1]\n smoothed_points.append(previous * factor + point * (1 - factor))\n else:\n smoothed_points.append(point)\n return smoothed_points\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\nplt.plot(epochs,smooth_curve(acc), 'bo', label='Smoothed training acc')\nplt.plot(epochs,smooth_curve(val_acc), 'b', label='Smoothed validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs,smooth_curve(loss), 'bo', label='Smoothed training loss')\nplt.plot(epochs,smooth_curve(val_loss), 'b', label='Smoothed validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n# Evaluate Model on Test Data\ntest_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size=(150, 150),\n batch_size=20,\n class_mode='binary')\n\ntest_loss,test_acc = model.evaluate_generator(test_generator,steps=50)\nprint('test acc:', test_acc)\n\n\"\"\"\nListing 5.25 Preprocessing an image\n\"\"\"\n\nimg_path = '/home/lqdev/Downloads/cats_and_dogs_small/test/cats/cat.1700.jpg'\n\nfrom keras.preprocessing.image import image\nimport numpy as np\n\nimg = image.load_img(img_path,target_size=(150,150))\nimg_tensor = image.img_to_array(img)\nimg_tensor = np.expand_dims(img_tensor,axis=0)\nimg_tensor /= 255.\n\nprint(img_tensor.shape)\n\n\"\"\"\nListing 5.26 Displaying the test picture\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nplt.imshow(img_tensor[0])\nplt.show()\n\n\"\"\"\nListing 5.27 Instantiating a model from an input tensor and a list of output tensors\n\"\"\"\n\nfrom keras.models import load_model\nmodel = load_model('cats_and_dogs_small_2.h5')\n\nfrom keras import models\n\nlayer_outputs = [layer.output for layer in model.layers[:8]]\n\nactivation_model = models.Model(inputs=model.input,outputs=layer_outputs)\n\n\"\"\"\nListing 5.28 Running the model in predict mode\n\"\"\"\n\nactivations = activation_model.predict(img_tensor)\n\nfirst_layer_activation = activations[0]\nprint(first_layer_activation.shape)\n\n\"\"\"\nListing 5.29 Visualizing the fourth channel\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nplt.matshow(first_layer_activation[0,:,:,4],cmap='viridis')\nplt.show()\n\n\"\"\"\nListing 5.30 Visualizing the seventh channel\n\"\"\"\n\nplt.matshow(first_layer_activation[0,:,:,7],cmap='viridis')\nplt.show()\n\n\"\"\"\nListing 5.31 Visualizing every channel in every intermediate activation\n\"\"\"\n\nlayer_names = []\n\n# Names of layers so you can have them as part of your plot\nfor layer in model.layers[:8]:\n layer_names.append(layer.name)\n\nimages_per_row = 16\n\nfor layer_name,layer_activation in zip(layer_names,activations): # Displays the feature maps\n n_features = layer_activation.shape[-1] #Number of features in the feature map\n\n size = layer_activation.shape[1] #The feature map has ashape (l,size,size,n_features)\n\n n_cols = n_features // images_per_row # Tiles the activation channels channels in this matrix\n\n display_grid = np.zeros((size * n_cols,images_per_row * size))\n\n for col in range(n_cols): # Tiles each filter into a big horizontal grid\n for row in range(images_per_row): # Post processes the feature to make it visually palatable\n channel_image = layer_activation[0,:,:,col * images_per_row + row]\n \n channel_image -= channel_image.mean()\n channel_image /= channel_image.std()\n channel_image *= 64\n channel_image += 128\n channel_image = np.clip(channel_image,0,255).astype('uint8')\n display_grid[col * size : (col + 1) * size,row * size : (row + 1) * size] = channel_image\n\n scale = 1. /size\n plt.figure(figsize=(scale * display_grid.shape[0],scale * display_grid.shape[1]))\n plt.title(layer_name)\n plt.grid(False)\n plt.imshow(display_grid,aspect='auto',cmap='viridis')\n\nplt.show()\n\n\"\"\"\nListing 5.32 Defining the loss tensor for filter visualization\n\"\"\"\n\nfrom keras.applications import VGG16\nfrom keras import backend as K\n\nmodel = VGG16(weights='imagenet',include_top=False)\n\nlayer_name = 'block3_conv1'\nfilter_index = 0\n\nlayer_output = model.get_layer(layer_name).output\nloss = K.mean(layer_output[:,:,:,filter_index])\n\n\"\"\"\nListing 5.33 Obtainig the gradient of the loss with regard to the input\n\"\"\"\n\n# The call to gradients returns a list of tensors (of size 1 in this case). \n# Hence keep only first elemtent which is a tensor\ngrads = K.gradients(loss,model.input)[0] \n\n\"\"\"\nListing 5.34 Gradient-normalization trick\n\"\"\"\n\ngrads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) # Smmoth SGD with L2 Regularization\n\n\"\"\"\nListing 5.35 Fetching Numpy output values given Numpy input values\n\"\"\"\n\niterate = K.function([model.input],[loss,grads])\n\nimport numpy as np\nloss_value,grads_value = iterate([np.zeros((1,150,150,3))])\n\n\"\"\"\nListing 5.36 Loss maximization via stochastic gradient descent\n\"\"\"\n\ninput_img_data = np.random.random((1,150,150,3)) * 20 + 128. # Starts from a gray image with some noise\n\nstep = 1. # Magnitude of each gradient update\nfor i in range(40): # Runs gradient ascent for 40 steps\n loss_value,grads_value = iterate([input_img_data]) # Compute loss value and gradient value\n\n input_img_data += grads_value * step # Adjusts the input image in the direction that maximizes the loss\n\n\"\"\"\nListing 5.37 Utility function to convert a tensor into a valid image\n\"\"\"\n\ndef deprocess_image(x):\n # Normalizes the tensor;Centers on 0;Ensures that std is 0.1\n x -= x.mean()\n x /= (x.std() + 1e-5)\n x *= 0.1\n\n x += 0.5\n x = np.clip(x,0,1)\n\n x *= 255\n x = np.clip(x,0,255).astype('uint8') #Convert to an RGB Array\n return x\n\n\"\"\"\nListing 5.38 Function to generate filter visualizations\n\"\"\"\n\ndef generate_pattern(layer_name,filter_index,size=150):\n # Builds a loss function tat maximizes the activaiton of the nth filter of the layer under consideration\n layer_output = model.get_layer(layer_name).output\n loss = K.mean(layer_output[:,:,:,filter_index])\n\n grads = K.gradients(loss,model.input)[0] # Computes the gradient of the input pucture with regard to this loss\n\n grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) # Normalization trick: normalizes the gradient\n\n iterate = K.function([model.input],[loss,grads]) # Return the loss and grads given the input picture\n\n input_img_data = np.random.random((1,size,size,3)) * 20 + 128. # Starts from a gray image with some noise\n\n step = 1.\n\n # Runs graduent ascent for 40 steps\n for i in range(40):\n loss_value,grads_value = iterate([input_img_data])\n input_img_data += grads_value * step\n \n img = input_img_data[0]\n return deprocess_image(img)\n\nplt.imshow(generate_pattern('block3_conv1',0))\nplt.show()\n\n\"\"\"\nListing 5.39 Generating a grid of all filter response patterns in a layer\n\"\"\"\n\nlayer_name = 'block3_conv1'\nsize = 64\nmargin = 5\n\nresults = np.zeros((8 * size + 7 * margin, 8 * size + 7 * margin, 3)) # Empty (black) image to store results\n\nfor i in range(8):\n for j in range(8):\n # Generates the pattern for filter i + (j * 8) in layer_name\n filter_img = generate_pattern(layer_name, i + (j * 8), size=size)\n\n # Puts the result in the square (i,j) of the results grid\n horizontal_start = i * size + i * margin\n horizontal_end = horizontal_start + size\n vertical_start = j * size + j * margin\n vertical_end = vertical_start + size\n results[horizontal_start: horizontal_end,vertical_start: vertical_end, :] = filter_img\n\nplt.figure(figsize=(20, 20))\nplt.imshow(results)\nplt.show()\n\n\"\"\"\nListing 5.40 Loading the VGG16 network with pretrained weights\n\"\"\"\n\nfrom keras.applications import VGG16\n\nmodel = VGG16(weights='imagenet')\n\n\"\"\"\nListing 5.41 Preprocessing an input image for VGG16\n\"\"\"\n\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input, decode_predictions\nimport numpy as np\n\nimg_path = \"/home/lqdev/Downloads/creative_commons_elephant.jpg\" # Local path to the target image\n\nimg = image.load_img(img_path,target_size=(224,224)) # Python Imaging Library (PIL) image of size 224 x 224\n\nx = image.img_to_array(img) # float32 Numpy array of shape (224,224,3)\n\nx = np.expand_dims(x, axis=0) # Adds a dimension to transform the array into a batch of size (1,224,224,3)\n\nx = preprocess_input(x) # Preprocess the batch (this does channel-wise color normalization)\n\npreds = model.predict(x)\n\nprint('Predicted:', decode_predictions(preds, top=3)[0])\n\nnp.argmax(preds[0])\n\n\"\"\"\nListing 5.42 Setting up the Grad-CAM algorithm\n\"\"\"\n\n# African elephant entryu in the prediction vector\nafrican_elephant_output = model.output[:,386]\n\n# Output feature map of the block5_conv3 layer, the last convolutional layer in VGG16\nlast_conv_layer = model.get_layer('block5_conv3') \n\n# Gradient of the \"African elephant\" class with regard to the output feature map of block5_conv3\ngrads = K.gradients(african_elephant_output,last_conv_layer.output)[0]\n\n# Vector of shape (512,) where each entry is the m,ean intensity of the gradient over a specific feature-map channel\npooled_grads = K.mean(grads,axis=(0,1,2))\n\n# Lets you access the values of the quantities you just defined\n# pooled_grads and the output feature map of block5_conv3, given a sample image\niterate = K.function([model.input],[pooled_grads,last_conv_layer.output[0]])\n\n# Values of these two quantities, as Numpy arrays, given the sample image of two elephants\npooled_grads_value,conv_layer_output_value = iterate([x])\n\n# Multiplies each channel in the feature-map array by \"how important this cahnnel is\" with the \"elephant\" class\nfor i in range(512):\n conv_layer_output_value[:,:,i] *= pooled_grads_value[i]\n\n# The channel-wise mean of the resulting feature map is the heatmap of the class activation\nheatmap = np.mean(conv_layer_output_value,axis=-1)\n\n\"\"\"\nListing 5.43 Heatmap post-processing\n\"\"\"\n\nheatmap = np.maximum(heatmap,0)\nheatmap /= np.max(heatmap)\nplt.matshow(heatmap)\nplt.show()\n\n\"\"\"\nListing 5.44 Superimposing the heatmap with the original picture\n\"\"\"\n\nimport cv2\nimg = cv2.imread(img_path)\nheatmap = cv2.resize(heatmap,(img.shape[1],img.shape[0]))\nheatmap = np.uint8(255 * heatmap)\nheatmap = cv2.applyColorMap(heatmap,cv2.COLORMAP_JET)\nsuperimposed_img = heatmap * 0.4 + img\ncv2.imwrite('/home/lqdev/Downloads/elephant_cam.jpg',superimposed_img)" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "numpy.expand_dims", "matplotlib.pyplot.plot", "numpy.max", "numpy.mean", "matplotlib.pyplot.matshow", "numpy.clip", "numpy.reshape", "numpy.uint8", "numpy.argmax", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "numpy.maximum", "numpy.random.random", "matplotlib.pyplot.clf", "matplotlib.pyplot.grid" ] ]
bouchraamirouche/bouchra
[ "ac1257bef933ac0a8872ca310623ae017b62124f" ]
[ "scripts/select_folds.py" ]
[ "\"\"\"Split the training set into K folds.\n\nThis script requires three command-line arguments:\n\n * metadata_path: Path to training set metadata.\n * output_path: Output file path.\n * n_folds: Number of folds to use.\n\nThe output is a new metadata file that assigns each example to a fold.\n\"\"\"\n\nimport argparse\n\nimport pandas as pd\n\nfrom sklearn.model_selection import StratifiedKFold\n\n\n# Parse command line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('metadata_path', help='path to training set metadata')\nparser.add_argument('output_path', help='output metadata file path')\nparser.add_argument('--n_folds', type=int, default=5,\n help='number of folds to use')\nargs = parser.parse_args()\n\n# Create dummy labels to ensure each fold has a similar number of\n# manually verified examples.\ndf = pd.read_csv(args.metadata_path, index_col=0)\nlabels = df.label + df.manually_verified.astype(str)\n\n# Assign a fold number to each example\ndf['fold'] = -1\nskf = StratifiedKFold(args.n_folds)\nfor i, (_, te) in enumerate(skf.split(df.index, labels)):\n df.iloc[te, 2] = i\n\nprint('Number of verified examples per fold:')\nprint([sum((df.fold == i) & (df.manually_verified == 1))\n for i in range(args.n_folds)])\n\n# Save new metadata file to disk\ndf.to_csv(args.output_path)\n" ]
[ [ "pandas.read_csv", "sklearn.model_selection.StratifiedKFold" ] ]
MingtaoGuo/Pytorch_Learning_Diary
[ "6910fe8ce0f780b456dd2a8b3ec6de9b46b11c9d" ]
[ "Day 6/GANs.py" ]
[ "import torch\r\nimport torch.nn as nn\r\nimport torch.autograd as autograd\r\nimport numpy as np\r\nimport scipy.io as sio\r\nfrom PIL import Image\r\n\r\nbatchsize = 128\r\n\r\n\r\nclass Generator(nn.Module):\r\n def __init__(self):\r\n super(Generator, self).__init__()\r\n self.linear = nn.Sequential(\r\n nn.Linear(128, 4 * 4 * 1024),\r\n nn.ReLU(inplace=True)\r\n )\r\n self.deconv1 = nn.Sequential(\r\n nn.ConvTranspose2d(1024, 512, 4, 2, 1),\r\n nn.BatchNorm2d(512),\r\n nn.ReLU(inplace=True)\r\n )\r\n self.deconv2 = nn.Sequential(\r\n nn.ConvTranspose2d(512, 256, 4, 2, 1),\r\n nn.BatchNorm2d(256),\r\n nn.ReLU(inplace=True)\r\n )\r\n self.deconv3 = nn.Sequential(\r\n nn.ConvTranspose2d(256, 128, 4, 2, 1),\r\n nn.BatchNorm2d(128),\r\n nn.ReLU(inplace=True)\r\n )\r\n self.deconv4 = nn.Sequential(\r\n nn.ConvTranspose2d(128, 3, 4, 2, 1),\r\n nn.Tanh()\r\n )\r\n\r\n def forward(self, x):\r\n x = self.linear(x)\r\n x = x.view(-1, 1024, 4, 4)\r\n x = self.deconv1(x)\r\n x = self.deconv2(x)\r\n x = self.deconv3(x)\r\n x = self.deconv4(x)\r\n return x\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self):\r\n super(Discriminator, self).__init__()\r\n self.conv1 = nn.Sequential(\r\n nn.Conv2d(3, 64, 4, 2, 1),\r\n nn.LeakyReLU(inplace=True)\r\n )\r\n self.conv2 = nn.Sequential(\r\n nn.Conv2d(64, 128, 4, 2, 1),\r\n nn.BatchNorm2d(128),\r\n nn.LeakyReLU(inplace=True)\r\n )\r\n self.conv3 = nn.Sequential(\r\n nn.Conv2d(128, 256, 4, 2, 1),\r\n nn.BatchNorm2d(256),\r\n nn.LeakyReLU(inplace=True)\r\n )\r\n self.conv4 = nn.Sequential(\r\n nn.Conv2d(256, 512, 4, 2, 1),\r\n nn.BatchNorm2d(512),\r\n nn.LeakyReLU(inplace=True)\r\n )\r\n self.linear = nn.Linear(4 * 4 * 512, 1)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = self.conv2(x)\r\n x = self.conv3(x)\r\n x = self.conv4(x)\r\n x = x.view(-1, 4 * 4 * 512)\r\n x = self.linear(x)\r\n return x\r\n\r\n\r\ndef DCGAN():\r\n generator = Generator()\r\n discriminator = Discriminator()\r\n generator.to(\"cuda:0\")\r\n discriminator.to(\"cuda:0\")\r\n opt_g = torch.optim.Adam(generator.parameters(), lr=2e-4)\r\n opt_d = torch.optim.Adam(discriminator.parameters(), lr=2e-4)\r\n data = sio.loadmat(\"./facedata.mat\")[\"data\"]\r\n data = np.transpose(data, axes=[0, 3, 1, 2])\r\n nums = data.shape[0]\r\n for i in range(100000):\r\n z = torch.randn(batchsize, 128).to(\"cuda:0\")\r\n fake_img = generator(z)\r\n fake_logits = discriminator(fake_img)\r\n g_loss = -torch.mean(torch.log(torch.sigmoid(fake_logits) + 1e-10))\r\n for j in range(1):\r\n rand_idx = np.random.randint(0, nums, [batchsize])\r\n batch = data[rand_idx] / 127.5 - 1.0\r\n batch = torch.tensor(batch, dtype=torch.float32).to(\"cuda:0\")\r\n real_logits = discriminator(batch)\r\n d_loss = -torch.mean(torch.log(torch.sigmoid(real_logits)+1e-10) + torch.log(1 - torch.sigmoid(fake_logits)+1e-10))\r\n opt_d.zero_grad()\r\n d_loss.backward(retain_graph=True)\r\n opt_d.step()\r\n opt_g.zero_grad()\r\n g_loss.backward(retain_graph=True)\r\n opt_g.step()\r\n if i % 100 == 0:\r\n img = np.uint8(np.transpose((fake_img.cpu().detach().numpy()[0]+1)*127.5, axes=[1, 2, 0]))\r\n Image.fromarray(img).save(\"./results/\"+str(i)+\".jpg\")\r\n print(\"Iteration: %d, D_loss: %f, G_loss: %f\"%(i, d_loss, g_loss))\r\n\r\ndef WGAN():\r\n generator = Generator()\r\n discriminator = Discriminator()\r\n generator.to(\"cuda:0\")\r\n discriminator.to(\"cuda:0\")\r\n opt_g = torch.optim.RMSprop(generator.parameters(), lr=5e-5)\r\n opt_d = torch.optim.RMSprop(discriminator.parameters(), lr=5e-5)\r\n data = sio.loadmat(\"./facedata.mat\")[\"data\"]\r\n data = np.transpose(data, axes=[0, 3, 1, 2])\r\n nums = data.shape[0]\r\n for i in range(100000):\r\n z = torch.randn(batchsize, 128).to(\"cuda:0\")\r\n fake_img = generator(z)\r\n fake_logits = discriminator(fake_img)\r\n g_loss = -torch.mean(fake_logits)\r\n for j in range(1):\r\n rand_idx = np.random.randint(0, nums, [batchsize])\r\n batch = data[rand_idx] / 127.5 - 1.0\r\n batch = torch.tensor(batch, dtype=torch.float32).to(\"cuda:0\")\r\n real_logits = discriminator(batch)\r\n d_loss = -torch.mean(real_logits) + torch.mean(fake_logits)\r\n for para in discriminator.parameters():\r\n para.data.clamp_(-0.01, 0.01)\r\n opt_d.zero_grad()\r\n d_loss.backward(retain_graph=True)\r\n opt_d.step()\r\n opt_g.zero_grad()\r\n g_loss.backward(retain_graph=True)\r\n opt_g.step()\r\n if i % 100 == 0:\r\n img = np.uint8(np.transpose((fake_img.cpu().detach().numpy()[0]+1)*127.5, axes=[1, 2, 0]))\r\n Image.fromarray(img).save(\"./results/\"+str(i)+\".jpg\")\r\n print(\"Iteration: %d, D_loss: %f, G_loss: %f\"%(i, d_loss, g_loss))\r\n\r\ndef WGANGP():\r\n def gradient_penalty(x_real, x_fake, D, lambda_=10):\r\n eps = torch.rand(1, 1, 1, 1).to(\"cuda:0\")\r\n x_hat = eps * x_real + (1. - eps) * x_fake\r\n outputs = D(x_hat)\r\n grads = autograd.grad(outputs, x_hat, torch.ones_like(outputs), retain_graph=True, create_graph=True)[0]\r\n grads = grads.view(grads.size()[0], -1)\r\n penalty = lambda_ * (torch.norm(grads, p=2, dim=1).mean() - 1) ** 2\r\n return penalty\r\n\r\n generator = Generator()\r\n discriminator = Discriminator()\r\n generator.to(\"cuda:0\")\r\n discriminator.to(\"cuda:0\")\r\n opt_g = torch.optim.Adam(generator.parameters(), lr=1e-4, betas=(0, 0.9))\r\n opt_d = torch.optim.Adam(discriminator.parameters(), lr=1e-4, betas=(0, 0.9))\r\n data = sio.loadmat(\"./facedata.mat\")[\"data\"]\r\n data = np.transpose(data, axes=[0, 3, 1, 2])\r\n nums = data.shape[0]\r\n for i in range(100000):\r\n for j in range(1):\r\n rand_idx = np.random.randint(0, nums, [batchsize])\r\n batch = data[rand_idx] / 127.5 - 1.0\r\n batch = torch.tensor(batch, dtype=torch.float32).to(\"cuda:0\")\r\n z = torch.randn(batchsize, 128).to(\"cuda:0\")\r\n fake_img = generator(z)\r\n fake_logits = discriminator(fake_img)\r\n real_logits = discriminator(batch)\r\n penalty = gradient_penalty(batch, fake_img, discriminator, lambda_=10)\r\n d_loss = -torch.mean(real_logits) + torch.mean(fake_logits) + penalty\r\n opt_d.zero_grad()\r\n d_loss.backward(retain_graph=True)\r\n opt_d.step()\r\n z = torch.randn(batchsize, 128).to(\"cuda:0\")\r\n fake_img = generator(z)\r\n fake_logits = discriminator(fake_img)\r\n g_loss = -torch.mean(fake_logits)\r\n opt_g.zero_grad()\r\n g_loss.backward(retain_graph=True)\r\n opt_g.step()\r\n if i % 100 == 0:\r\n img = np.uint8(np.transpose((fake_img.cpu().detach().numpy()[0]+1)*127.5, axes=[1, 2, 0]))\r\n Image.fromarray(img).save(\"./results/\"+str(i)+\".jpg\")\r\n print(\"Iteration: %d, D_loss: %f, G_loss: %f\"%(i, d_loss, g_loss))\r\n\r\nif __name__ == \"__main__\":\r\n WGANGP()\r\n" ]
[ [ "torch.mean", "torch.sigmoid", "torch.norm", "torch.nn.ConvTranspose2d", "torch.randn", "torch.nn.Conv2d", "scipy.io.loadmat", "torch.nn.Tanh", "torch.tensor", "torch.nn.Linear", "torch.nn.LeakyReLU", "torch.nn.BatchNorm2d", "numpy.transpose", "torch.rand", "torch.nn.ReLU", "torch.ones_like", "numpy.random.randint" ] ]
dah33/visions
[ "381b9c1aa700bf0b352a014a50af4d8159c2d0e7" ]
[ "src/visions/application/summaries/series/email_address_summary.py" ]
[ "import pandas as pd\n\n\ndef email_address_summary(series: pd.Series) -> dict:\n summary = {}\n\n local = []\n fqdn = []\n for v in series.drop().values:\n local.append(v.local)\n fqdn.append(v.fqdn)\n\n summary[\"local_counts\"] = pd.Series(local).value_counts().to_dict()\n summary[\"fqdn_counts\"] = pd.Series(fqdn).value_counts().to_dict()\n\n return summary\n" ]
[ [ "pandas.Series" ] ]
IIMarch/ssd
[ "79361ed185f0bbd750e3af8fb281bb6deb27be73" ]
[ "train.py" ]
[ "from data import *\nfrom utils.augmentations import SSDAugmentation\nfrom layers.modules import MultiBoxLoss\nfrom ssd import build_ssd\nimport os\nimport sys\nimport time\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport torch.utils.data as data\nimport numpy as np\nimport argparse\n\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\nparser = argparse.ArgumentParser(\n description='Single Shot MultiBox Detector Training With Pytorch')\ntrain_set = parser.add_mutually_exclusive_group()\nparser.add_argument('--dataset', default='VOC', choices=['VOC', 'COCO'],\n type=str, help='VOC or COCO')\nparser.add_argument('--dataset_root', default=VOC_ROOT,\n help='Dataset root directory path')\nparser.add_argument('--basenet', default='vgg16_reducedfc.pth',\n help='Pretrained base model')\nparser.add_argument('--batch_size', default=32, type=int,\n help='Batch size for training')\nparser.add_argument('--resume', default=None, type=str,\n help='Checkpoint state_dict file to resume training from')\nparser.add_argument('--start_iter', default=0, type=int,\n help='Resume training at this iter')\nparser.add_argument('--num_workers', default=4, type=int,\n help='Number of workers used in dataloading')\nparser.add_argument('--cuda', default=True, type=str2bool,\n help='Use CUDA to train model')\nparser.add_argument('--lr', '--learning-rate', default=0.001, type=float,\n help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float,\n help='Momentum value for optim')\nparser.add_argument('--weight_decay', default=5e-4, type=float,\n help='Weight decay for SGD')\nparser.add_argument('--gamma', default=0.1, type=float,\n help='Gamma update for SGD')\nparser.add_argument('--visdom', default=False, type=str2bool,\n help='Use visdom for loss visualization')\nparser.add_argument('--save_folder', default='weights/',\n help='Directory for saving checkpoint models')\nargs = parser.parse_args()\n\n\nif torch.cuda.is_available():\n if args.cuda:\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n if not args.cuda:\n print(\"WARNING: It looks like you have a CUDA device, but aren't \" +\n \"using CUDA.\\nRun with --cuda for optimal training speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\n\ndef train():\n if args.dataset == 'COCO':\n if args.dataset_root == VOC_ROOT:\n if not os.path.exists(COCO_ROOT):\n parser.error('Must specify dataset_root if specifying dataset')\n print(\"WARNING: Using default COCO dataset_root because \" +\n \"--dataset_root was not specified.\")\n args.dataset_root = COCO_ROOT\n cfg = coco\n dataset = COCODetection(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))\n elif args.dataset == 'VOC':\n #if args.dataset_root == COCO_ROOT:\n # parser.error('Must specify dataset if specifying dataset_root')\n cfg = voc\n dataset = VOCDetection(root=args.dataset_root,\n transform=SSDAugmentation(cfg['min_dim'],\n MEANS))\n\n if args.visdom:\n import visdom\n viz = visdom.Visdom()\n\n ssd_net = build_ssd('train', cfg['min_dim'], cfg['num_classes'])\n net = ssd_net\n\n if args.cuda:\n net = torch.nn.DataParallel(ssd_net)\n cudnn.benchmark = True\n\n if args.resume:\n print('Resuming training, loading {}...'.format(args.resume))\n ssd_net.load_weights(args.resume)\n else:\n vgg_weights = torch.load(args.save_folder + args.basenet)\n print('Loading base network...')\n ssd_net.vgg.load_state_dict(vgg_weights)\n\n if args.cuda:\n net = net.cuda()\n\n if not args.resume:\n print('Initializing weights...')\n # initialize newly added layers' weights with xavier method\n ssd_net.extras.apply(weights_init)\n ssd_net.loc.apply(weights_init)\n ssd_net.conf.apply(weights_init)\n\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=args.momentum,\n weight_decay=args.weight_decay)\n criterion = MultiBoxLoss(cfg['num_classes'], 0.5, True, 0, True, 3, 0.5,\n False, args.cuda)\n\n net.train()\n # loss counters\n loc_loss = 0\n conf_loss = 0\n epoch = 0\n print('Loading the dataset...')\n\n epoch_size = len(dataset) // args.batch_size\n print('Training SSD on:', dataset.name)\n print('Using the specified args:')\n print(args)\n\n step_index = 0\n\n if args.visdom:\n vis_title = 'SSD.PyTorch on ' + dataset.name\n vis_legend = ['Loc Loss', 'Conf Loss', 'Total Loss']\n iter_plot = create_vis_plot('Iteration', 'Loss', vis_title, vis_legend)\n epoch_plot = create_vis_plot('Epoch', 'Loss', vis_title, vis_legend)\n\n data_loader = data.DataLoader(dataset, args.batch_size,\n num_workers=args.num_workers,\n shuffle=True, collate_fn=detection_collate,\n pin_memory=True)\n # create batch iterator\n iteration = args.start_iter\n for epoch in range(100000):\n for i_batch, (images, targets) in enumerate(data_loader):\n if args.visdom and iteration != 0 and (iteration % epoch_size == 0):\n update_vis_plot(epoch, loc_loss, conf_loss, epoch_plot, None,\n 'append', epoch_size)\n # reset epoch loss counters\n loc_loss = 0\n conf_loss = 0\n epoch += 1\n\n if iteration in cfg['lr_steps']:\n step_index += 1\n adjust_learning_rate(optimizer, args.gamma, step_index)\n\n if args.cuda:\n images = Variable(images.cuda())\n targets = [Variable(ann.cuda(), volatile=True) for ann in targets]\n else:\n images = Variable(images)\n targets = [Variable(ann, volatile=True) for ann in targets]\n # forward\n t0 = time.time()\n out = net(images)\n # backprop\n optimizer.zero_grad()\n loss_l, loss_c = criterion(out, targets)\n loss = loss_l + loss_c\n loss.backward()\n optimizer.step()\n t1 = time.time()\n loc_loss += loss_l.data.item()\n conf_loss += loss_c.data.item()\n\n\n if iteration % 10 == 0:\n print('timer: %.4f sec.' % (t1 - t0))\n print('epoch ' + repr(epoch) + ' iter ' + repr(iteration) + ', loss: %.4f' % (loss.data.item()))\n for param_group in optimizer.param_groups:\n print ('lr: {}'.format(param_group['lr']))\n\n if args.visdom:\n update_vis_plot(iteration, loss_l.data.item(), loss_c.data.item(),\n iter_plot, epoch_plot, 'append')\n iteration += 1\n\n\n torch.save(ssd_net.state_dict(),\n args.save_folder + 'SSD300_{}_'.format(epoch) + args.dataset + '.pth')\n\n\ndef adjust_learning_rate(optimizer, gamma, step):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 at every\n specified step\n # Adapted from PyTorch Imagenet example:\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n lr = args.lr * (gamma ** (step))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef xavier(param):\n init.xavier_uniform(param)\n\n\ndef weights_init(m):\n if isinstance(m, nn.Conv2d):\n xavier(m.weight.data)\n m.bias.data.zero_()\n\n\ndef create_vis_plot(_xlabel, _ylabel, _title, _legend):\n return viz.line(\n X=torch.zeros((1,)).cpu(),\n Y=torch.zeros((1, 3)).cpu(),\n opts=dict(\n xlabel=_xlabel,\n ylabel=_ylabel,\n title=_title,\n legend=_legend\n )\n )\n\n\ndef update_vis_plot(iteration, loc, conf, window1, window2, update_type,\n epoch_size=1):\n viz.line(\n X=torch.ones((1, 3)).cpu() * iteration,\n Y=torch.Tensor([loc, conf, loc + conf]).unsqueeze(0).cpu() / epoch_size,\n win=window1,\n update=update_type\n )\n # initialize epoch plot on first iteration\n if iteration == 0:\n viz.line(\n X=torch.zeros((1, 3)).cpu(),\n Y=torch.Tensor([loc, conf, loc + conf]).unsqueeze(0).cpu(),\n win=window2,\n update=True\n )\n\n\nif __name__ == '__main__':\n train()\n" ]
[ [ "torch.set_default_tensor_type", "torch.ones", "torch.Tensor", "torch.load", "torch.zeros", "torch.utils.data.DataLoader", "torch.cuda.is_available", "torch.nn.DataParallel", "torch.nn.init.xavier_uniform", "torch.autograd.Variable" ] ]
chrisspen/speaker-recognition-1
[ "d55b600bbebef2199cab2180eaa6033e078af4cc" ]
[ "speaker_recognition/test/test-nperson.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# $File: test-nperson.py\n# $Date: Fri Dec 27 03:08:25 2013 +0000\n# $Author: Xinyu Zhou <zxytim[at]gmail[dot]com>\n\nimport glob\nimport traceback\nimport sys\nimport random\nimport os\nimport time\nimport numpy as np\nimport multiprocessing\nimport operator\nfrom collections import defaultdict\n\nfrom .gmm.python.pygmm import GMM\nfrom ..feature import BOB, LPC, MFCC, get_extractor\nfrom .multiprocess import MultiProcessWorker\nfrom .sample import Sample\n\nconcurrency = multiprocessing.cpu_count()\n\n\nclass Person:\n\n def __init__(self, sample=None, name=None, gender=None):\n self.sample = sample\n self.name = name\n self.gender = gender\n self.samples = []\n\n def add_sample(self, sample):\n self.samples.append(sample)\n if not self.sample:\n self.sample = sample\n else:\n self.sample.add(sample)\n\n def sample_duration(self):\n return self.sample.duration()\n\n def get_fragment(self, duration):\n return self.sample.get_fragment(duration)\n\n def get_fragment_with_interval(self, duration):\n return self.sample.get_fragment_with_interval(duration)\n\n def remove_subsignal(self, begin, end):\n self.sample.remove_subsignal(begin, end)\n\n\ndef get_corpus(dirs):\n persons = defaultdict(Person)\n\n for d in dirs:\n print(\"processing {} ...\".format(d))\n for fname in sorted(glob.glob(os.path.join(d, \"*.wav\"))):\n basename = os.path.basename(fname)\n gender, name, _ = basename.split('_')\n p = persons[name]\n p.name, p.gender = name, gender\n try:\n orig_sample = Sample.from_wavfile(fname)\n p.add_sample(orig_sample)\n except Exception as e:\n print(\"Exception occured while reading {}: {} \".format(fname, e))\n print(\"======= traceback =======\")\n print(traceback.format_exc())\n print(\"=========================\")\n\n return persons\n\n\nclass GMMSet:\n\n def __init__(self, gmm_order=32):\n self.gmms = []\n self.gmm_order = gmm_order\n self.y = []\n\n def fit_new(self, x, label):\n self.y.append(label)\n gmm = GMM(self.gmm_order)\n gmm.fit(x)\n self.gmms.append(gmm)\n\n def cluster_by_label(self, X, y):\n Xtmp = defaultdict(list)\n for ind, x in enumerate(X):\n label = y[ind]\n Xtmp[label].extend(x)\n yp, Xp = zip(*Xtmp.items())\n return Xp, yp\n\n def fit(self, X, y):\n X, y = self.cluster_by_label(X, y)\n for ind, x in enumerate(X):\n self.fit_new(x, y[ind])\n\n def gmm_score(self, gmm, x):\n return np.exp(np.sum(gmm.score(x)) / 1000)\n\n def predict_one(self, x):\n scores = [self.gmm_score(gmm, x) for gmm in self.gmms]\n return self.y[max(enumerate(scores), key=operator.itemgetter(1))[0]]\n\n def predict(self, X):\n return map(self.predict_one, X)\n\n\ndef gen_data(params):\n p, duration = params\n return p.get_fragment(duration)\n\n\ndef predict_task(gmmset, x_test):\n return gmmset.predict_one(x_test)\n\n\ndef test_feature(feature_impl, X_train, y_train, X_test, y_test):\n start = time.time()\n print('calculating features...')\n worker = MultiProcessWorker(feature_impl)\n X_train = worker.run(X_train)\n del worker\n worker = MultiProcessWorker(feature_impl)\n X_test = worker.run(X_test)\n del worker\n print('time elapsed: ', time.time() - start)\n\n start = time.time()\n gmmset = GMMSet()\n print('training ...')\n gmmset.fit(X_train, y_train)\n nr_correct = 0\n print('time elapsed: ', time.time() - start)\n\n print('predicting...')\n start = time.time()\n pool = multiprocessing.Pool(concurrency)\n predictions = []\n for x_test, label_true in zip(*(X_test, y_test)):\n predictions.append(pool.apply_async(predict_task, args=(gmmset, x_test)))\n pool.close()\n for ind, (x_test, label_true) in enumerate(zip(*(X_test, y_test))):\n label_pred = predictions[ind].get()\n if label_pred == label_true:\n nr_correct += 1\n print('time elapsed: ', time.time() - start)\n print(\"{}/{} {:.6f}\".format(nr_correct, len(y_test), float(nr_correct) / len(y_test)))\n\n\ndef main():\n if len(sys.argv) == 1:\n print(\"Usage: {} <dir_contains_wav_file> [<dirs> ...]\".format(sys.argv[0]))\n sys.exit(1)\n\n dirs = sys.argv[1:]\n\n fout = open(\"final-log/nperson-newg-mix-t5.log\", 'a')\n sys.stdout = fout\n\n for nr_person in [4, 6, 8, 10, 12, 14, 16, 18, 20, 25, 30, 40, 50, 60, 80]:\n print(\"Nperson: \", nr_person)\n train_duration = 20\n test_duration = 5\n nr_test_fragment_per_person = 50\n\n persons = list(get_corpus(dirs).items())\n random.shuffle(persons)\n persons = persons[:nr_person]\n\n X_train, y_train = [], []\n X_test, y_test = [], []\n for name, p in persons:\n y_train.append(name)\n fs, signal, begin, end = p.get_fragment_with_interval(train_duration)\n # it is important to remove signal used for training to get\n # unbiased result\n p.remove_subsignal(begin, end)\n X_train.append((fs, signal))\n for name, p in persons:\n for i in range(nr_test_fragment_per_person):\n y_test.append(name)\n X_test.append(gen_data((p, test_duration)))\n\n def mix(tup):\n bob = BOB.extract(tup)\n lpc = LPC.extract(tup)\n return np.concatenate((bob, lpc), axis=1)\n\n test_feature(mix, X_train, y_train, X_test, y_test)\n fout.close()\n\n\nif __name__ == '__main__':\n main()\n\n# vim: foldmethod=marker\n" ]
[ [ "numpy.concatenate" ] ]
paulirish/covid-data-model
[ "b93ae5d598b8378f9c1f2698e3162f87136cde74" ]
[ "pyseir/inference/model_fitter.py" ]
[ "import logging\nimport iminuit\nimport numpy as np\nimport us\nimport pickle\nfrom pprint import pformat\nimport pandas as pd\nfrom scipy.stats import gamma, norm\nfrom copy import deepcopy\nfrom matplotlib import pyplot as plt\nfrom datetime import datetime, timedelta\nfrom multiprocessing import Pool\nfrom pyseir.models import suppression_policies\nfrom pyseir import load_data\nfrom pyseir.models.seir_model import SEIRModel\nfrom libs.datasets.dataset_utils import AggregationLevel\nfrom pyseir.parameters.parameter_ensemble_generator import ParameterEnsembleGenerator\nfrom pyseir.load_data import HospitalizationDataType\nfrom pyseir.utils import get_run_artifact_path, RunArtifact\n\n\nclass ModelFitter:\n \"\"\"\n Fit a SEIR model and suppression policy for a geographic unit (county or\n state) against case, hospitalization, and mortality data. The error model\n to blend these is dominated by systematic uncertainties rather than\n statistical ones. We allow for relative rates of confirmed cases, hosp and\n deaths to float, allowing the fitter to focus on the shape parameters rather\n than absolutes.\n\n Parameters\n ----------\n fips: str\n State or county fips code.\n ref_date: datetime\n Date to reference against. This should be before the first case.\n min_deaths: int\n Minimum number of fatalities to use death data.\n n_years: int\n Number of years to run the simulation for.\n cases_to_deaths_err_factor: float\n To control chi2 mix between cases and deaths, we multiply the systematic\n errors of cases by this number. Thus higher numbers reduce the influence\n of case data on the fit.\n hospital_to_deaths_err_factor: float\n To control chi2 mix between hospitalization and deaths, we multiply the\n systematic errors of cases by this number. Thus higher numbers reduce\n the influence of hospitalization data on the fit.\n percent_error_on_max_observation: float\n Relative error on the max observation in each category. The reltive\n errors are then scaled based on the sqrt(observed value / observed max)\n relative to the max. The overall scale here doesn't influence the max\n likelihood fit, but it does influence the prior blending and error\n estimates. 0.5 = 50% error. Best to be conservatively high.\n \"\"\"\n\n DEFAULT_FIT_PARAMS = dict(\n R0=3.4, limit_R0=[2, 4.5], error_R0=.05,\n log10_I_initial=2, limit_log10_I_initial=[0, 5],\n error_log10_I_initial=.2,\n t0=60, limit_t0=[10, 80], error_t0=1.0,\n eps=.4, limit_eps=[.23, 2], error_eps=.005,\n t_break=20, limit_t_break=[5, 40], error_t_break=1,\n test_fraction=.1, limit_test_fraction=[0.02, 1], error_test_fraction=.02,\n hosp_fraction=.7, limit_hosp_fraction=[0.25, 1], error_hosp_fraction=.05,\n # Let's not fit this to start...\n errordef=.5\n )\n\n PARAM_SETS = {\n ('KY', 'KS', 'ID', 'NE', 'VA', 'RI'): dict(\n eps=0.4, limit_eps=[0.25, 1],\n limit_t0=[40, 80]\n ),\n\n ('AK'): dict(\n eps=0.4, limit_eps=[0.25, 1],\n t0=75, limit_t0=[40, 80],\n t_break=10\n ),\n ('ND'): dict(\n eps=0.4, limit_eps=[0.25, 1],\n t0=60, limit_t0=[40, 80],\n t_break=10\n ),\n ('MN'): dict(\n eps=0.4, limit_eps=[0.25, 1], t0=20\n ),\n ('AL', 'DE'): dict(limit_t_break=[7, 10], t0=70),\n ('SD', 'NM', 'WV'): dict(\n # To Be relaxed after more data.\n eps=0.4, t_break=5, fix_t_break=True\n ),\n ('MI'): dict(limit_t_break=[7, 40], t0=70),\n ('VT', 'NH'): dict(limit_t_break=[10, 30], t0=45)\n }\n\n steady_state_exposed_to_infected_ratio = 1.2\n\n def __init__(self,\n fips,\n ref_date=datetime(year=2020, month=1, day=1),\n min_deaths=2,\n n_years=1,\n cases_to_deaths_err_factor=.5,\n hospital_to_deaths_err_factor=.5,\n percent_error_on_max_observation=0.5):\n\n # Seed the random state. It is unclear whether this propagates to the\n # Minuit optimizer.\n np.random.seed(seed=42)\n\n self.fips = fips\n self.ref_date = ref_date\n self.min_deaths = min_deaths\n self.t_list = np.linspace(0, int(365 * n_years), int(365 * n_years) + 1)\n self.cases_to_deaths_err_factor = cases_to_deaths_err_factor\n self.hospital_to_deaths_err_factor = hospital_to_deaths_err_factor\n self.percent_error_on_max_observation = percent_error_on_max_observation\n self.t0_guess = 60\n\n if len(fips) == 2: # State FIPS are 2 digits\n self.agg_level = AggregationLevel.STATE\n self.state_obj = us.states.lookup(self.fips)\n self.state = self.state_obj.name\n self.geo_metadata = load_data.load_county_metadata_by_state(self.state).loc[self.state].to_dict()\n\n self.times, self.observed_new_cases, self.observed_new_deaths = \\\n load_data.load_new_case_data_by_state(self.state, self.ref_date)\n\n self.hospital_times, self.hospitalizations, self.hospitalization_data_type = \\\n load_data.load_hospitalization_data_by_state(self.state_obj.abbr, t0=self.ref_date)\n self.display_name = self.state\n else:\n self.agg_level = AggregationLevel.COUNTY\n self.geo_metadata = load_data.load_county_metadata().set_index('fips').loc[fips].to_dict()\n self.state = self.geo_metadata['state']\n self.state_obj = us.states.lookup(self.state)\n self.county = self.geo_metadata['county']\n if self.county:\n self.display_name = self.county + ', ' + self.state\n else:\n self.display_name = self.state\n # TODO Swap for new data source.\n self.times, self.observed_new_cases, self.observed_new_deaths = \\\n load_data.load_new_case_data_by_fips(self.fips, t0=self.ref_date)\n self.hospital_times, self.hospitalizations, self.hospitalization_data_type = \\\n load_data.load_hospitalization_data(self.fips, t0=self.ref_date)\n\n self.cases_stdev, self.hosp_stdev, self.deaths_stdev = self.calculate_observation_errors()\n\n self.fit_params = self.DEFAULT_FIT_PARAMS\n # Update any state specific params.\n for k, v in self.PARAM_SETS.items():\n if self.state_obj.abbr in k:\n self.fit_params.update(v)\n\n self.fit_params['fix_hosp_fraction'] = self.hospitalizations is None\n if self.hospitalizations is None:\n self.fit_params['hosp_fraction'] = 1\n\n self.model_fit_keys = ['R0', 'eps', 't_break', 'log10_I_initial']\n\n self.SEIR_kwargs = self.get_average_seir_parameters()\n self.fit_results = None\n self.mle_model = None\n\n self.chi2_deaths = None\n self.chi2_cases = None\n self.chi2_hosp = None\n self.dof_deaths = None\n self.dof_cases = None\n self.dof_hosp = None\n\n def get_average_seir_parameters(self):\n \"\"\"\n Generate the additional fitter candidates from the ensemble generator. This\n has the suppression policy and R0 keys removed.\n\n Returns\n -------\n SEIR_kwargs: dict\n The average ensemble params.\n \"\"\"\n SEIR_kwargs = ParameterEnsembleGenerator(\n fips=self.fips,\n N_samples=5000,\n t_list=self.t_list,\n suppression_policy=None).get_average_seir_parameters()\n\n SEIR_kwargs = {k: v for k, v in SEIR_kwargs.items() if k not in self.fit_params}\n del SEIR_kwargs['suppression_policy']\n del SEIR_kwargs['I_initial']\n return SEIR_kwargs\n\n def calculate_observation_errors(self):\n \"\"\"\n Generate the errors on the observations.\n\n Here we throw out a few assumptions to plant a flag...\n\n 1. Systematic errors dominate and are likely of order 50% at least based\n on 100% undercounting of deaths and hospitalizations in many places.\n Though we account for static undercounting by letting case and hosp\n counts float, so lets assume the error is a bit smaller for now.\n\n 2. 100% is too small for 1 case count or mortality.. We should be much\n more confident in large numbers of observations\n 3. TODO: Deal with this fact.. Actual observations are lower bounds.\n Need asymmetric errors.\n\n As an error model, absolutes are less important to our problem compared\n to getting relative error scaling reasonably done. This is not true if\n drawing contours and confidence intervals which is why we choose large\n conservative errors to overestimate the uncertainty.\n\n As a relative scaling model we think about Poisson processes and scale\n the errors in the following way:\n\n 1. Set the error of the largest observation to 100% of its value.\n 2. Scale all other errors based on sqrt(value) * sqrt(max_value)\n\n Returns\n -------\n cases_stdev: array-like\n Float uncertainties (stdev) for case data.\n hosp_stdev: array-like\n Float uncertainties (stdev) for hosp data.\n deaths_stdev: array-like\n Float uncertainties (stdev) for death data.\n Float uncertainties (stdev) for death data.\n \"\"\"\n # Stdev 50% of values.\n cases_stdev = self.percent_error_on_max_observation * self.cases_to_deaths_err_factor \\\n * self.observed_new_cases ** 0.5 * self.observed_new_cases.max() ** 0.5\n deaths_stdev = self.percent_error_on_max_observation \\\n * self.observed_new_deaths ** 0.5 * self.observed_new_deaths.max() ** 0.5\n\n # add a bit more error in cases with very few deaths. This upweights cases and hospitalizations in this regime.\n deaths_stdev[self.observed_new_deaths <= 4] = deaths_stdev[self.observed_new_deaths <= 4] * 3\n\n # If cumulative hospitalizations, differentiate.\n if self.hospitalization_data_type is HospitalizationDataType.CUMULATIVE_HOSPITALIZATIONS:\n hosp_data = (self.hospitalizations[1:] - self.hospitalizations[:-1]).clip(min=0)\n hosp_stdev = self.percent_error_on_max_observation * \\\n self.hospital_to_deaths_err_factor * hosp_data ** 0.5 * hosp_data.max() ** 0.5\n # Increase errors a bit for very low hospitalizations. There are clear outliers due to data quality.\n hosp_stdev[hosp_data <= 2] *= 3\n\n elif self.hospitalization_data_type is HospitalizationDataType.CURRENT_HOSPITALIZATIONS:\n hosp_data = self.hospitalizations\n hosp_stdev = self.percent_error_on_max_observation \\\n * self.hospital_to_deaths_err_factor * hosp_data ** 0.5 * hosp_data.max() ** 0.5\n # Increase errors a bit for very low hospitalizations. There are clear outliers due to data quality.\n hosp_stdev[hosp_data <= 2] *= 3\n else:\n hosp_stdev = None\n\n # Zero inflated poisson Avoid floating point errors..\n cases_stdev[cases_stdev == 0] = 1e10\n deaths_stdev[deaths_stdev == 0] = 1e10\n if hosp_stdev is not None:\n hosp_stdev[hosp_stdev == 0] = 1e10\n\n return cases_stdev, hosp_stdev, deaths_stdev\n\n def run_model(self, R0, eps, t_break, log10_I_initial):\n \"\"\"\n Generate the model and run.\n\n Parameters\n ----------\n R0: float\n Basic reproduction number\n eps: float\n Fraction of reduction in contact rates as result of to suppression\n policy projected into future.\n t_break: float\n Timing for the switch in suppression policy.\n log10_I_initial:\n log10 initial infections.\n\n Returns\n -------\n model: SEIRModel\n The SEIR model that has been run.\n \"\"\"\n # Leaving this block since we likely want to switch back shortly.\n # if by == 'fips':\n # suppression_policy = \\\n # suppression_policies.generate_empirical_distancing_policy(\n # fips=fips, future_suppression=eps, **suppression_policy_params)\n # elif by == 'state':\n # # TODO: This takes > 200ms which is 10x the model run time. Can be optimized...\n # suppression_policy = \\\n # suppression_policies.generate_empirical_distancing_policy_by_state(\n # state=state, future_suppression=eps, **suppression_policy_params)\n suppression_policy = suppression_policies.generate_two_step_policy(self.t_list, eps, t_break)\n\n # Load up some number of initial exposed so the initial flow into infected is stable.\n self.SEIR_kwargs['E_initial'] = self.steady_state_exposed_to_infected_ratio * 10 ** log10_I_initial\n\n model = SEIRModel(\n R0=R0,\n suppression_policy=suppression_policy,\n I_initial=10 ** log10_I_initial,\n **self.SEIR_kwargs)\n model.run()\n return model\n\n def _fit_seir(self, R0, t0, eps, t_break, test_fraction, hosp_fraction,\n log10_I_initial):\n \"\"\"\n Fit SEIR model by MLE.\n\n Parameters\n ----------\n R0: float\n Basic reproduction number\n t0: float\n Epidemic starting time.\n eps: float\n Fraction of reduction in contact rates as result of to suppression\n policy projected into future.\n t_break: float\n Timing for the switch in suppression policy.\n test_fraction: float\n Fraction of cases that get tested.\n hosp_fraction: float\n Fraction of actual hospitalizations vs the total.\n log10_I_initial:\n log10 initial infections.\n\n Returns\n -------\n : float\n Chi square of fitting model to observed cases and deaths.\n \"\"\"\n l = locals()\n model_kwargs = {k: l[k] for k in self.model_fit_keys}\n model = self.run_model(**model_kwargs)\n\n # -----------------------------------\n # Chi2 Cases\n # -----------------------------------\n # Extract the predicted rates from the model.\n predicted_cases = (test_fraction * model.gamma\n * np.interp(self.times, self.t_list + t0, model.results['total_new_infections']))\n chi2_cases = np.sum((self.observed_new_cases - predicted_cases) ** 2 / self.cases_stdev ** 2)\n\n # -----------------------------------\n # Chi2 Hospitalizations\n # -----------------------------------\n if self.hospitalization_data_type is HospitalizationDataType.CURRENT_HOSPITALIZATIONS:\n predicted_hosp = hosp_fraction * np.interp(self.hospital_times,\n self.t_list + t0,\n model.results['HGen'] +\n model.results['HICU'])\n chi2_hosp = np.sum((self.hospitalizations - predicted_hosp) ** 2 / self.hosp_stdev ** 2)\n self.dof_hosp = (self.observed_new_cases > 0).sum()\n\n elif self.hospitalization_data_type is HospitalizationDataType.CUMULATIVE_HOSPITALIZATIONS:\n # Cumulative, so differentiate the data\n cumulative_hosp_predicted = model.results['HGen_cumulative'] + model.results['HICU_cumulative']\n new_hosp_predicted = cumulative_hosp_predicted[1:] - cumulative_hosp_predicted[:-1]\n new_hosp_predicted = hosp_fraction * np.interp(self.hospital_times[1:], self.t_list[1:] + t0, new_hosp_predicted)\n new_hosp_observed = self.hospitalizations[1:] - self.hospitalizations[:-1]\n\n chi2_hosp = np.sum((new_hosp_observed - new_hosp_predicted) ** 2 / self.hosp_stdev ** 2)\n self.dof_hosp = (self.observed_new_cases > 0).sum()\n else:\n chi2_hosp = 0\n self.dof_hosp = 1e-10\n\n # -----------------------------------\n # Chi2 Deaths\n # -----------------------------------\n # Only use deaths if there are enough observations..\n predicted_deaths = np.interp(self.times, self.t_list + t0, model.results['total_deaths_per_day'])\n if self.observed_new_deaths.sum() > self.min_deaths:\n chi2_deaths = np.sum((self.observed_new_deaths - predicted_deaths) ** 2 / self.deaths_stdev ** 2)\n else:\n chi2_deaths = 0\n\n self.chi2_deaths = chi2_deaths\n self.chi2_cases = chi2_cases\n self.chi2_hosp = chi2_hosp\n self.dof_deaths = (self.observed_new_deaths > 0).sum()\n self.dof_cases = (self.observed_new_cases > 0).sum()\n\n return chi2_deaths + chi2_cases + chi2_hosp\n\n def get_posterior_estimate_eps(self, R0, eps, eps_error, plot=False):\n \"\"\"\n Generate a posterior estimate for epsilon based on the inferred R0. This\n is a little weird right now since we actually want a prior on Reff. So\n in this case we use the inferred R0 to convert eps -> Reff, apply a\n prior, and invert this transform to get back to the epsilon Max\n A-Posteriori (MAP) estimate.\n\n Returns\n -------\n posterior_map_estimate: float\n Max A-Posteriori (MAP) estimate for epsilon.\n \"\"\"\n R_eff = R0 * eps\n R_eff_stdev = R0 * eps_error\n\n x = np.linspace(0.00, 10, 1001)\n delta_x = x[1] - x[0]\n\n # This implements a hard lower limit of 0.98.\n # TODO: As more data comes in, relax this.. Probably just use MCMC..\n prior = gamma.pdf((x - 0.98) / 1.5, 1.1)\n # Add a tiny amount to the likelihood to prevent zero common support\n # between the prior and likelihood functions.\n likelihood = norm.pdf(x, R_eff, R_eff_stdev) + 0.0001\n posterior = prior * likelihood\n posterior = posterior / (posterior.sum() * delta_x)\n posterior_MAP_estimate = x[np.argmax(posterior)] / R0\n\n if plot:\n plt.plot(x, prior, label='Prior')\n plt.plot(x, likelihood, label='Likelihood')\n plt.plot(x, posterior, label='Posterior')\n plt.grid()\n plt.legend()\n\n return posterior_MAP_estimate\n\n def fit(self):\n \"\"\"\n Fit a model to the data.\n \"\"\"\n minuit = iminuit.Minuit(self._fit_seir, **self.fit_params, print_level=1)\n\n # run MIGRAD algorithm for optimization.\n # for details refer: https://root.cern/root/html528/TMinuit.html\n minuit.migrad(precision=1e-5)\n self.fit_results = dict(fips=self.fips, **dict(minuit.values))\n self.fit_results.update({k + '_error': v for k, v in dict(minuit.errors).items()})\n\n # This just updates chi2 values\n self._fit_seir(**dict(minuit.values))\n\n if self.fit_results['eps'] < 0.1:\n raise RuntimeError(f'Fit failed for {self.state, self.fips}: '\n f'Epsilon == 0 which implies lack of convergence.')\n\n # Sometimes this is estimated to be way to small (incorrectly since we\n # don't know the true error model). This is a problem for bayesian\n # updates. Set a lower bound for the error here.\n self.fit_results['eps_error'] = max(self.fit_results['eps_error'], 0.05)\n\n # TODO: Add confidence intervals here.\n self.fit_results['eps'] = self.get_posterior_estimate_eps(\n R0=self.fit_results['R0'], eps=self.fit_results['eps'],\n eps_error=self.fit_results['eps_error'])\n\n if np.isnan(self.fit_results['t0']):\n logging.error(f'Could not compute MLE values for {self.display_name}')\n self.fit_results['t0_date'] = self.ref_date + timedelta(days=self.t0_guess).isoformat()\n else:\n self.fit_results['t0_date'] = (self.ref_date + timedelta(days=self.fit_results['t0'])).isoformat()\n self.fit_results['t_today'] = (datetime.today() - self.ref_date).days\n\n self.fit_results['Reff'] = self.fit_results['R0'] * self.fit_results['eps']\n\n self.fit_results['chi2_cases'] = self.chi2_cases\n if self.hospitalizations is not None:\n self.fit_results['chi2_hosps'] = self.chi2_hosp\n self.fit_results['chi2_deaths'] = self.chi2_deaths\n\n if self.hospitalization_data_type:\n self.fit_results['hospitalization_data_type'] = self.hospitalization_data_type.value\n else:\n self.fit_results['hospitalization_data_type'] = self.hospitalization_data_type\n\n try:\n param_state = minuit.get_param_states()\n logging.info(f'Fit Results for {self.display_name} \\n {param_state}')\n except:\n param_state = dict(minuit.values)\n logging.info(f'Fit Results for {self.display_name} \\n {param_state}')\n\n logging.info(f'Complete fit results for {self.display_name} \\n {pformat(self.fit_results)}')\n self.mle_model = self.run_model(**{k: self.fit_results[k] for k in self.model_fit_keys})\n\n def plot_fitting_results(self):\n \"\"\"\n Plotting model fitting results.\n \"\"\"\n data_dates = [self.ref_date + timedelta(days=t) for t in self.times]\n if self.hospital_times is not None:\n hosp_dates = [self.ref_date + timedelta(days=float(t)) for t in self.hospital_times]\n model_dates = [self.ref_date + timedelta(days=t + self.fit_results['t0']) for t in self.t_list]\n\n # Don't display the zero-inflated error bars\n cases_err = np.array(self.cases_stdev)\n cases_err[cases_err > 1e5] = 0\n death_err = deepcopy(self.deaths_stdev)\n death_err[death_err > 1e5] = 0\n if self.hosp_stdev is not None:\n hosp_stdev = deepcopy(self.hosp_stdev)\n hosp_stdev[hosp_stdev > 1e5] = 0\n\n plt.figure(figsize=(18, 12))\n plt.errorbar(data_dates, self.observed_new_cases, yerr=cases_err,\n marker='o', linestyle='', label='Observed Cases Per Day',\n color='steelblue', capsize=3, alpha=.4, markersize=10)\n plt.errorbar(data_dates, self.observed_new_deaths, yerr=death_err,\n marker='d', linestyle='', label='Observed Deaths Per Day',\n color='firebrick', capsize=3, alpha=.4, markersize=10)\n\n plt.plot(model_dates, self.mle_model.results['total_new_infections'],\n label='Estimated Total New Infections Per Day', linestyle='--',\n lw=4, color='steelblue')\n plt.plot(model_dates,\n self.fit_results['test_fraction'] * self.mle_model.results[\n 'total_new_infections'],\n label='Estimated Tested New Infections Per Day',\n color='steelblue', lw=4)\n\n plt.plot(model_dates, self.mle_model.results['total_deaths_per_day'],\n label='Model Deaths Per Day', color='firebrick', lw=4)\n\n if self.hospitalization_data_type is HospitalizationDataType.CUMULATIVE_HOSPITALIZATIONS:\n new_hosp_observed = self.hospitalizations[\n 1:] - self.hospitalizations[:-1]\n plt.errorbar(hosp_dates[1:], new_hosp_observed, yerr=hosp_stdev,\n marker='s', linestyle='',\n label='Observed New Hospitalizations Per Day',\n color='darkseagreen', capsize=3, alpha=1)\n predicted_hosp = (self.mle_model.results['HGen_cumulative'] +\n self.mle_model.results['HICU_cumulative'])\n predicted_hosp = predicted_hosp[1:] - predicted_hosp[:-1]\n plt.plot(model_dates[1:],\n self.fit_results['hosp_fraction'] * predicted_hosp,\n label='Estimated Total New Hospitalizations Per Day',\n linestyle='-.', lw=4, color='darkseagreen', markersize=10)\n elif self.hospitalization_data_type is HospitalizationDataType.CURRENT_HOSPITALIZATIONS:\n plt.errorbar(hosp_dates, self.hospitalizations, yerr=hosp_stdev,\n marker='s', linestyle='',\n label='Observed Total Current Hospitalizations',\n color='darkseagreen', capsize=3, alpha=.5,\n markersize=10)\n predicted_hosp = (self.mle_model.results['HGen'] + self.mle_model.results['HICU'])\n plt.plot(model_dates,\n self.fit_results['hosp_fraction'] * predicted_hosp,\n label='Estimated Total Current Hospitalizations',\n linestyle='-.', lw=4, color='darkseagreen')\n\n plt.plot(model_dates,\n self.fit_results['hosp_fraction'] * self.mle_model.results['HICU'],\n label='Estimated ICU Occupancy',\n linestyle=':', lw=6, color='black')\n plt.plot(model_dates,\n self.fit_results['hosp_fraction'] * self.mle_model.results['HGen'],\n label='Estimated General Occupancy',\n linestyle=':', lw=4, color='black', alpha=0.4)\n\n plt.yscale('log')\n y_lim = plt.ylim(.8e0)\n\n start_intervention_date = self.ref_date + timedelta(days=self.fit_results['t_break'] + self.fit_results['t0'])\n stop_intervention_date = start_intervention_date + timedelta(days=14)\n\n plt.fill_betweenx([y_lim[0], y_lim[1]],\n [start_intervention_date, start_intervention_date],\n [stop_intervention_date, stop_intervention_date], alpha=0.2, label='Estimated Intervention')\n\n running_total = timedelta(days=0)\n for i_label, k in enumerate((\n 'symptoms_to_hospital_days',\n 'hospitalization_length_of_stay_general',\n 'hospitalization_length_of_stay_icu')):\n\n end_time = timedelta(days=self.SEIR_kwargs[k])\n x = start_intervention_date + running_total\n y = 1.5 ** (i_label + 1)\n plt.errorbar(x=[x],\n y=[y],\n xerr=[[timedelta(days=0)], [end_time]],\n marker='', capsize=8, color='k', elinewidth=3, capthick=3)\n plt.text(x + (end_time + timedelta(days=2)), y, k.replace('_', ' ').title(), fontsize=14)\n running_total += end_time\n\n plt.hlines(self.SEIR_kwargs['beds_ICU'], *plt.xlim(), color='k', linestyles='-', linewidths=6, alpha=0.2)\n plt.text(data_dates[0] + timedelta(days=5), self.SEIR_kwargs['beds_ICU'] * 1.1, 'Available ICU Capacity',\n color='k', alpha=0.5, fontsize=15)\n\n plt.ylim(*y_lim)\n plt.xlim(data_dates[0], data_dates[-1] + timedelta(days=150))\n plt.xticks(rotation=30, fontsize=14)\n plt.yticks(fontsize=14)\n plt.legend(loc=4, fontsize=14)\n plt.grid(which='both', alpha=.5)\n plt.title(self.display_name, fontsize=20)\n\n for i, (k, v) in enumerate(self.fit_results.items()):\n\n fontweight = 'bold' if k in ('R0', 'Reff') else 'normal'\n\n if np.isscalar(v) and not isinstance(v, str):\n plt.text(1.05, .7 - 0.032 * i, f'{k}={v:1.3f}', transform=plt.gca().transAxes, fontsize=15, alpha=.6, fontweight=fontweight)\n else:\n plt.text(1.05, .7 - 0.032 * i, f'{k}={v}', transform=plt.gca().transAxes, fontsize=15, alpha=.6, fontweight=fontweight)\n\n output_file = get_run_artifact_path(self.fips, RunArtifact.MLE_FIT_REPORT)\n plt.savefig(output_file, bbox_inches='tight')\n plt.close()\n\n self.mle_model.plot_results()\n plt.savefig(output_file.replace('mle_fit_results', 'mle_fit_model'), bbox_inches='tight')\n plt.close()\n\n @classmethod\n def run_for_fips(cls, fips, n_retries=3):\n \"\"\"\n Run the model fitter for a state or county fips code.\n\n Parameters\n ----------\n fips: str\n 2-digit state or 5-digit county fips code.\n n_retries: int\n The model fitter is stochastic in nature and a seed cannot be set.\n This is a bandaid until more sophisticated retries can be\n implemented.\n\n Returns\n -------\n : ModelFitter\n \"\"\"\n # Assert that there are some cases for counties\n if len(fips) == 5:\n _, observed_new_cases, _ = load_data.load_new_case_data_by_fips(\n fips, t0=datetime.today())\n if observed_new_cases.sum() < 1:\n return None\n\n try:\n for i in range(n_retries):\n model_fitter = cls(fips)\n try:\n model_fitter.fit()\n if model_fitter.mle_model:\n model_fitter.plot_fitting_results()\n break\n except RuntimeError as e:\n logging.warning('No convergence.. Retrying ' + str(e))\n if model_fitter.mle_model is None:\n raise RuntimeError(f'Could not converge after {n_retries} for fips {fips}')\n except Exception:\n logging.exception(f\"Failed to run {fips}\")\n return None\n return model_fitter\n\n\ndef run_state(state, states_only=False):\n \"\"\"\n Run the fitter for each county in a state.\n\n Parameters\n ----------\n state: str\n State to run against.\n states_only: bool\n If True only run the state level.\n \"\"\"\n state_obj = us.states.lookup(state)\n logging.info(f'Running MLE fitter for state {state_obj.name}')\n\n model_fitter = ModelFitter.run_for_fips(state_obj.fips)\n\n df_whitelist = load_data.load_whitelist()\n df_whitelist = df_whitelist[df_whitelist['inference_ok'] == True]\n\n output_path = get_run_artifact_path(state_obj.fips, RunArtifact.MLE_FIT_RESULT)\n pd.DataFrame(model_fitter.fit_results, index=[state_obj.fips]).to_json(output_path)\n\n with open(get_run_artifact_path(state_obj.fips, RunArtifact.MLE_FIT_MODEL), 'wb') as f:\n pickle.dump(model_fitter.mle_model, f)\n\n # Run the counties.\n if not states_only:\n all_fips = df_whitelist[df_whitelist['state'].str.lower() == state_obj.name.lower()].fips.values\n\n if len(all_fips) > 0:\n p = Pool()\n fitters = p.map(ModelFitter.run_for_fips, all_fips)\n p.close()\n\n county_output_file = get_run_artifact_path(all_fips[0], RunArtifact.MLE_FIT_RESULT)\n pd.DataFrame([fit.fit_results for fit in fitters if fit]).to_json(county_output_file)\n\n # Serialize the model results.\n for fips, fitter in zip(all_fips, fitters):\n if fitter:\n with open(get_run_artifact_path(fips, RunArtifact.MLE_FIT_MODEL), 'wb') as f:\n pickle.dump(fitter.mle_model, f)\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linspace", "pandas.DataFrame", "matplotlib.pyplot.plot", "matplotlib.pyplot.fill_betweenx", "matplotlib.pyplot.gca", "numpy.argmax", "numpy.interp", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.isnan", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "numpy.array", "numpy.sum", "matplotlib.pyplot.xticks", "numpy.random.seed", "scipy.stats.norm.pdf", "scipy.stats.gamma.pdf", "matplotlib.pyplot.yscale", "matplotlib.pyplot.xlim", "matplotlib.pyplot.grid", "numpy.isscalar", "matplotlib.pyplot.yticks" ] ]
dushyantkhosla/dataviz
[ "05a004a390d180d87be2d09873c3f7283c2a2e27" ]
[ "99-Miscel/AnatomyOfMatplotlib-master/solutions/4.2-spines_ticks_and_subplot_spacing.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\n\ndata = [('dogs', 4, 4), ('frogs', -3, 1), ('cats', 1, 5), ('goldfish', -2, 2)]\nanimals, friendliness, popularity = zip(*data)\n\n\ndef plot_and_setup_spines(ax, animals, y, ylabel):\n x = np.arange(len(animals))\n ax.bar(x, y, align='center', color='gray')\n ax.set(xticks=x, xticklabels=animals, ylabel=ylabel)\n\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n ax.spines['bottom'].set_position(('data', 0))\n ax.tick_params(axis='x', direction='inout', length=8)\n ax.margins(0.05)\n\nfig, axes = plt.subplots(nrows=2)\nfig.subplots_adjust(hspace=0.0)\n\nplot_and_setup_spines(axes[0], animals, friendliness, 'Friendliness')\nplot_and_setup_spines(axes[1], animals, popularity, 'Popularity')\n\nplt.show()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
ksuarz/monary
[ "e8775ef11a8f9f020bacbaa2d8e802da1c0b4c19" ]
[ "monary/monary.py" ]
[ "# Monary - Copyright 2011-2014 David J. C. Beach\n# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.\n\nimport atexit\nimport os.path\nimport platform\nimport sys\nfrom copy import deepcopy\nfrom ctypes import *\n\nPY3 = sys.version_info[0] >= 3\nif PY3:\n # Python 3\n bytes_type = bytes\n string_type = str\n from urllib.parse import urlencode\nelse:\n # Python 2.6/2.7\n bytes_type = basestring\n string_type = basestring\n from urllib import urlencode\n\ntry:\n # if we are using Python 2.7+\n from collections import OrderedDict\nexcept ImportError:\n # for Python 2.6 and earlier\n from .ordereddict import OrderedDict\n\nimport numpy\nimport bson\n\ncmonary = None\n\ndef _load_cmonary_lib():\n \"\"\"Loads the cmonary CDLL library (from the directory containing this module).\"\"\"\n global cmonary\n thismodule = __file__\n abspath = os.path.abspath(thismodule)\n moduledir = list(os.path.split(abspath))[:-1]\n if platform.system() == 'Windows':\n libbson = CDLL(os.path.join(*(moduledir + ['libbson-1.0.dll'])))\n libcmongo = CDLL(os.path.join(*(moduledir + ['libmongoc-1.0.dll'])))\n cmonary_fname = \"libcmonary.dll\"\n else:\n cmonary_fname = \"libcmonary.so\"\n cmonaryfile = os.path.join(*(moduledir + [cmonary_fname]))\n cmonary = CDLL(cmonaryfile)\n\n_load_cmonary_lib()\n\nCTYPE_CODES = {\n \"P\": c_void_p, # pointer\n \"S\": c_char_p, # string\n \"I\": c_int, # int\n \"U\": c_uint, # unsigned int\n \"L\": c_long, # long\n \"0\": None, # None/void\n}\n\n# List of C function definitions from the cmonary library\nFUNCDEFS = [\n # format: \"func_name:arg_types:return_type\"\n \"monary_init::0\",\n \"monary_cleanup::0\",\n \"monary_connect:S:P\",\n \"monary_disconnect:P:0\",\n \"monary_use_collection:PSS:P\",\n \"monary_destroy_collection:P:0\",\n \"monary_alloc_column_data:UU:P\",\n \"monary_free_column_data:P:I\",\n \"monary_set_column_item:PUSUUPP:I\",\n \"monary_query_count:PP:L\",\n \"monary_init_query:PUUPPI:P\",\n \"monary_init_aggregate:PPP:P\",\n \"monary_load_query:P:I\",\n \"monary_close_query:P:0\",\n]\n\nMAX_COLUMNS = 1024\nMAX_STRING_LENGTH = 1024\n\ndef _decorate_cmonary_functions():\n \"\"\"Decorates each of the cmonary functions with their argument and result types.\"\"\"\n for funcdef in FUNCDEFS:\n name, argtypes, restype = funcdef.split(\":\")\n func = getattr(cmonary, name)\n func.argtypes = [ CTYPE_CODES[c] for c in argtypes ]\n func.restype = CTYPE_CODES[restype]\n\n_decorate_cmonary_functions()\n\n# Initialize Monary and register the cleanup function\ncmonary.monary_init()\natexit.register(cmonary.monary_cleanup)\n\n# Table of type names and conversions between cmonary and numpy types\nMONARY_TYPES = {\n # \"common_name\": (cmonary_type_code, numpy_type_object)\n \"id\": (1, \"<V12\"),\n \"bool\": (2, numpy.bool),\n \"int8\": (3, numpy.int8),\n \"int16\": (4, numpy.int16),\n \"int32\": (5, numpy.int32),\n \"int64\": (6, numpy.int64),\n \"uint8\": (7, numpy.uint8),\n \"uint16\": (8, numpy.uint16),\n \"uint32\": (9, numpy.uint32),\n \"uint64\": (10, numpy.uint64),\n \"float32\": (11, numpy.float32),\n \"float64\": (12, numpy.float64),\n \"date\": (13, numpy.int64),\n \"timestamp\": (14, numpy.uint64),\n # Note, numpy strings do not need the null character\n \"string\": (15, \"S\"),\n # Raw data (void pointer)\n \"binary\": (16, \"<V\"),\n \"bson\": (17, \"<V\"),\n \"type\": (18, numpy.uint8),\n \"size\": (19, numpy.uint32),\n \"length\": (20, numpy.uint32),\n}\n\ndef get_monary_numpy_type(orig_typename):\n \"\"\"Given a common typename, find the corresponding cmonary type number,\n type argument, and numpy type object (or code).\n\n The input typename must be one of the keys found in the ``MONARY_TYPES``\n dictionary. These are common BSON type names such as ``id``, ``bool``,\n ``int32``, ``float64``, ``date``, or ``string``. If the type is ``string``,\n ``binary``, or ``bson``, its name must be followed by a ``:size`` suffix\n indicating the maximum number of bytes that will be used to store the\n representation.\n\n :param str orig_typename: a common type name with optional argument\n (for fields with a size)\n :returns: (type_num, type_arg, numpy_type)\n :rtype: tuple\n \"\"\"\n # process any type_arg that might be included\n if ':' in orig_typename:\n vals = orig_typename.split(':', 2)\n if len(vals) > 2:\n raise ValueError(\"too many parts in type: %r\" % orig_typename)\n type_name, arg = vals\n try:\n type_arg = int(arg)\n except ValueError:\n raise ValueError(\"unable to parse type argument in: %r\" % orig_typename)\n else:\n type_arg = 0\n type_name = orig_typename\n\n if type_name not in MONARY_TYPES:\n raise ValueError(\"unknown typename: %r\" % type_name)\n if type_name in (\"string\", \"binary\", \"bson\"):\n if type_arg == 0:\n raise ValueError(\"%r must have an explicit typearg with nonzero length \"\n \"(use 'string:20', for example)\" % type_name)\n type_num, numpy_type_code = MONARY_TYPES[type_name]\n numpy_type = \"%s%i\" % (numpy_type_code, type_arg)\n else:\n type_num, numpy_type = MONARY_TYPES[type_name]\n return type_num, type_arg, numpy_type\n\ndef make_bson(obj):\n \"\"\"Given a Python (JSON compatible) dictionary, returns a BSON string.\n\n (This hijacks the Python -> BSON conversion code from pymongo, which is needed for\n converting queries. Perhaps this dependency can be removed in a later version.)\n\n :param obj: object to be encoded as BSON (dict, string, or None)\n :returns: BSON encoded representation (byte string)\n :rtype: str\n \"\"\"\n if obj is None:\n obj = { }\n if not isinstance(obj, bytes_type):\n obj = bson.BSON.encode(obj)\n return obj\n\n\ndef mvoid_to_bson_id(mvoid):\n \"\"\"Converts a numpy mvoid value to a BSON ObjectId.\n\n :param mvoid: numpy.ma.core.mvoid returned from Monary\n :returns: the _id as a bson ObjectId\n :rtype: bson.objectid.ObjectId\n \"\"\"\n if PY3:\n # Python 3\n string = str(mvoid)\n string_list = ''.join(filter(lambda x: x not in '[]', string)).split()\n ints = map(int, string_list)\n uints = [x & 0xff for x in ints]\n id_bytes = bytes(uints)\n return bson.ObjectId(id_bytes)\n else:\n # Python 2.6 / 2.7\n return bson.ObjectId(str(mvoid))\n\n\ndef get_ordering_dict(obj):\n \"\"\"Converts a field/direction specification to an OrderedDict, suitable\n for BSON encoding.\n \n :param obj: single field name or list of (field, direction) pairs\n :returns: mapping representing the field/direction list\n :rtype: OrderedDict\n \"\"\"\n if obj is None:\n return OrderedDict()\n elif isinstance(obj, string_type):\n return OrderedDict([(obj, 1)])\n elif isinstance(obj, list):\n return OrderedDict(obj)\n else:\n raise ValueError(\"invalid ordering: should be str or list of (column, direction) pairs\")\n\ndef get_plain_query(query):\n \"\"\"Composes a plain query from the given query object.\n \n :param dict query: query dictionary (or None)\n :returns: BSON encoded query (byte string)\n :rtype: str\n \"\"\"\n if query is None:\n query = { }\n return make_bson(query)\n\ndef get_full_query(query, sort=None, hint=None):\n \"\"\"Composes a full query from the given query object, and sort and hint clauses, if provided.\n \n :param dict query: query dictionary (or None)\n :param sort: (optional) single field name or list of (field, direction) pairs\n :param hint: (optional) single field name or list of (field, direction) pairs\n :returns: BSON encoded query (byte string)\n :rtype: str\n \"\"\"\n if query is None:\n query = { }\n\n if sort or hint:\n query = OrderedDict([(\"$query\", query)])\n if sort:\n try:\n query[\"$orderby\"] = get_ordering_dict(sort)\n except ValueError:\n raise ValueError(\"sort arg must be string or list of (field, direction) pairs\")\n if hint:\n try:\n query[\"$hint\"] = get_ordering_dict(hint)\n except ValueError:\n raise ValueError(\"hint arg must be string or list of (field, direction) pairs\")\n \n return make_bson(query)\n\ndef get_pipeline(pipeline):\n \"\"\"Manipulates the input pipeline into a usable form.\n \"\"\"\n if isinstance(pipeline, list):\n pipeline = {\"pipeline\" : pipeline}\n elif isinstance(pipeline, dict):\n if not \"pipeline\" in pipeline:\n pipeline = {\"pipeline\" : [pipeline]}\n else:\n raise TypeError(\"Pipeline must be a dict or a list\")\n return pipeline\n\n\nclass Monary(object):\n \"\"\"Represents a 'monary' connection to a particular MongoDB server.\"\"\"\n \n def __init__(self, host=\"localhost\", port=27017, username=None,\n password=None, database=None, options={}):\n \"\"\"Initialize this connection with the given host and port.\n \n :param host: either host name (or IP) to connect to, or full URI\n :param port: port number of running MongoDB service on host\n :param username: An optional username for authentication.\n :param password: An optional password for authentication.\n :param database: The database to authenticate to if the URI\n specifies a username and password. If this is not specified but\n credentials exist, this defaults to the \"admin\" database. See\n mongoc_uri(7).\n :param options: Connection-specific options as a dict.\n \"\"\"\n\n self._cmonary = cmonary\n self._connection = None\n if not self.connect(host, port, username, password, database, options):\n raise ValueError(\"Misformatted Mongo URI.\")\n\n def connect(self, host=\"localhost\", port=27017, username=None,\n password=None, database=None, options={}):\n \"\"\"Connects to the given host and port.\n\n :param host: either host name (or IP) to connect to, or full URI\n :param port: port number of running MongoDB service on host\n :param username: An optional username for authentication.\n :param password: An optional password for authentication.\n :param database: The database to authenticate to if the URI\n specifies a username and password. If this is not specified but\n credentials exist, this defaults to the \"admin\" database. See\n mongoc_uri(7).\n :param options: Connection-specific options as a dict.\n\n :returns: True if successful; false otherwise.\n :rtype: bool\n \"\"\"\n\n if self._connection is not None:\n self.close()\n\n if host.startswith(\"mongodb://\"):\n uri = host\n else:\n # Build up the URI string.\n uri = [\"mongodb://\"]\n if username is not None:\n if password is None:\n uri.append(\"%s@\" % username)\n else:\n uri.append(\"%s:%s@\" % (username, password))\n elif password is not None:\n raise ValueError(\"You cannot have a password with no username.\")\n\n uri.append(\"%s:%d\" % (host, port))\n\n if database is not None:\n uri.append(\"/%s\" % database)\n if len(options) > 0:\n uri.append(\"?%s\" % urlencode(options))\n uri = \"\".join(uri)\n\n # Attempt the connection\n self._connection = cmonary.monary_connect(uri.encode('ascii'))\n return (self._connection is not None)\n\n def _make_column_data(self, fields, types, count):\n \"\"\"Builds the 'column data' structure used by the underlying cmonary code to\n populate the arrays. This code must allocate the array objects, and provide\n their corresponding storage pointers and sizes to cmonary.\n\n :param fields: list of field names\n :param types: list of Monary type names\n :param count: size of storage to be allocated\n \n :returns: (coldata, colarrays) where coldata is the cmonary\n column data storage structure, and colarrays is a list of\n numpy.ndarray instances\n :rtype: tuple\n \"\"\"\n\n if len(fields) != len(types):\n raise ValueError(\"number of fields and types do not match\")\n numcols = len(fields)\n if numcols > MAX_COLUMNS:\n raise ValueError(\"number of fields exceeds maximum of %d\" % MAX_COLUMNS)\n coldata = cmonary.monary_alloc_column_data(numcols, count)\n colarrays = [ ]\n for i, (field, typename) in enumerate(zip(fields, types)):\n if len(field) > MAX_STRING_LENGTH:\n raise ValueError(\"length of field name %s exceeds \"\n \"maximum of %d\" % (field, MAX_COLUMNS))\n\n cmonary_type, cmonary_type_arg, numpy_type = get_monary_numpy_type(typename)\n\n data = numpy.zeros([count], dtype=numpy_type)\n mask = numpy.ones([count], dtype=bool)\n storage = numpy.ma.masked_array(data, mask)\n colarrays.append(storage)\n\n data_p = data.ctypes.data_as(c_void_p)\n mask_p = mask.ctypes.data_as(c_void_p)\n cmonary.monary_set_column_item(coldata, i, field.encode('ascii'),\n cmonary_type, cmonary_type_arg,\n data_p, mask_p)\n\n return coldata, colarrays\n\n def _get_collection(self, db, collection):\n \"\"\"Returns the specified collection to query against.\n\n :param db: name of database\n :param collection: name of collection\n\n :returns: the collection\n :rtype: cmonary mongoc_collection_t*\n \"\"\"\n if self._connection is not None:\n return cmonary.monary_use_collection(self._connection,\n db.encode('ascii'),\n collection.encode('ascii'))\n else:\n raise ValueError(\"failed to get collection %s.%s - not connected\" % (db, collection))\n\n def count(self, db, coll, query=None):\n \"\"\"Count the number of records that will be returned by the given query.\n \n :param db: name of database\n :param coll: name of the collection to be queried\n :param query: (optional) dictionary of Mongo query parameters\n \n :returns: the number of records\n :rtype: int\n \"\"\"\n collection = None\n try:\n collection = self._get_collection(db, coll)\n if collection is None:\n raise ValueError(\"couldn't connect to collection %s.%s\" % (db, coll))\n query = make_bson(query)\n count = cmonary.monary_query_count(collection, query)\n finally:\n if collection is not None:\n cmonary.monary_destroy_collection(collection)\n if count < 0:\n raise RuntimeError(\"Internal error in count()\")\n return count\n\n def query(self, db, coll, query, fields, types,\n sort=None, hint=None,\n limit=0, offset=0,\n do_count=True, select_fields=False):\n \"\"\"Performs an array query.\n \n :param db: name of database\n :param coll: name of the collection to be queried\n :param query: dictionary of Mongo query parameters\n :param fields: list of fields to be extracted from each record\n :param types: corresponding list of field types\n :param sort: (optional) single field name or list of (field, direction) pairs\n :param hint: (optional) single field name or list of (field, direction) pairs\n :param limit: (optional) limit number of records (and size of arrays)\n :param offset: (optional) skip this many records before gathering results\n :param bool do_count: count items before allocating arrays\n (otherwise, array size is set to limit)\n :param bool select_fields: select exact fields from database\n (performance/bandwidth tradeoff)\n\n :returns: list of numpy.ndarray, corresponding to the requested fields and types\n :rtype: list\n \"\"\"\n\n plain_query = get_plain_query(query)\n full_query = get_full_query(query, sort, hint)\n \n if not do_count and limit > 0:\n count = limit\n else:\n # count() doesn't like $query/$orderby/$hint clauses, so we need to use a plain query\n count = self.count(db, coll, plain_query)\n\n if count > limit > 0:\n count = limit\n\n coldata = None\n try:\n coldata, colarrays = self._make_column_data(fields, types, count)\n cursor = None\n try:\n collection = self._get_collection(db, coll)\n if collection is None:\n raise ValueError(\"unable to get the collection\")\n cursor = cmonary.monary_init_query(collection, offset, limit,\n full_query, coldata, select_fields)\n cmonary.monary_load_query(cursor)\n finally:\n if cursor is not None:\n cmonary.monary_close_query(cursor)\n if collection is not None:\n cmonary.monary_destroy_collection(collection)\n finally:\n if coldata is not None:\n cmonary.monary_free_column_data(coldata)\n return colarrays\n\n def block_query(self, db, coll, query, fields, types,\n sort=None, hint=None,\n block_size=8192, limit=0, offset=0,\n select_fields=False):\n \"\"\"Performs a block query.\n\n :param db: name of database\n :param coll: name of the collection to be queried\n :param query: dictionary of Mongo query parameters\n :param fields: list of fields to be extracted from each record\n :param types: corresponding list of field types\n :param sort: (optional) single field name or list of (field, direction) pairs\n :param hint: (optional) single field name or list of (field, direction) pairs\n :param block_size: (optional) size in number of rows of each yeilded list \n :param limit: (optional) limit number of records (and size of arrays)\n :param offset: (optional) skip this many records before gathering results\n :param bool select_fields: select exact fields from database\n (performance/bandwidth tradeoff)\n\n :returns: list of numpy.ndarray, corresponding to the requested fields and types\n :rtype: list\n\n A block query is a query whose results are returned in\n blocks of a given size. Instead of returning a list of arrays, this generator\n yields portions of each array in multiple blocks, where each block may contain\n up to *block_size* elements.\n\n An example::\n \n cumulative_gain = 0.0\n for buy_price_block, sell_price_block in (\n monary.block_query(\"finance\", \"assets\", {\"sold\": True},\n [\"buy_price\", \"sell_price\"],\n [\"float64\", \"float64\"],\n block_size=1024)):\n gain = sell_price_block - buy_price_block # vector subtraction\n cumulative_gain += numpy.sum(gain)\n\n .. note:: Memory for each block is reused between iterations. If the\n caller wishes to retain the values from a given iteration, it\n should copy the data.\n \"\"\"\n\n if block_size < 1:\n block_size = 1\n\n full_query = get_full_query(query, sort, hint)\n\n coldata = None\n try:\n coldata, colarrays = self._make_column_data(fields, types, block_size)\n cursor = None\n try:\n collection = self._get_collection(db, coll)\n if collection is None:\n raise ValueError(\"unable to get the collection\")\n cursor = cmonary.monary_init_query(collection, offset, limit,\n full_query, coldata, select_fields)\n while True:\n num_rows = cmonary.monary_load_query(cursor)\n if num_rows == block_size:\n yield colarrays\n elif num_rows > 0:\n yield [ arr[:num_rows] for arr in colarrays ]\n break\n else:\n break\n finally:\n if cursor is not None:\n cmonary.monary_close_query(cursor)\n if collection is not None:\n cmonary.monary_destroy_collection(collection)\n finally:\n if coldata is not None:\n cmonary.monary_free_column_data(coldata)\n\n def aggregate(self, db, coll, pipeline, fields, types, limit=0,\n do_count=True):\n \"\"\"Performs an aggregation operation.\n\n :param: db: name of database\n :param coll: name of collection on which to perform the aggregation\n :param pipeline: a list of pipeline stages\n :param fields: list of fields to be extracted from the result\n :param types: corresponding list of field types\n\n :returns: list of numpy.ndarray, corresponding to the requested\n fields and types\n :rtype: list\n \"\"\"\n # Convert the pipeline to a usable form\n pipeline = get_pipeline(pipeline)\n\n # Determine sizing for array allocation\n if not do_count and limit > 0:\n # Limit ourselves to only the first ``count`` records.\n count = limit\n else:\n # Use the aggregation pipeline to count the result size\n count_stage = {\"$group\" : {\"_id\" : 1, \"count\" : {\"$sum\" : 1}}}\n pipe_copy = deepcopy(pipeline)\n pipe_copy[\"pipeline\"].append(count_stage)\n\n # Extract the count\n result, = self.aggregate(db, coll, pipe_copy, [\"count\"], [\"int64\"],\n limit=1, do_count=False)\n result = result.compressed()\n if len(result) == 0:\n # The count returned was masked\n raise RuntimeError(\"Failed to count the aggregation size\")\n else:\n count = result[0]\n\n if count > limit > 0:\n count = limit\n\n encoded_pipeline = get_plain_query(pipeline)\n coldata = None\n try:\n coldata, colarrays = self._make_column_data(fields, types, count)\n cursor = None\n try:\n collection = self._get_collection(db, coll)\n if collection is None:\n raise ValueError(\"unable to get the collection\")\n cursor = cmonary.monary_init_aggregate(collection,\n encoded_pipeline,\n coldata)\n cmonary.monary_load_query(cursor)\n finally:\n if cursor is not None:\n cmonary.monary_close_query(cursor)\n if collection is not None:\n cmonary.monary_destroy_collection(collection)\n finally:\n if coldata is not None:\n cmonary.monary_free_column_data(coldata)\n return colarrays\n\n def block_aggregate(self, db, coll, pipeline, fields, types,\n block_size=8192, limit=0):\n \"\"\"Performs an aggregation operation.\n\n Perform an aggregation operation on a collection, returning the\n results in blocks of size ``block_size``.\n \"\"\"\n if block_size < 1:\n block_size = 1\n\n pipeline = get_pipeline(pipeline)\n encoded_pipeline = get_plain_query(pipeline)\n\n coldata = None\n try:\n coldata, colarrays = self._make_column_data(fields,\n types,\n block_size)\n cursor = None\n try:\n collection = self._get_collection(db, coll)\n if collection is None:\n raise ValueError(\"unable to get the collection\")\n cursor = cmonary.monary_init_aggregate(collection,\n encoded_pipeline,\n coldata)\n\n while True:\n num_rows = cmonary.monary_load_query(cursor)\n if num_rows == block_size:\n yield colarrays\n elif num_rows > 0:\n yield [arr[:num_rows] for arr in colarrays]\n break\n else:\n break\n finally:\n if cursor is not None:\n cmonary.monary_close_query(cursor)\n if collection is not None:\n cmonary.monary_destroy_collection(collection)\n finally:\n if coldata is not None:\n cmonary.monary_free_column_data(coldata)\n\n def close(self):\n \"\"\"Closes the current connection, if any.\"\"\"\n if self._connection is not None:\n cmonary.monary_disconnect(self._connection)\n self._connection = None\n \n def __enter__(self):\n \"\"\"Monary connections meet the ContextManager protocol.\"\"\"\n return self\n \n def __exit__(self, *args):\n \"\"\"Monary connections meet the ContextManager protocol.\"\"\"\n self.close()\n \n def __del__(self):\n \"\"\"Closes the Monary connection and cleans up resources.\"\"\"\n self.close()\n self._cmonary = None\n" ]
[ [ "numpy.ma.masked_array", "numpy.zeros", "numpy.ones" ] ]
ictnlp/STEMM
[ "e3ae1903be5534f860fcd71ea9c9ef1c0f6267e9" ]
[ "fairseq/data/audio/audio_utils.py" ]
[ "from pathlib import Path\nfrom typing import BinaryIO, Optional, Tuple, Union, List\n\nimport os\nimport numpy as np\nimport torch\nimport torchaudio\n\n\nSF_AUDIO_FILE_EXTENSIONS = {\".wav\", \".flac\", \".ogg\"}\nFEATURE_OR_SF_AUDIO_FILE_EXTENSIONS = {\".npy\", \".wav\", \".flac\", \".ogg\"}\n\n\ndef _convert_to_mono(\n waveform: torch.FloatTensor, sample_rate: int\n) -> torch.FloatTensor:\n if waveform.shape[0] > 1:\n try:\n import torchaudio.sox_effects as ta_sox\n except ImportError:\n raise ImportError(\n \"Please install torchaudio to convert multi-channel audios\"\n )\n effects = [['channels', '1']]\n return ta_sox.apply_effects_tensor(waveform, sample_rate, effects)[0]\n return waveform\n\n\ndef convert_to_mono(waveform: np.ndarray, sample_rate: int) -> np.ndarray:\n if waveform.shape[0] > 1:\n _waveform = torch.from_numpy(waveform)\n return _convert_to_mono(_waveform, sample_rate).numpy()\n return waveform\n\n\ndef get_waveform(\n path_or_fp: Union[str, BinaryIO], normalization=True, mono=True,\n frames=-1, start=0, always_2d=True\n) -> Tuple[np.ndarray, int]:\n \"\"\"Get the waveform and sample rate of a 16-bit WAV/FLAC/OGG Vorbis audio.\n\n Args:\n path_or_fp (str or BinaryIO): the path or file-like object\n normalization (bool): Normalize values to [-1, 1] (Default: True)\n mono (bool): convert multi-channel audio to mono-channel one\n frames (int): the number of frames to read. (-1 for reading all)\n start (int): Where to start reading. A negative value counts from the end.\n always_2d (bool): always return 2D array even for mono-channel audios\n Returns:\n waveform (numpy.ndarray): 1D or 2D waveform (channels x length)\n sample_rate (float): sample rate\n \"\"\"\n if isinstance(path_or_fp, str):\n ext = Path(path_or_fp).suffix\n if ext not in SF_AUDIO_FILE_EXTENSIONS:\n raise ValueError(f\"Unsupported audio format: {ext}\")\n\n try:\n import soundfile as sf\n except ImportError:\n raise ImportError(\n \"Please install soundfile to load WAV/FLAC/OGG Vorbis audios\"\n )\n\n waveform, sample_rate = sf.read(\n path_or_fp, dtype=\"float32\", always_2d=True, frames=frames, start=start\n )\n waveform = waveform.T # T x C -> C x T\n if mono and waveform.shape[0] > 1:\n waveform = convert_to_mono(waveform, sample_rate)\n if not normalization:\n waveform *= 2 ** 15 # denormalized to 16-bit signed integers\n if not always_2d:\n waveform = waveform.squeeze(axis=0)\n return waveform, sample_rate\n\n\ndef get_segment_waveform(\n path_or_fp, offset, n_frames, normalization=True\n):\n if isinstance(path_or_fp, str):\n ext = os.path.splitext(os.path.basename(path_or_fp))[1]\n if ext not in {\".flac\", \".wav\"}:\n raise ValueError(f\"Unsupported audio format: {ext}\")\n\n waveform, sample_rate = torchaudio.load(path_or_fp, frame_offset=offset, num_frames=n_frames)\n if not normalization:\n waveform *= 2 ** 15\n return waveform, sample_rate\n\n\ndef _get_kaldi_fbank(\n waveform: np.ndarray, sample_rate: int, n_bins=80\n) -> Optional[np.ndarray]:\n \"\"\"Get mel-filter bank features via PyKaldi.\"\"\"\n try:\n from kaldi.feat.mel import MelBanksOptions\n from kaldi.feat.fbank import FbankOptions, Fbank\n from kaldi.feat.window import FrameExtractionOptions\n from kaldi.matrix import Vector\n\n mel_opts = MelBanksOptions()\n mel_opts.num_bins = n_bins\n frame_opts = FrameExtractionOptions()\n frame_opts.samp_freq = sample_rate\n opts = FbankOptions()\n opts.mel_opts = mel_opts\n opts.frame_opts = frame_opts\n fbank = Fbank(opts=opts)\n features = fbank.compute(Vector(waveform.squeeze()), 1.0).numpy()\n return features\n except ImportError:\n return None\n\n\ndef _get_torchaudio_fbank(\n waveform: np.ndarray, sample_rate, n_bins=80\n) -> Optional[np.ndarray]:\n \"\"\"Get mel-filter bank features via TorchAudio.\"\"\"\n try:\n import torchaudio.compliance.kaldi as ta_kaldi\n waveform = torch.from_numpy(waveform)\n features = ta_kaldi.fbank(\n waveform, num_mel_bins=n_bins, sample_frequency=sample_rate\n )\n return features.numpy()\n except ImportError:\n return None\n\n\ndef get_fbank(path_or_fp: Union[str, BinaryIO], n_bins=80) -> np.ndarray:\n \"\"\"Get mel-filter bank features via PyKaldi or TorchAudio. Prefer PyKaldi\n (faster CPP implementation) to TorchAudio (Python implementation). Note that\n Kaldi/TorchAudio requires 16-bit signed integers as inputs and hence the\n waveform should not be normalized.\"\"\"\n waveform, sample_rate = get_waveform(path_or_fp, normalization=False)\n\n features = _get_kaldi_fbank(waveform, sample_rate, n_bins)\n if features is None:\n features = _get_torchaudio_fbank(waveform, sample_rate, n_bins)\n if features is None:\n raise ImportError(\n \"Please install pyKaldi or torchaudio to enable \"\n \"online filterbank feature extraction\"\n )\n\n return features\n\n\ndef is_npy_data(data: bytes) -> bool:\n return data[0] == 147 and data[1] == 78\n\n\ndef is_sf_audio_data(data: bytes) -> bool:\n is_wav = (data[0] == 82 and data[1] == 73 and data[2] == 70)\n is_flac = (data[0] == 102 and data[1] == 76 and data[2] == 97)\n is_ogg = (data[0] == 79 and data[1] == 103 and data[2] == 103)\n return is_wav or is_flac or is_ogg\n\n\ndef read_from_stored_zip(zip_path: str, offset: int, file_size: int) -> bytes:\n with open(zip_path, \"rb\") as f:\n f.seek(offset)\n data = f.read(file_size)\n return data\n\n\ndef parse_path(path: str) -> Tuple[str, List[int]]:\n \"\"\"Parse data path which is either a path to\n 1. a .npy/.wav/.flac/.ogg file\n 2. a stored ZIP file with slicing info: \"[zip_path]:[offset]:[length]\"\n\n Args:\n path (str): the data path to parse\n\n Returns:\n file_path (str): the file path\n slice_ptr (list of int): empty in case 1;\n byte offset and length for the slice in case 2\n \"\"\"\n\n if Path(path).suffix in FEATURE_OR_SF_AUDIO_FILE_EXTENSIONS:\n _path, slice_ptr = path, []\n else:\n _path, *slice_ptr = path.split(\":\")\n if not Path(_path).is_file():\n raise FileNotFoundError(f\"File not found: {_path}\")\n assert len(slice_ptr) in {0, 2}, f\"Invalid path: {path}\"\n slice_ptr = [int(i) for i in slice_ptr]\n return _path, slice_ptr\n" ]
[ [ "torch.from_numpy" ] ]
joaopaulocastro/resnetkeras
[ "8c65bd386e77b91a67fac4433cb3497f91875e41" ]
[ "DataGenerator.py" ]
[ "\"\"\"\n This is the class used to provide trainning examples to the model in real time, during trainning\n\n Is this implementation, it gets data from pre-processed files (resulting of the pre-processing and data augmentation steps)\n\"\"\"\n\n# imports\nimport keras\nimport Constants as const\nimport numpy as np\nimport h5py\n\nclass DataGeneratorFromPreprocessed(keras.utils.Sequence):\n 'Generates data for Keras'\n def __init__(self, QtdeExamples, QtdeBatches, QtdeChannels = const.X_Channels):\n 'Initialization'\n # folder where to fetch data\n self.folderPath = const.PreprocessedDataFolderPath(QtdeExamples)\n self.qtdeBatches = QtdeBatches\n self.qtdeChannels = QtdeChannels\n self.on_epoch_end()\n\n def __len__(self):\n 'Denotes the number of batches per epoch'\n return self.qtdeBatches\n\n def on_epoch_end(self):\n 'Updates indexes after each epoch'\n self.indexes = np.arange(self.qtdeBatches - 1)\n np.random.shuffle(self.indexes)\n self.indexes = np.append(self.indexes, self.qtdeBatches - 1)\n\n def __getitem__(self, index):\n 'Generate one batch of data'\n X, y = self.__data_generation(index)\n\n return X, y\n\n def __data_generation(self, index):\n 'Generates data containing batch_size samples'\n i = self.indexes[index]\n f = h5py.File(self.folderPath + 'XY' + str(i+1) + '.hdf5', \"r\")\n x0 = f['X'][:]\n Y = f['Y'][:]\n f.close()\n\n if self.qtdeChannels == const.X_Channels:\n X = x0\n else:\n shape = (x0.shape[0], x0.shape[1], x0.shape[2], self.qtdeChannels)\n X = np.zeros(shape, np.float16)\n X[:,:,:,:] = x0\n\n return X, Y\n" ]
[ [ "numpy.arange", "numpy.append", "numpy.zeros", "numpy.random.shuffle" ] ]
fugokidi/block_transform
[ "752041f3681776e335e442fa53ce294d008cf024", "752041f3681776e335e442fa53ce294d008cf024" ]
[ "cifar10/keydefense.py", "imagenet/keydefense.py" ]
[ "\"\"\"\nThis module contains all the key-based transformation for adversarial defense.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport pyffx\n\n__all__ = [\"Shuffle\", \"NP\", \"FFX\"]\n\n\nclass BlockTransform(nn.Module):\n \"\"\"\n Generic class for block-wise transformation.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.block_size = config.block_size\n assert (\n config.height % self.block_size == 0 | config.width % self.block_size == 0\n ), \"Image not divisible by block_size\"\n self.blocks_axis0 = int(config.height / self.block_size)\n self.blocks_axis1 = int(config.width / self.block_size)\n self.mean = torch.Tensor(config.mean)\n self.std = torch.Tensor(config.std)\n\n def segment(self, X):\n X = X.permute(0, 2, 3, 1)\n X = X.reshape(\n -1,\n self.blocks_axis0,\n self.block_size,\n self.blocks_axis1,\n self.block_size,\n 3,\n )\n X = X.permute(0, 1, 3, 2, 4, 5)\n X = X.reshape(\n -1,\n self.blocks_axis0,\n self.blocks_axis1,\n self.block_size * self.block_size * 3,\n )\n return X\n\n def integrate(self, X):\n X = X.reshape(\n -1,\n self.blocks_axis0,\n self.blocks_axis1,\n self.block_size,\n self.block_size,\n 3,\n )\n X = X.permute(0, 1, 3, 2, 4, 5)\n X = X.reshape(\n -1,\n self.blocks_axis0 * self.block_size,\n self.blocks_axis1 * self.block_size,\n 3,\n )\n X = X.permute(0, 3, 1, 2)\n return X\n\n def generate_key(self, seed, binary=False):\n torch.manual_seed(seed)\n key = torch.randperm(self.block_size * self.block_size * 3)\n if binary:\n key = key > len(key) / 2\n return key\n\n def normalize(self, X):\n return (X - self.mean.type_as(X)[None, :, None, None]) / self.std.type_as(X)[\n None, :, None, None\n ]\n\n def denormalize(self, X):\n return (X * self.std.type_as(X)[None, :, None, None]) + self.mean.type_as(X)[\n None, :, None, None\n ]\n\n def forward(self, X, decrypt=False):\n raise NotImplementedError\n\n\nclass Shuffle(BlockTransform):\n def __init__(self, config):\n super().__init__(config)\n self.key = self.generate_key(config.seed, binary=False)\n\n def forward(self, X, decrypt=False):\n X = self.segment(X)\n if decrypt:\n key = torch.argsort(self.key)\n X = X[:, :, :, key]\n else:\n X = X[:, :, :, self.key]\n X = self.integrate(X)\n return X.contiguous()\n\n\nclass NP(BlockTransform):\n def __init__(self, config):\n super().__init__(config)\n self.key = self.generate_key(config.seed, binary=True)\n\n def forward(self, X, decrypt=False):\n # uncomment the following during training\n # X = self.denormalize(X)\n X = self.segment(X)\n X[:, :, :, self.key] = 1 - X[:, :, :, self.key]\n X = self.integrate(X)\n # uncomment the following during training\n # X = self.normalize(X)\n return X.contiguous()\n\n\nclass FFX(BlockTransform):\n def __init__(self, config):\n super().__init__(config)\n self.key = self.generate_key(config.seed, binary=True)\n self.lookup, self.relookup = self.generate_lookup(config.password)\n self.lookup, self.relookup = self.lookup.cuda(), self.relookup.cuda()\n\n def generate_lookup(self, password=\"password\"):\n password = str.encode(password)\n fpe = pyffx.Integer(password, length=3)\n f = lambda x: fpe.encrypt(x)\n g = lambda x: fpe.decrypt(x)\n f = np.vectorize(f)\n g = np.vectorize(g)\n lookup = f(np.arange(256))\n relookup = g(np.arange(1000))\n lookup = torch.from_numpy(lookup)\n relookup = torch.from_numpy(relookup)\n return lookup, relookup\n\n def forward(self, X, decrypt=False):\n # uncomment the following during training\n # X = self.denormalize(X)\n X = self.segment(X)\n if decrypt:\n X = (X * self.lookup.max()).long()\n X[:, :, :, self.key] = self.relookup[X[:, :, :, self.key]]\n X = X.float()\n X = X / 255.0\n else:\n # important: without it cuda trigerring devise assertion error with index out of bound\n X = torch.clamp(X, 0, 1)\n X = (X * 255).long()\n X[:, :, :, self.key] = self.lookup[X[:, :, :, self.key]].clone()\n X = X.float()\n X = X / self.lookup.max()\n X = self.integrate(X)\n # uncomment the following during training\n # X = self.normalize(X)\n return X.contiguous()\n", "\"\"\"\nThis module contains all the key-based transformation for adversarial defense.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport pyffx\n\n__all__ = [\"Shuffle\", \"NP\", \"FFX\"]\n\n\nclass BlockTransform(nn.Module):\n \"\"\"\n Generic class for block-wise transformation.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.block_size = config.block_size\n assert (\n config.height % self.block_size == 0 | config.width % self.block_size == 0\n ), \"Image not divisible by block_size\"\n self.blocks_axis0 = int(config.height / self.block_size)\n self.blocks_axis1 = int(config.width / self.block_size)\n self.mean = torch.Tensor(config.TRAIN.mean)\n self.std = torch.Tensor(config.TRAIN.std)\n\n def segment(self, X):\n X = X.permute(0, 2, 3, 1)\n X = X.reshape(\n -1,\n self.blocks_axis0,\n self.block_size,\n self.blocks_axis1,\n self.block_size,\n 3,\n )\n X = X.permute(0, 1, 3, 2, 4, 5)\n X = X.reshape(\n -1,\n self.blocks_axis0,\n self.blocks_axis1,\n self.block_size * self.block_size * 3,\n )\n return X\n\n def integrate(self, X):\n X = X.reshape(\n -1,\n self.blocks_axis0,\n self.blocks_axis1,\n self.block_size,\n self.block_size,\n 3,\n )\n X = X.permute(0, 1, 3, 2, 4, 5)\n X = X.reshape(\n -1,\n self.blocks_axis0 * self.block_size,\n self.blocks_axis1 * self.block_size,\n 3,\n )\n X = X.permute(0, 3, 1, 2)\n return X\n\n def generate_key(self, seed, binary=False):\n torch.manual_seed(seed)\n key = torch.randperm(self.block_size * self.block_size * 3)\n if binary:\n key = key > len(key) / 2\n return key\n\n def normalize(self, X):\n return (X - self.mean.type_as(X)[None, :, None, None]) / self.std.type_as(X)[\n None, :, None, None\n ]\n\n def denormalize(self, X):\n return (X * self.std.type_as(X)[None, :, None, None]) + self.mean.type_as(X)[\n None, :, None, None\n ]\n\n def forward(self, X, decrypt=False):\n raise NotImplementedError\n\n\nclass Shuffle(BlockTransform):\n def __init__(self, config):\n super().__init__(config)\n self.key = self.generate_key(config.seed, binary=False)\n\n def forward(self, X, decrypt=False):\n X = self.segment(X)\n if decrypt:\n key = torch.argsort(self.key)\n X = X[:, :, :, key]\n else:\n X = X[:, :, :, self.key]\n X = self.integrate(X)\n return X.contiguous()\n\n\nclass NP(BlockTransform):\n def __init__(self, config):\n super().__init__(config)\n self.key = self.generate_key(config.seed, binary=True)\n\n def forward(self, X, decrypt=False):\n # uncomment the following during training\n # X = self.denormalize(X)\n X = self.segment(X)\n X[:, :, :, self.key] = 1 - X[:, :, :, self.key]\n X = self.integrate(X)\n # uncomment the following during training\n # X = self.normalize(X)\n return X.contiguous()\n\n\nclass FFX(BlockTransform):\n def __init__(self, config):\n super().__init__(config)\n self.key = self.generate_key(config.seed, binary=True)\n self.lookup, self.relookup = self.generate_lookup(config.password)\n self.lookup, self.relookup = self.lookup.cuda(), self.relookup.cuda()\n\n def generate_lookup(self, password=\"password\"):\n password = str.encode(password)\n fpe = pyffx.Integer(password, length=3)\n f = lambda x: fpe.encrypt(x)\n g = lambda x: fpe.decrypt(x)\n f = np.vectorize(f)\n g = np.vectorize(g)\n lookup = f(np.arange(256))\n relookup = g(np.arange(1000))\n lookup = torch.from_numpy(lookup)\n relookup = torch.from_numpy(relookup)\n return lookup, relookup\n\n def forward(self, X, decrypt=False):\n # uncomment the following during training\n # X = self.denormalize(X)\n X = self.segment(X)\n if decrypt:\n X = (X * self.lookup.max()).long()\n X[:, :, :, self.key] = self.relookup[X[:, :, :, self.key]]\n X = X.float()\n X = X / 255.0\n else:\n # important: without it cuda trigerring devise assertion error with index out of bound\n X = torch.clamp(X, 0, 1)\n X = (X * 255).long()\n X[:, :, :, self.key] = self.lookup[X[:, :, :, self.key]]\n X = X.float()\n X = X / self.lookup.max()\n X = self.integrate(X)\n # uncomment the following during training\n # X = self.normalize(X)\n return X.contiguous()\n" ]
[ [ "torch.clamp", "torch.Tensor", "torch.randperm", "torch.manual_seed", "numpy.arange", "torch.from_numpy", "numpy.vectorize", "torch.argsort" ], [ "torch.clamp", "torch.Tensor", "torch.randperm", "torch.manual_seed", "numpy.arange", "torch.from_numpy", "numpy.vectorize", "torch.argsort" ] ]
TaoSunVoyage/fastcluster
[ "4414d9402db127140cbafa7d063d10967fc04c9b" ]
[ "src/python/tests/vectortest.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# TBD test single on integer matrices for hamming/jaccard\nprint('''\nTest program for the 'fastcluster' package.\nCopyright:\n * Until package version 1.1.23: (c) 2011 Daniel Müllner <http://danifold.net>\n * All changes from version 1.1.24 on: (c) Google Inc. <http://google.com>''')\nimport sys\nimport fastcluster as fc\nimport numpy as np\nfrom scipy.spatial.distance import pdist, squareform\nimport math\n\nversion = '1.2.3'\nif fc.__version__ != version:\n raise ValueError('Wrong module version: {} instead of {}.'.format(fc.__version__, version))\n\nimport atexit\ndef print_seed():\n print(\"Seed: {0}\".format(seed))\natexit.register(print_seed)\n\nseed = np.random.randint(0,1e9)\n\nprint_seed()\nnp.random.seed(seed)\nabstol = 1e-14 # absolute tolerance\nrtol = 1e-13 # relative tolerance\n\n# NaN values are used in computations. Do not warn about them.\nnp.seterr(invalid='ignore')\n\ndef correct_for_zero_vectors(D, pcd, metric):\n # Correct some metrics: we want the distance from the zero vector\n # to itself to be 0, not NaN.\n if metric in ('jaccard', 'dice', 'sokalsneath'):\n z = np.flatnonzero(np.all(pcd==0, axis=1))\n if len(z):\n DD = squareform(D)\n DD[np.ix_(z, z)] = 0\n D = squareform(DD)\n return D\n\ndef test_all(n,dim):\n method = 'single'\n\n # metrics for boolean vectors\n pcd = np.random.randint(0, 2, size=(n,dim), dtype=bool)\n pcd2 = pcd.copy()\n\n for metric in ('hamming', 'jaccard', 'yule', 'matching', 'dice',\n 'rogerstanimoto',\n #'sokalmichener',\n # exclude, bug in Scipy\n # http://projects.scipy.org/scipy/ticket/1486\n 'russellrao', 'sokalsneath',\n #'kulsinski'\n # exclude, bug in Scipy\n # http://projects.scipy.org/scipy/ticket/1484\n ):\n sys.stdout.write(\"Metric: \" + metric + \"...\")\n D = pdist(pcd, metric=metric)\n D = correct_for_zero_vectors(D, pcd, metric)\n\n try:\n Z2 = fc.linkage_vector(pcd, method, metric)\n except FloatingPointError:\n # If linkage_vector reported a NaN dissimilarity value,\n # check whether the distance matrix really contains NaN.\n if np.any(np.isnan(D)):\n print(\"Skip this test: NaN dissimilarity value.\")\n continue\n else:\n raise AssertionError('\"linkage_vector\" erroneously reported NaN.')\n\n if np.any(pcd2!=pcd):\n raise AssertionError('Input array was corrupted.', pcd)\n check(Z2, method, D)\n\n # metrics for real vectors\n bound = math.sqrt(n)\n pcd = np.random.randint(-bound, bound + 1, (n,dim))\n for metric in ['euclidean', 'sqeuclidean', 'cityblock', 'chebychev',\n 'minkowski', 'cosine', 'correlation', 'hamming', 'jaccard',\n 'canberra',\n # canberra: see bug in older Scipy versions\n # http://projects.scipy.org/scipy/ticket/1430\n 'braycurtis', 'seuclidean', 'mahalanobis', 'user']:\n sys.stdout.write(\"Metric: \" + metric + \"...\")\n if metric=='minkowski':\n p = np.random.uniform(1.,10.)\n sys.stdout.write(\"p: \" + str(p) + \"...\")\n D = pdist(pcd, metric=metric, p=p)\n Z2 = fc.linkage_vector(pcd, method, metric, p)\n elif metric=='user':\n # Euclidean metric as a user function\n fn = (lambda u, v: np.sqrt(((u-v)*(u-v).T).sum()))\n D = pdist(pcd, metric=fn)\n Z2 = fc.linkage_vector(pcd, method, fn)\n else:\n D = pdist(pcd, metric=metric)\n D = correct_for_zero_vectors(D, pcd, metric)\n try:\n Z2 = fc.linkage_vector(pcd, method, metric)\n except FloatingPointError:\n if np.any(np.isnan(D)):\n print(\"Skip this test: NaN dissimilarity value.\")\n continue\n else:\n raise AssertionError(\n '\"linkage_vector\" erroneously reported NaN.')\n\n check(Z2, method, D)\n\n D = pdist(pcd)\n for method in ['ward', 'centroid', 'median']:\n Z2 = fc.linkage_vector(pcd, method)\n check(Z2, method, D)\n\ndef check(Z2, method, D):\n sys.stdout.write(\"Method: \" + method + \"...\")\n I = np.array(Z2[:,:2], dtype=int)\n\n Ds = squareform(D)\n n = len(Ds)\n row_repr = np.arange(2*n-1)\n row_repr[n:] = -1\n size = np.ones(n, dtype=int)\n\n np.fill_diagonal(Ds, np.nan)\n\n mins = np.empty(n-1)\n\n for i in range(n-1):\n for j in range(n-1):\n mins[j] = np.nanmin(Ds[j,j+1:])\n gmin = np.nanmin(mins)\n if abs(Z2[i,2]-gmin) > max(abs(Z2[i,2]),abs(gmin))*rtol and \\\n abs(Z2[i,2]-gmin)>abstol:\n raise AssertionError(\n 'Not the global minimum in step {2}: {0}, {1}'.\n format(Z2[i,2], gmin,i), squareform(D))\n i1, i2 = row_repr[I[i,:]]\n if (i1<0):\n raise AssertionError('Negative index i1.', squareform(D))\n if (i2<0):\n raise AssertionError('Negative index i2.', squareform(D))\n if I[i,0]>=I[i,1]:\n raise AssertionError('Convention violated.', squareform(D))\n if i1>i2:\n i1, i2 = i2, i1\n if abs(Ds[i1,i2]-gmin) > max(abs(Ds[i1,i2]),abs(gmin))*rtol and \\\n abs(Ds[i1,i2]-gmin)>abstol:\n raise AssertionError(\n 'The global minimum is not at the right place in step {5}: '\n '({0}, {1}): {2} != {3}. Difference: {4}'\n .format(i1, i2, Ds[i1, i2], gmin, Ds[i1, i2]-gmin, i),\n squareform(D))\n\n s1 = size[i1]\n s2 = size[i2]\n S = float(s1+s2)\n if method=='single':\n if i1>0: # mostly unnecessary; workaround for a bug/feature in NumPy\n # 1.7.0.dev, see http://projects.scipy.org/numpy/ticket/2078\n Ds[:i1,i2] = np.min( Ds[:i1,(i1,i2)],axis=1)\n Ds[i1:i2,i2] = np.minimum(Ds[i1,i1:i2],Ds[i1:i2,i2])\n Ds[i2,i2:] = np.min( Ds[(i1,i2),i2:],axis=0)\n elif method=='complete':\n if i1>0:\n Ds[:i1,i2] = np.max( Ds[:i1,(i1,i2)],axis=1)\n Ds[i1:i2,i2] = np.maximum(Ds[i1,i1:i2],Ds[i1:i2,i2])\n Ds[i2,i2:] = np.max( Ds[(i1,i2),i2:],axis=0)\n elif method=='average':\n Ds[:i1,i2] = ( Ds[:i1,i1]*s1 + Ds[:i1,i2]*s2 ) / S\n Ds[i1:i2,i2] = ( Ds[i1,i1:i2]*s1 + Ds[i1:i2,i2]*s2 ) / S\n Ds[i2,i2:] = ( Ds[i1,i2:]*s1 + Ds[i2,i2:]*s2 ) / S\n elif method=='weighted':\n if i1>0:\n Ds[:i1,i2] = np.mean( Ds[:i1,(i1,i2)],axis=1)\n Ds[i1:i2,i2] = ( Ds[i1,i1:i2] + Ds[i1:i2,i2] )*.5\n Ds[i2,i2:] = np.mean( Ds[(i1,i2),i2:],axis=0)\n elif method=='ward':\n Ds[:i1,i2] = np.sqrt((np.square(Ds[:i1,i1])*(s1+size[:i1])\n -gmin*gmin*size[:i1]\n +np.square(Ds[:i1,i2])*(s2+size[:i1]))/(S+size[:i1]))\n Ds[i1:i2,i2] = np.sqrt((np.square(Ds[i1,i1:i2])*(s1+size[i1:i2])\n -gmin*gmin*size[i1:i2]\n +np.square(Ds[i1:i2,i2])*(s2+size[i1:i2]))\n /(S+size[i1:i2]))\n Ds[i2,i2:] = np.sqrt((np.square(Ds[i1,i2:])*(s1+size[i2:])\n -gmin*gmin*size[i2:]\n +np.square(Ds[i2,i2:])*(s2+size[i2:]))/(S+size[i2:]))\n elif method=='centroid':\n Ds[:i1,i2] = np.sqrt((np.square(Ds[:i1,i1])*s1\n +np.square(Ds[:i1,i2])*s2)*S-gmin*gmin*s1*s2) / S\n Ds[i1:i2,i2] = np.sqrt((np.square(Ds[i1,i1:i2])*s1\n +np.square(Ds[i1:i2,i2])*s2)*S-gmin*gmin*s1*s2) / S\n Ds[i2,i2:] = np.sqrt((np.square(Ds[i1,i2:])*s1\n +np.square(Ds[i2,i2:])*s2)*S-gmin*gmin*s1*s2) / S\n elif method=='median':\n Ds[:i1,i2] = np.sqrt((np.square(Ds[:i1,i1])\n +np.square(Ds[:i1,i2]))*2-gmin*gmin)*.5\n Ds[i1:i2,i2] = np.sqrt((np.square(Ds[i1,i1:i2])\n +np.square(Ds[i1:i2,i2]))*2-gmin*gmin)*.5\n Ds[i2,i2:] = np.sqrt((np.square(Ds[i1,i2:])\n +np.square(Ds[i2,i2:]))*2-gmin*gmin)*.5\n else:\n raise ValueError('Unknown method.')\n\n Ds[i1, i1:n] = np.inf\n Ds[:i1, i1] = np.inf\n row_repr[n+i] = i2\n size[i2] = S\n print('OK.')\n\ndef test(repeats):\n if repeats:\n iterator = range(repeats)\n else:\n import itertools\n iterator = itertools.repeat(None)\n print('''\nIf everything is OK, the test program will run forever, without an error\nmessage.\n''')\n for _ in iterator:\n dim = np.random.randint(2, 13)\n n = np.random.randint(max(2*dim,5),200)\n\n print('Dimension: {0}'.format(dim))\n print('Number of points: {0}'.format(n))\n\n test_all(n,dim)\n\nif __name__ == \"__main__\":\n test(None)\n" ]
[ [ "numpy.minimum", "numpy.nanmin", "numpy.all", "numpy.seterr", "numpy.max", "numpy.mean", "numpy.fill_diagonal", "numpy.any", "scipy.spatial.distance.squareform", "numpy.random.randint", "numpy.square", "numpy.ix_", "numpy.arange", "numpy.min", "numpy.isnan", "numpy.array", "numpy.maximum", "numpy.random.seed", "numpy.ones", "scipy.spatial.distance.pdist", "numpy.random.uniform", "numpy.empty" ] ]
hugh-braico/skug-stamper
[ "9eae67441dd7d3e20b84e7bba91dfe4f9d3a0e3e" ]
[ "utils/cv2.py" ]
[ "import cv2 as cv\r\nimport numpy as np\r\nimport sys\r\nimport logging\r\nfrom pathlib import Path\r\n\r\n# Read a frame at a specific time from a video\r\ndef get_frame_from_video(capture, seconds, GAME_X, GAME_Y, GAME_SIZE):\r\n capture.set(cv.CAP_PROP_POS_MSEC,(seconds*1000)) \r\n success, image = capture.read()\r\n if not success:\r\n sys.exit(f\"Failed to read frame at t = {seconds} from capture!\")\r\n # Cut down to only the relevant part we're interested in\r\n # This means passing around a smaller array, and also all calculations\r\n # from this point forward can be independent of GAME_X and GAME_Y\r\n y1 = GAME_Y\r\n y2 = GAME_Y + int(GAME_SIZE*0.15)\r\n x1 = GAME_X\r\n x2 = GAME_X + GAME_SIZE - 1\r\n return image[y1:y2, x1:x2]\r\n\r\n\r\ndef avg_colour_of_area(image, y1, y2, x1, x2):\r\n area = image[y1:y2, x1:x2]\r\n return area.mean(axis=0).mean(axis=0)\r\n\r\n\r\n# Determines whether a frame is near the start of a round by looking for the\r\n# presence of a green health bar on both P1 and P2's point characters.\r\ndef is_round_start(image, GAME_SIZE):\r\n\r\n # Take two slices from each health bar, take the average colour, and then\r\n # compare to an \"expected\" green value. \r\n # Needs to be two because stuff like Band's saxophone and Bella's hoop \r\n # intro like to cut through the middle. Very annoying\r\n y1 = int(GAME_SIZE*0.0734)\r\n y2 = y1 + 1\r\n\r\n # Correct/\"expected\" green colours + max allowable error\r\n correct_outer_green = np.array([128.9, 221.8, 218.9])\r\n correct_inner_green = np.array([ 69.7, 126.3, 56.6])\r\n threshold = 9\r\n\r\n # P1 outer slice\r\n p1x1_outer = int(GAME_SIZE*0.146)\r\n p1x2_outer = int(GAME_SIZE*0.225)\r\n p1_outer_avg = avg_colour_of_area(image, y1, y2, p1x1_outer, p1x2_outer)\r\n if np.linalg.norm(p1_outer_avg - correct_outer_green) > threshold:\r\n return False\r\n\r\n # P2 outer slice\r\n p2x1_outer = GAME_SIZE - p1x2_outer\r\n p2x2_outer = GAME_SIZE - p1x1_outer\r\n p2_outer_avg = avg_colour_of_area(image, y1, y2, p2x1_outer, p2x2_outer)\r\n if np.linalg.norm(p2_outer_avg - correct_outer_green) > threshold:\r\n return False\r\n\r\n # P1 inner slice\r\n p1x1_inner = int(GAME_SIZE*0.330)\r\n p1x2_inner = int(GAME_SIZE*0.409)\r\n p1_inner_avg = avg_colour_of_area(image, y1, y2, p1x1_inner, p1x2_inner)\r\n if np.linalg.norm(p1_inner_avg - correct_inner_green) > threshold:\r\n return False\r\n\r\n # P2 inner slice\r\n p2x1_inner = GAME_SIZE - p1x2_inner\r\n p2x2_inner = GAME_SIZE - p1x1_inner\r\n p2_inner_avg = avg_colour_of_area(image, y1, y2, p2x1_inner, p2x2_inner)\r\n if np.linalg.norm(p2_inner_avg - correct_inner_green) > threshold:\r\n return False\r\n\r\n return True\r\n\r\n\r\n# Get character portraits from a frame\r\ndef get_char_imgs(image, char_num, GAME_SIZE):\r\n # funny magic numbers for each portrait's position\r\n if char_num == 1:\r\n y1 = int(GAME_SIZE*0.015625)\r\n y2 = int(GAME_SIZE*0.078125)\r\n p1x1 = int(GAME_SIZE*0.023438)\r\n p1x2 = int(GAME_SIZE*0.117188)\r\n elif char_num == 2:\r\n y1 = int(GAME_SIZE*0.054688)\r\n y2 = int(GAME_SIZE*0.064063)\r\n p1x1 = int(GAME_SIZE*0.134375)\r\n p1x2 = int(GAME_SIZE*0.171875)\r\n else:\r\n y1 = int(GAME_SIZE*0.043750)\r\n y2 = int(GAME_SIZE*0.053125)\r\n p1x1 = int(GAME_SIZE*0.128906)\r\n p1x2 = int(GAME_SIZE*0.166406)\r\n # horizontal flip for player 2\r\n p2x1 = GAME_SIZE - p1x2\r\n p2x2 = GAME_SIZE - p1x1\r\n # crop the image and return\r\n return image[y1:y2, p1x1:p1x2], image[y1:y2, p2x1:p2x2]\r\n\r\n\r\n# Get the player's names from a frame\r\ndef get_name_imgs(image, GAME_SIZE):\r\n # funny magic numbers for each name's position\r\n y1 = int(GAME_SIZE*0.1)\r\n y2 = int(GAME_SIZE*0.1234)\r\n p1x1 = int(GAME_SIZE*0.164)\r\n p1x2 = int(GAME_SIZE*0.352)\r\n # horizontal flip for player 2\r\n p2x1 = GAME_SIZE - p1x2\r\n p2x2 = GAME_SIZE - p1x1\r\n # crop the image and return\r\n return image[y1:y2, p1x1:p1x2], image[y1:y2, p2x1:p2x2]" ]
[ [ "numpy.array", "numpy.linalg.norm" ] ]
choiwb/Computer_Vision_for_Smart_Factory
[ "af182570009beedef75b12a9fc6233f4d0cbdbea", "af182570009beedef75b12a9fc6233f4d0cbdbea" ]
[ "object_tracker_v5.0.py", "object_tracke_v1.0.py" ]
[ "######################################################################\n######################################################################\n# Object Tracking & Object Counting by Line\n# bounding box, label box 좌표 수정\n\n# TEST #\n'''\nmaking csv\nmaking function\n'''\n######################################################################\n######################################################################\n\nfrom models import *\nfrom utils import *\nimport os, sys, time, datetime, random\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport argparse\nimport cv2\nfrom sort import *\nimport csv\n\n# load weights and set defaults\n# YOLO-v3\nconfig_path = 'config/yolov3.cfg'\nweights_path = 'config/yolov3.weights'\nclass_path = 'config/coco.names'\n\nimg_size = 416\nconf_thres = 0.8\nnms_thres = 0.4\n\ncounter = 0\nmemory = {}\n\n# load model and put into eval mode\nmodel = Darknet(config_path, img_size=img_size)\nmodel.load_weights(weights_path)\n\n'''Cuda Running'''\nmodel.cuda()\n\nmodel.eval()\n\nclasses = utils.load_classes(class_path)\nprint(classes)\n\n'''Cuda Running'''\nTensor = torch.cuda.FloatTensor\n\ndef detect_image(img):\n # scale and pad image\n ratio = min(img_size/img.size[0], img_size/img.size[1])\n imw = round(img.size[0] * ratio)\n imh = round(img.size[1] * ratio)\n img_transforms = transforms.Compose([ transforms.Resize((imh, imw)),\n transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)),\n (128,128,128)),\n transforms.ToTensor(),\n ])\n # convert image to Tensor\n image_tensor = img_transforms(img).float()\n image_tensor = image_tensor.unsqueeze_(0)\n input_img = Variable(image_tensor.type(Tensor))\n # run inference on the model and get detections\n with torch.no_grad():\n detections = model(input_img)\n detections = utils.non_max_suppression(detections, 80, conf_thres, nms_thres)\n return detections[0]\n\n# videopath = 'C:/Users/md459/PycharmProjects/choiwb/BigData_Team_AI_Contest/CycleGAN/blackbox_day.mp4'\n\n# videopath = 'park3.mp4'\nvideopath = 'highway.mp4'\n\ncolors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255), (128, 0, 0), (0, 128, 0), (0, 0, 128), (128, 0, 128),\n (128, 128, 0), (0, 128, 128)]\n\nvid = cv2.VideoCapture(videopath)\n# vid = cv2.VideoCapture(0)\n\n# my smart phone real time tracking\n# vid = cv2.VideoCapture(\"https://192.168.43.1:8080/video\")\n# vid = cv2.VideoCapture('http://192.168.40.122:8080/video')\n\nmot_tracker = Sort()\n\ncv2.namedWindow('Stream', cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Stream', (800, 600))\n\n# saving video\nret, frame = vid.read()\nvw = frame.shape[1]\nvh = frame.shape[0]\nprint(\"Video size: (%d, %d)\" % (vw, vh))\n\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\noutvideo = cv2.VideoWriter(videopath.replace(\".mp4\", \"-det.mp4\"),fourcc,20.0,(vw,vh))\n\ndef make_line(shp1_x, shp1_y, shp2_x, shp2_y):\n return (int(shp1_x), int(shp1_y)), (int(shp2_x), int(shp2_y))\n\n# frame별 세로 줄\n# line_start, line_end = make_line(vw/2, 0, vw/2, vh)\n\n# frame별 가로 줄\nline_start, line_end = make_line(0, vh * 0.8, vw, vh * 0.8)\n\n# Return true if line segments AB and CD intersect\ndef intersect(A, B, C, D):\n return ccw(A, C, D) != ccw(B, C, D) and ccw(A, B, C) != ccw(A, B, D)\n\ndef ccw(A, B, C):\n return (C[1] - A[1]) * (B[0] - A[0]) > (B[1] - A[1]) * (C[0] - A[0])\n\ndef intersect_point(counter):\n # object별 기준 선 통과 좌표\n p0 = (int(x + (w - x) / 2), int(y + (h - y) / 2))\n p1 = (int(x2 + (w2 - x2) / 2), int(y2 + (h2 - y2) / 2))\n\n print('----------------------------------------------------')\n print('frame No: %d\\n' % (frames))\n print('object center point : ', p0, p1)\n print('----------------------------------------------------')\n\n if intersect(p0, p1, line_start, line_end):\n counter += 1\n\n return p0, p1, str(counter)\n\ndef intersect_count():\n # detect line (green)\n cv2.line(frame, line_start, line_end, (0, 0xFF, 0), 3)\n\n # draw counter (frame별 기준 선 통과 한 객체 count\n cv2.putText(frame, str(counter), (int(vw * 0.1), int(vh * 0.2)), cv2.FONT_HERSHEY_DUPLEX, 5.0,\n (0, 255, 255), 3)\n\ndef save_csv():\n # making real time data frame\n data = {'realtime': [realtime], 'frames': [frames],'detecting object': [cls],\n 'p0 counter point': [p0], 'p1 counter point': [p1], 'counter': [counter]}\n\n df = pd.DataFrame(data, columns=['realtime', 'frames', 'detecting object',\n 'p0 counter point', 'p1 counter point', 'counter'])\n\n test_df = df.append(df, ignore_index = True)\n test_df.to_csv('test_df.csv', sep=',', encoding='utf-8')\n\n return test_df\n\nframes = 0\nframe_count = 0\n\ndet_start = time.time()\n\nwhile (True):\n ret, frame = vid.read()\n if not ret:\n break\n\n frames += 1\n\n # frame 관련 2가지 중복 코드 (아래 코드와 중복 필요) BGR -> RGB\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n pilimg = Image.fromarray(frame)\n detections = detect_image(pilimg)\n\n # frame 관련 2가지 중복 코드 (아래 코드와 중복 필요) RGB -> BGR\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n img = np.array(pilimg)\n pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape))\n pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape))\n unpad_h = img_size - pad_y\n unpad_w = img_size - pad_x\n\n boxes = []\n confidences = []\n classIDs = []\n\n if detections is not None:\n\n tracked_objects = mot_tracker.update(detections.cpu())\n # tracked_objects = mot_tracker.update(detections.cuda())\n\n box = detections[0:4]\n # box = detections[0] * [np.array(vw), detections[1] * np.array(vh), detections[2] * np.array(vw),\n # detections[3] * np.array(vh)]\n\n # box = detections[0:4] * Tensor([vw, vh, vw, vh])\n\n # unique_labels = detections[:, -1].cpu().unique()\n unique_labels = detections[:, -1].cuda().unique()\n\n n_cls_preds = len(unique_labels)\n\n boxes = []\n indexIDs = []\n previous = memory.copy()\n memory = {}\n\n for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects:\n realtime = datetime.datetime.now()\n\n box_h = int(((y2 - y1) / unpad_h) * img.shape[0])\n box_w = int(((x2 - x1) / unpad_w) * img.shape[1])\n y1 = int(((y1 - pad_y // 2) / unpad_h) * img.shape[0])\n x1 = int(((x1 - pad_x // 2) / unpad_w) * img.shape[1])\n color = colors[int(obj_id) % len(colors)]\n\n cls = classes[int(cls_pred)]\n\n # all bounding box per 1 frame\n cv2.rectangle(frame, (x1, y1), (x1 + box_w, y1 + box_h), color, 4)\n # object label box\n # cv2.rectangle(frame, (x1, y1 - 35), (x1 + len(cls) * 19 + 80, y1), color, -1)\n cv2.rectangle(frame, (x1, y1 - 35), (x1 + len(cls) * 19 + 30, y1), color, -1)\n\n # object label name\n # cv2.putText(frame, cls + \"-\" + str(int(obj_id)), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1,\n # (255, 255, 255), 3)\n cv2.putText(frame, cls, (x1 + 15, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (255, 255, 255), 3)\n\n # Real Time per frame\n cv2.putText(frame, str(realtime), (int(vw * 0.5), int(vh * 0.1)), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (255, 255, 255), 3)\n\n print('----------------------------------------------------')\n print('frame No : %d\\n' % (frames))\n print(realtime, cls + \"-\" + str(int(obj_id)))\n print('----------------------------------------------------')\n print('bounding box location :%s\\n' % (tracked_objects[0:6]))\n print('----------------------------------------------------')\n\n ####################################################################################\n boxes.append([x1, y1, box_w, box_h])\n indexIDs.append(int(obj_id))\n memory[indexIDs[-1]] = boxes[-1]\n ####################################################################################\n\n if len(boxes) > 0:\n i = int(0)\n for box in boxes:\n # extract the bounding box coordinates\n (x, y) = (int(box[0]), int(box[1]))\n (w, h) = (int(box[2]), int(box[3]))\n\n if indexIDs[i] in previous:\n previous_box = previous[indexIDs[i]]\n (x2, y2) = (int(previous_box[0]), int(previous_box[1]))\n (w2, h2) = (int(previous_box[2]), int(previous_box[3]))\n\n ####################\n intersect_point(counter)\n intersect_count()\n ####################\n\n i += 1\n\n # saving from video to image per frame\n # cv2.imwrite('output/frame%d.jpg' % (frame_count), frame)\n # frame_count += 1\n\n cv2.imshow('Stream', frame)\n outvideo.write(frame)\n ch = 0xFF & cv2.waitKey(1)\n if ch == 27:\n break\n\ndet_end = time.time()\ndet_result = det_end - det_start\nprint('영상 추적 걸린 시간 : %.4f (초)' % (det_result))\n\ncv2.destroyAllWindows()\noutvideo.release()", "######################################################################\n######################################################################\n# Only Object Tracking code\n######################################################################\n######################################################################\n\nfrom models import *\nfrom utils import *\nimport os, sys, time, datetime, random\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport argparse\nimport cv2\nfrom sort import *\n\n# load weights and set defaults\nconfig_path = 'config/yolov3.cfg'\nweights_path = 'config/yolov3.weights'\nclass_path = 'config/coco.names'\n\nimg_size=416\nconf_thres=0.8\nnms_thres=0.4\n\ncounter = 0\nmemory = {}\n\n# load model and put into eval mode\nmodel = Darknet(config_path, img_size=img_size)\nmodel.load_weights(weights_path)\n# model.cuda()\nmodel.eval()\n\nclasses = utils.load_classes(class_path)\nprint(classes)\n\nTensor = torch.FloatTensor\n\ndef detect_image(img):\n # scale and pad image\n ratio = min(img_size/img.size[0], img_size/img.size[1])\n imw = round(img.size[0] * ratio)\n imh = round(img.size[1] * ratio)\n img_transforms = transforms.Compose([ transforms.Resize((imh, imw)),\n transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)),\n (128,128,128)),\n transforms.ToTensor(),\n ])\n # convert image to Tensor\n image_tensor = img_transforms(img).float()\n image_tensor = image_tensor.unsqueeze_(0)\n input_img = Variable(image_tensor.type(Tensor))\n # run inference on the model and get detections\n with torch.no_grad():\n detections = model(input_img)\n detections = utils.non_max_suppression(detections, 80, conf_thres, nms_thres)\n return detections[0]\n\nvideopath = 'C:/Users/wbchoi/PycharmProjects/wbchoi/Tensorflow_object_detection_API/blackbox_day.mp4'\n\ncolors=[(255,0,0),(0,255,0),(0,0,255),(255,0,255),(128,0,0),(0,128,0),(0,0,128),(128,0,128),(128,128,0),(0,128,128)]\n\nvid = cv2.VideoCapture(videopath)\n\n# my smart phone real time tracking\n# vid = cv2.VideoCapture(\"https://192.168.43.1:8080/video\")\n# vid = cv2.VideoCapture(\"httpx://192.168.40.122:8080/video\")\n\nmot_tracker = Sort()\n\ncv2.namedWindow('Stream',cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Stream', (800,600))\n\n# saving video\nret, frame = vid.read()\nvw = frame.shape[1]\nvh = frame.shape[0]\nprint(\"Video size\", vw, vh)\n\nline = [(0, int(vh/2)), (int(vw), int(vh/2))]\n\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\n# outvideo = cv2.VideoWriter(videopath.replace(\".mp4\", \"-det.mp4\"),fourcc,20.0,(vw,vh))\n\n# Return true if line segments AB and CD intersect\ndef intersect(A,B,C,D):\n\treturn ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)\n\ndef ccw(A,B,C):\n\treturn (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0])\n\nframes = 0\n\ndet_start = time.time()\n\nwhile(True):\n ret, frame = vid.read()\n if not ret:\n break\n\n frames += 1\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n pilimg = Image.fromarray(frame)\n detections = detect_image(pilimg)\n\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n img = np.array(pilimg)\n pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape))\n pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape))\n unpad_h = img_size - pad_y\n unpad_w = img_size - pad_x\n\n boxes = []\n confidences = []\n classIDs = []\n\n if detections is not None:\n\n tracked_objects = mot_tracker.update(detections.cpu())\n # tracked_objects = mot_tracker.update(detections.cuda())\n\n box = detections[0:4]\n # box = detections[0] * [np.array(vw), detections[1] * np.array(vh), detections[2] * np.array(vw),\n # detections[3] * np.array(vh)]\n\n # box = detections[0:4] * Tensor([vw, vh, vw, vh])\n\n unique_labels = detections[:, -1].cpu().unique()\n # unique_labels = detections[:, -1].cuda().unique()\n\n n_cls_preds = len(unique_labels)\n\n boxes = []\n indexIDs = []\n previous = memory.copy()\n memory = {}\n\n for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects:\n\n realtime = datetime.datetime.now()\n\n box_h = int(((y2 - y1) / unpad_h) * img.shape[0])\n box_w = int(((x2 - x1) / unpad_w) * img.shape[1])\n y1 = int(((y1 - pad_y // 2) / unpad_h) * img.shape[0])\n x1 = int(((x1 - pad_x // 2) / unpad_w) * img.shape[1])\n color = colors[int(obj_id) % len(colors)]\n\n cls = classes[int(cls_pred)]\n\n # all bounding box per 1 frame\n # (720, 1280, 3) shape\n cv2.rectangle(frame, (x1, y1), (x1 + box_w, y1 + box_h), color, 4)\n # object label box\n cv2.rectangle(frame, (x1, y1 - 35), (x1 + len(cls) * 19 + 80, y1), color, -1)\n # object label name\n cv2.putText(frame, cls + \"-\" + str(int(obj_id)), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (255, 255, 255), 3)\n\n print('----------------------------------------------------')\n print('frame No : %d\\n' % (frames))\n print(realtime, cls + \"-\" + str(int(obj_id)))\n print('----------------------------------------------------')\n print('bounding box location :%s\\n' % (tracked_objects[0:6]))\n print('----------------------------------------------------')\n\n cv2.imshow('Stream', frame)\n #outvideo.write(frame)\n ch = 0xFF & cv2.waitKey(1)\n if ch == 27:\n break\n\ndet_end = time.time()\ndet_result = det_end - det_start\nprint('영상 추적 걸린 시간 : %.4f (초)' %(det_result))\n\ncv2.destroyAllWindows()\n#outvideo.release()" ]
[ [ "numpy.array", "torch.no_grad", "pandas.DataFrame" ], [ "numpy.array", "torch.no_grad" ] ]
chomd90/snip
[ "04aa8ca76364c61c3f6013832827fa292402652b" ]
[ "train_utils.py" ]
[ "import torch\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\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 accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\ndef accuracy_list(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n \n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = torch.tensor(output).cuda().topk(max(topk))\n pred = pred.t()\n correct = pred.eq(target)\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res \n\ndef init_logfile(filename: str, text: str):\n f = open(filename, 'w')\n f.write(text+\"\\n\")\n f.close()\n\ndef log(filename: str, text: str):\n f = open(filename, 'a')\n f.write(text+\"\\n\")\n f.close()\n \n " ]
[ [ "torch.no_grad", "torch.tensor" ] ]
stevievb/s3dataviewer
[ "c96a57c03cfdc15e9808632c465db9f4c2b33bbe" ]
[ "bokeh-backend/s3DataViewerPlotServer/apps/image.py" ]
[ "from bokeh.application.handlers import FunctionHandler, DirectoryHandler\nfrom bokeh.application import Application\n\nimport numpy as np\nimport holoviews as hv\nimport boto3\nfrom PIL import Image\nimport holoviews.plotting.bokeh # important\nfrom bokeh.io import show, curdoc\nfrom bokeh.layouts import layout\nimport io\nfrom holoviews.operation.datashader import datashade\nfrom bokeh.models import Slider, Button\n\nfrom marshmallow import Schema, fields, INCLUDE\n\nrenderer = hv.renderer('bokeh').instance(mode='server')\n\n\nclass BokehImageAppArgsSchema(Schema):\n bucket = fields.List(fields.String())\n key = fields.List(fields.String())\n height = fields.List(fields.Integer())\n width = fields.List(fields.Integer())\n\n\n# Define valid function for FunctionHandler\n# when deploying as script, simply attach to curdoc\ndef modify_doc(doc):\n args = doc.session_context.request.arguments\n\n args_schema = BokehImageAppArgsSchema()\n loaded_args = args_schema.load(args, unknown=INCLUDE)\n\n bucket = loaded_args['bucket'][0]\n key = loaded_args['key'][0]\n\n s3 = boto3.resource('s3')\n bucket = s3.Bucket(bucket)\n object = bucket.Object(key)\n\n file_stream = io.BytesIO()\n object.download_fileobj(file_stream)\n pil_image = Image.open(file_stream)\n\n hv_img_plot = hv.Image(np.asarray(pil_image)).options(\n height=loaded_args['height'][0], width=loaded_args['width'][0])\n # Create HoloViews plot and attach the document\n hvplot = renderer.get_plot(hv_img_plot, doc)\n\n # Combine the holoviews plot and widgets in a layout\n plot = layout([\n [hvplot.state]], sizing_mode='fixed')\n\n doc.add_root(plot)\n return doc\n\n\nbokeh_image_app = Application(FunctionHandler(modify_doc))\n" ]
[ [ "numpy.asarray" ] ]
aluckyi/FASNet
[ "aefd3da73a7bc8aa1389b13b5a823fba5995ac3f" ]
[ "networks/fasnet.py" ]
[ "import torch.nn as nn\nimport torch\n\nimport torch.nn.functional as F\nfrom .module import MSFA\nfrom .enet import backbone_net\n\n\n# add MSFA + FSLoss\nclass FASNet(nn.Module):\n def __init__(self, num_classes=3):\n super(FASNet, self).__init__()\n\n self.backbone = backbone_net()\n self.msfa = MSFA(in_channels=416, mid_channels=64, out_channels=16)\n\n self.cls_conv = nn.Conv2d(16, num_classes, 1)\n\n def forward(self, inputs):\n # Initial block\n x0 = self.backbone.initial_block(inputs)\n\n # Stage 1 - Encoder\n stage1_input_size = x0.size()\n x, max_indices1_0 = self.backbone.downsample1_0(x0)\n x = self.backbone.regular1_1(x)\n x = self.backbone.regular1_2(x)\n x = self.backbone.regular1_3(x)\n x1 = self.backbone.regular1_4(x)\n\n # Stage 2 - Encoder\n stage2_input_size = x1.size()\n x, max_indices2_0 = self.backbone.downsample2_0(x1)\n x = self.backbone.regular2_1(x)\n x = self.backbone.dilated2_2(x)\n x = self.backbone.asymmetric2_3(x)\n x = self.backbone.dilated2_4(x)\n x = self.backbone.regular2_5(x)\n x = self.backbone.dilated2_6(x)\n x = self.backbone.asymmetric2_7(x)\n x2 = self.backbone.dilated2_8(x)\n\n # Stage 3 - Encoder\n x = self.backbone.regular3_0(x2)\n x = self.backbone.dilated3_1(x)\n x = self.backbone.asymmetric3_2(x)\n x = self.backbone.dilated3_3(x)\n x = self.backbone.regular3_4(x)\n x = self.backbone.dilated3_5(x)\n x = self.backbone.asymmetric3_6(x)\n x3 = self.backbone.dilated3_7(x)\n\n # Stage 4 - Decoder\n x = self.backbone.upsample4_0(x3, max_indices2_0, output_size=stage2_input_size)\n x = self.backbone.regular4_1(x)\n x4 = self.backbone.regular4_2(x)\n\n # Stage 5 - Decoder\n x = self.backbone.upsample5_0(x4, max_indices1_0, output_size=stage1_input_size)\n x5 = self.backbone.regular5_1(x)\n\n # feature fusion\n size = x5.size()[-2:]\n x_1 = F.interpolate(x1, size=size, mode='bilinear', align_corners=True)\n x_2 = F.interpolate(x2, size=size, mode='bilinear', align_corners=True)\n x_3 = F.interpolate(x3, size=size, mode='bilinear', align_corners=True)\n x_4 = F.interpolate(x4, size=size, mode='bilinear', align_corners=True)\n\n y = torch.cat([x0, x_1, x_2, x_3, x_4, x5], dim=1)\n y = self.msfa(y)\n\n x = self.cls_conv(x5+y)\n # # =============================================\n # import os\n # import numpy as np\n # import matplotlib.pyplot as plt\n # from utils import draw_features\n # feat = y.detach().cpu().numpy()\n # savename = os.path.join('./heatmap', 'heatmap_y.png')\n # draw_features(4, 4, feat, savename)\n # # =============================================\n\n pred = F.interpolate(x, size=inputs.size()[-2:], mode='bilinear', align_corners=True)\n\n return pred, y\n" ]
[ [ "torch.nn.Conv2d", "torch.nn.functional.interpolate", "torch.cat" ] ]
jinfagang/alfred
[ "adffe076ce4c64dbaf1533e1bd11fb46f30431d8" ]
[ "alfred/dl/evaluator/yolo_evaluator.py" ]
[ "import os\r\nimport json\r\nimport glob\r\nfrom alfred.utils.log import logger\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport cv2\r\nimport shutil\r\nfrom tqdm import tqdm\r\n\r\n\r\n__all__ = ['YoloEvaluator']\r\n\r\n\r\n\"\"\"\r\n\r\nParsing any dataset in Yolo format.\r\nYou can simply change classes names to yours.\r\n\"\"\"\r\n\r\nimg_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif',\r\n 'tiff', 'dng'] # acceptable image suffixes\r\n\r\n\r\nclass YoloEvaluator:\r\n\r\n def __init__(self,\r\n imgs_root,\r\n labels_root,\r\n infer_func,\r\n model=None,\r\n prep_func=None,\r\n posp_func=None,\r\n conf_thr=0.4,\r\n iou_thr=0.5):\r\n assert os.path.exists(imgs_root)\r\n assert os.path.exists(labels_root)\r\n\r\n self.infer_func = infer_func\r\n self.model_ = model\r\n self.prep_func = prep_func\r\n self.posp_func = posp_func\r\n\r\n self.conf_thr = conf_thr\r\n self.iou_thr = iou_thr\r\n\r\n self._data_root = imgs_root\r\n logger.info('data_root: {}'.format(self._data_root))\r\n\r\n self.img_files = []\r\n self.label_files = []\r\n self.load_combined_imgs_and_labels(imgs_root, labels_root)\r\n\r\n self.hold_vis = True\r\n logger.info(\r\n 'Press space to vis image, press q to skip and continue eval.')\r\n\r\n def load_combined_imgs_and_labels(self, imgs_root, labels_root):\r\n logger.info('labels root path: {}, img root: {}, pls check it they right or not.'.format(\r\n imgs_root, labels_root))\r\n self.label_files = glob.glob(os.path.join(labels_root, \"*.txt\"))\r\n for ext in img_formats:\r\n self.img_files.extend(\r\n glob.glob(os.path.join(imgs_root, '*.{}'.format(ext))))\r\n if len(self.img_files) != len(self.label_files):\r\n imgs_names = [os.path.basename(i).split('.')[0]\r\n for i in self.img_files]\r\n labels_names = [os.path.basename(i).split(\r\n '.')[0] for i in self.label_files]\r\n valid_files = [i for i in imgs_names if i in labels_names]\r\n logger.info('original imgs: {}, original labels: {}, valid num: {}'.format(\r\n len(self.img_files), len(self.label_files), len(valid_files)))\r\n # labels is more than images\r\n self.label_files = [os.path.join(\r\n labels_root, i + '.txt') for i in valid_files]\r\n self.img_files = [os.path.join(\r\n imgs_root, i + '.jpg') for i in valid_files]\r\n self.img_files = sorted(self.img_files)\r\n self.label_files = sorted(self.label_files)\r\n logger.info('img num: {}, label num: {}'.format(\r\n len(self.img_files), len(self.label_files)))\r\n logger.info(self.img_files[89])\r\n logger.info(self.label_files[89])\r\n logger.info('Please check if images and labels are paired properly.')\r\n\r\n def _load_yolo_boxes_and_labels(self, lb_file, ori_w, ori_h):\r\n with open(lb_file, 'r') as f:\r\n l = np.array([x.split() for x in f.read().strip(\r\n ).splitlines()], dtype=np.float32) # labels\r\n l = np.clip(l, 0, 1.)\r\n res_boxes = []\r\n res_labels = []\r\n if len(l):\r\n boxes = l[:, 1:]\r\n labels = l[:, 0]\r\n\r\n for i, b in enumerate(boxes):\r\n cx, cy, w, h = b\r\n cx *= ori_w\r\n cy *= ori_h\r\n w *= ori_w\r\n h *= ori_h\r\n x = cx - w/2\r\n y = cy - h/2\r\n if x < 0 or y < 0 or w <= 2 or h <= 2:\r\n continue\r\n res_boxes.append(np.array([x, y, x+w, y+h]).astype(np.int))\r\n res_labels.append(labels[i])\r\n return res_boxes, res_labels\r\n\r\n def exif_size(self, img):\r\n # Returns exif-corrected PIL size\r\n s = img.size # (width, height)\r\n try:\r\n rotation = dict(img._getexif().items())[orientation]\r\n if rotation == 6: # rotation 270\r\n s = (s[1], s[0])\r\n elif rotation == 8: # rotation 90\r\n s = (s[1], s[0])\r\n except:\r\n pass\r\n return s\r\n\r\n @staticmethod\r\n def compute_iou(rec1, rec2):\r\n \"\"\"\r\n computing IoU\r\n :param rec1: (x0, y0, x1, y1), which reflects\r\n (top, left, bottom, right)\r\n :param rec2: (x0, y0, x1, y1)\r\n :return: scala value of IoU\r\n \"\"\"\r\n # computing area of each rectangles\r\n S_rec1 = (rec1[3] - rec1[1]) * (rec1[2] - rec1[0])\r\n S_rec2 = (rec2[3] - rec2[1]) * (rec2[2] - rec2[0])\r\n\r\n # computing the sum_area\r\n sum_area = S_rec1 + S_rec2\r\n\r\n # find the each edge of intersect rectangle\r\n left_line = max(rec1[0], rec2[0])\r\n right_line = min(rec1[2], rec2[2])\r\n top_line = max(rec1[1], rec2[1])\r\n bottom_line = min(rec1[3], rec2[3])\r\n\r\n # judge if there is an intersect\r\n if left_line >= right_line or top_line >= bottom_line:\r\n return 0\r\n else:\r\n intersect = (right_line - left_line) * (bottom_line - top_line)\r\n return (intersect / (sum_area - intersect))*1.0\r\n\r\n def recall_precision(self, gt, pre, iou_thr=0.5):\r\n # recall\r\n recall_sum = len(gt)\r\n recall_cnt = 0\r\n precision_sum = len(pre)\r\n precision_cnt = 0\r\n for g_bbox in gt:\r\n for p_bbox in pre:\r\n iou_ = self.compute_iou(g_bbox, p_bbox)\r\n # print('iou_of_recall: ', iou_)\r\n if iou_ >= iou_thr:\r\n recall_cnt += 1\r\n break\r\n for p_bbox in pre:\r\n for g_bbox in gt:\r\n iou_ = self.compute_iou(g_bbox, p_bbox)\r\n # print('iou_of_precision: ', iou_)\r\n if iou_ >= iou_thr:\r\n precision_cnt += 1\r\n break\r\n\r\n if recall_cnt > recall_sum:\r\n print(\" ----------------------》》》 error recall\")\r\n if precision_cnt > precision_sum:\r\n print(\" ----------------------》》》 error precision\")\r\n return (recall_sum, recall_cnt, precision_sum, precision_cnt)\r\n\r\n def eval_precisely(self):\r\n recall_sum, recall_cnt, precision_sum, precision_cnt = 0., 0., 0., 0.\r\n mAPs = []\r\n mrecall = []\r\n pic_cnt = 0\r\n\r\n tbar = tqdm(self.img_files)\r\n for i, identity in enumerate(tbar):\r\n # load ground truth\r\n im = Image.open(identity)\r\n im.verify() # PIL verify\r\n shape = self.exif_size(im)\r\n img = cv2.imread(identity)\r\n w = shape[0]\r\n h = shape[1]\r\n\r\n annotation = self.label_files[i]\r\n bboxes, labels = self._load_yolo_boxes_and_labels(annotation, w, h)\r\n gt_list = bboxes\r\n\r\n # inference\r\n # inp = self.prep_func(identity)\r\n # out = self.model_(inp)\r\n # out = self.posp_func(out)\r\n out = self.infer_func(identity)\r\n\r\n for b in bboxes:\r\n x1, y1, x2, y2 = b\r\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2)\r\n\r\n pre_list = []\r\n for m_ in out:\r\n x1, y1, x2, y2, cls_id, conf = m_\r\n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\r\n if conf >= self.conf_thr:\r\n pre_list.append((x1, y1, x2, y2))\r\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)\r\n\r\n pic_cnt += 1\r\n eval_list = self.recall_precision(\r\n gt_list, pre_list, iou_thr=self.iou_thr)\r\n # logger.info(eval_list)\r\n\r\n recall_sum += eval_list[0]\r\n recall_cnt += eval_list[1]\r\n precision_sum += eval_list[2]\r\n precision_cnt += eval_list[3]\r\n # print('{} {} {} {}'.format(recall_sum, recall_cnt, precision_sum, precision_cnt))\r\n if (recall_sum > 0) and (precision_sum > 0):\r\n if eval_list[2] > 0:\r\n mAPs.append(eval_list[3]/eval_list[2])\r\n else:\r\n if eval_list[0] > 0:\r\n mAPs.append(0)\r\n if eval_list[0] > 0:\r\n mrecall.append(eval_list[1]/eval_list[0])\r\n # print(recall_cnt,recall_sum,precision_cnt,precision_sum)\r\n\r\n tbar.set_postfix(recall='{:.3f}'.format(recall_cnt/recall_sum), precision='{:.3f}'.format(\r\n precision_cnt/precision_sum), mAP='{:.3f}'.format(np.mean(mAPs)), refresh=True)\r\n\r\n if self.hold_vis:\r\n cv2.imshow('aa', img)\r\n if cv2.waitKey(0) & 0xFF == ord('q'):\r\n print('Pressed Q, continue eval without vis.')\r\n self.hold_vis = False\r\n cv2.destroyAllWindows()\r\n print(\"[\\n{:6d}] conf_thr: {:.2f}, iou_thr: {:.2f}, recall: {:.5f}, precision: {:.5f}, mrecall: {:.3f}, map: {:.3f}\".\r\n format(pic_cnt, self.conf_thr, self.iou_thr, recall_cnt/recall_sum, precision_cnt/precision_sum, np.mean(mrecall), np.mean(mAPs)))\r\n\r\n def eval(self):\r\n recall_sum, recall_cnt, precision_sum, precision_cnt = 0., 0., 0., 0.\r\n mAPs = []\r\n mrecall = []\r\n pic_cnt = 0\r\n\r\n for i, identity in enumerate(self.img_files):\r\n # load ground truth\r\n im = Image.open(identity)\r\n im.verify() # PIL verify\r\n shape = self.exif_size(im)\r\n w = shape[0]\r\n h = shape[1]\r\n\r\n annotation = self.label_files[i]\r\n bboxes, labels = self._load_yolo_boxes_and_labels(annotation, w, h)\r\n gt_list = bboxes\r\n\r\n # inference\r\n inp = self.prep_func(identity)\r\n out = self.model_(inp)\r\n out = self.posp_func(out)\r\n\r\n pre_list = []\r\n for m_ in out:\r\n x1, y1, x2, y2, conf = m_\r\n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\r\n if conf >= self.conf_thr:\r\n pre_list.append((y1, x1, y2, x2))\r\n\r\n pic_cnt += 1\r\n eval_list = self.recall_precision(\r\n gt_list, pre_list, iou_thr=self.iou_thr)\r\n\r\n recall_sum += eval_list[0]\r\n recall_cnt += eval_list[1]\r\n precision_sum += eval_list[2]\r\n precision_cnt += eval_list[3]\r\n if (recall_sum > 0) and (precision_sum > 0):\r\n if eval_list[2] > 0:\r\n mAPs.append(eval_list[3]/eval_list[2])\r\n else:\r\n if eval_list[0] > 0:\r\n mAPs.append(0)\r\n if eval_list[0] > 0:\r\n mrecall.append(eval_list[1]/eval_list[0])\r\n # print(recall_cnt,recall_sum,precision_cnt,precision_sum)\r\n print(\" {:6d}> -->>conf_thr :{:.2f} , iou_thr :{:.2f} , recall :{:.5f} , precision :{:.5f}, mrecall :{:.3f}, map :{:.3f}\".\r\n format(pic_cnt, self.conf_thr, self.iou_thr, recall_cnt/recall_sum, precision_cnt/precision_sum, np.mean(mrecall), np.mean(map)), end='\\r')\r\n print('all recall: {}, all precision: {}'.format(\r\n recall_sum, precision_sum))\r\n" ]
[ [ "numpy.array", "numpy.mean", "numpy.clip" ] ]
kl-31/batterycat
[ "c4956cb4a64fb3fc35df6ba193c9e40245410a05" ]
[ "helpers.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 25 05:28:51 2019\n\n@author: KCLIANG\nHelper functions for biophotobot.\n\"\"\"\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.externals import joblib\nimport pandas as pd\nimport numpy as np\nfrom unidecode import unidecode\nimport string\nimport json\nfrom os.path import isfile,splitext,isdir,dirname\nfrom os import environ,remove,makedirs\nimport tweepy\nfrom time import sleep\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport re\nimport datetime\nimport requests\nfrom bs4 import BeautifulSoup\nimport urllib\nfrom subprocess import call\nfrom shutil import rmtree\nimport patoolib\nimport glob\nfrom random import choice, randint\nfrom PyPDF2 import PdfFileReader\nimport fitz\nimport html2text\nfrom fuzzywuzzy import fuzz\n#import bitly_api\n#import sys\n\nscopes = ['https://spreadsheets.google.com/feeds',\n\t 'https://www.googleapis.com/auth/drive']\nkeyfile_dict = {\n 'auth_provider_x509_cert_url': environ['GSPREAD_AUTH_PROVIDER'],\n 'auth_uri': environ['GSPREAD_AUTH_URI'],\n 'client_email': environ['GSPREAD_CLIENT_EMAIL'],\n 'client_id': environ['GSPREAD_CLIENT_ID'],\n 'client_x509_cert_url': environ['GSPREAD_CLIENT_X509'],\n 'private_key': environ['GSPREAD_PRIVATE_KEY'].replace('\\\\n', '\\n'),\n 'private_key_id': environ['GSPREAD_PRIVATE_KEY_ID'],\n 'project_id': environ['GSPREAD_PROJECT_ID'],\n 'token_uri': environ['GSPREAD_TOKEN_URI'],\n 'type': environ['GSPREAD_TYPE']\n}\n\n\ndef get_titles_db():\n\t#print(keyfile_dict)\n\tcreds = ServiceAccountCredentials.from_json_keyfile_dict(\n keyfile_dict=keyfile_dict, scopes=scopes)\n\t#creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)\n\tclient = gspread.authorize(creds)\n\tsh = client.open_by_key('1yKc23vjZ9AGoUaMP1ebo9q31zVj5HEq0vUq2_C5shBs')\n\tworksheet = sh.sheet1\n\ttitles_list = worksheet.col_values(1)\t\n\ttitles_list = [s.strip().lower() for s in titles_list]\n\treturn titles_list\n\ndef write_to_db(row):\n\tcreds = ServiceAccountCredentials.from_json_keyfile_dict(\n keyfile_dict=keyfile_dict, scopes=scopes)\n\t#creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)\n\tclient = gspread.authorize(creds)\n\tsh = client.open_by_key('1yKc23vjZ9AGoUaMP1ebo9q31zVj5HEq0vUq2_C5shBs')\n\tworksheet = sh.sheet1\n\tworksheet.insert_row(row+[str(datetime.date.today())],1)\n\tsleep(1) # google api 60 write requests per 60 sec\n\treturn\n\n\ndef normalize_text(s):\n\ts=''.join([i for i in s if not i.isdigit()]) # remove numbers\n\ts = s.replace('-',' ')\n\ts = s.replace('/',' ')\n\ts = s.replace('μ','u')\n\ts = unidecode(str(s))\n\ts=s.translate(s.maketrans('', '', string.punctuation)) # remove punctuation\n\ts = s.lower() # make lowercase\n\ts = s.replace(' ',' ') # remove double spaces\n\treturn s\n\ndef strip_html(s):\n\t\t#if s[:3]=='<p>' and not s[-4:]=='</p>': # differentiate between Nature and Science abstract formats\n\t\tsoup = BeautifulSoup(s,'lxml')\n\t\t#soup.p.decompose()\n\t\ts = soup.get_text() \n\t\treturn s\n\ndef pull_handles_from_twitter(accounts):\n\t# twitter followers\n\tauth = tweepy.OAuthHandler(environ['TWITTER_CONSUMER_KEY'], environ['TWITTER_CONSUMER_SECRET'])\n\tauth.set_access_token(environ['TWITTER_ACCESS_TOKEN'], environ['TWITTER_ACCESS_SECRET'])\n\tapi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True,retry_count=10, retry_delay=5, retry_errors=set([503])\t)\n\tids = []\n\tnames = []\n\thandles = []\n\t#accounts = ['rita_strack','joachimgoedhart']\n\tfor account in accounts:\n\t\tfor page in tweepy.Cursor(api.followers_ids, screen_name=account).pages():\n\t\t\tids.extend(page)\n\t\t\tsleep(5)\n\tfor page in tweepy.Cursor(api.friends_ids, screen_name='biophotonicat').pages():\n\t\tids.extend(page)\n\t\tsleep(5)\t\t\n\t\t\t\n\tids = list(set(ids)) # dedupe\n\t#print(len(ids))\n\tfor chunk_i in range(0,len(ids),100):\n\t\tusers_obj = api.lookup_users(ids[chunk_i:chunk_i+100])\n\t\tnames.extend([unidecode(user.name) for user in users_obj])\n\t\thandles.extend(['@'+user.screen_name for user in users_obj])\n\t\tsleep(5)\n\tauthor_handles_data = dict(zip(names,handles))\t\n\treturn author_handles_data\n\t\ndef get_author_handles(raw_author_list,journal,author_handles_data):\n\n\t\n\thandles_all = ''\n\tif journal == 'Biorxiv Biophys/Bioeng' or journal == 'Science' or journal == 'Science Advances':\n\t\t#paper_id = urllib.parse.urlparse(raw_author_list).path.split('/')[-1]\n\t\t#paper_path = 'https://www.biorxiv.org/content/10.1101/' + paper_id + '.full'\n\t\tsoup = BeautifulSoup(urllib.request.urlopen(raw_author_list).read(),'lxml')\n\t\tauthors_raw = soup.find_all('meta',{'class':'DC.Contributor'})\t\n\t\tauthor_list = [x['content'] for x in authors_raw]\n\t\t\n\t\t#raw_author_list_split=raw_author_list[0]['name'].split(', ')\n\t\t#author_list = []\n#\t\tfor i in range(0,len(raw_author_list_split),2):\n#\t\t\tauthor_list.append(raw_author_list_split[i+1].replace('.','')+' '+raw_author_list_split[i])\t\n#\t\t# names are given in initials and last name. need to change format of twitter names.\n#\t\tfor key in author_handles_data.keys():\n#\t\t\tlastname = str(key).split(' ')[-1]\n#\t\t\tif len(str(key).split(' ')) > 1:\n#\t\t\t\tinitials = ' '.join([s[0] for s in str(key).split(' ')[:-1]])\n#\t\t\telse:\n#\t\t\t\tinitials = ''\n#\t\t\tname = initials + ' ' + lastname\n#\t\t\tauthor_handles_data[name] = author_handles_data.pop(key)\n\telif journal == \"Arxiv Optics\":\n\t\th = html2text.HTML2Text()\n\t\th.ignore_links = True\t\n\t\tauthor_list = h.handle(raw_author_list[0]['name'])\n\t\tauthor_list = (author_list).replace('\\n',' ').split(', ')\n\telif journal == \"Journal of Biophotonics\":\n\t\tif 'name' in raw_author_list[0]:\n\t\t\tauthor_list=raw_author_list[0]['name'].replace('\\n','').split(', ')\n\t\telse:\n\t\t\tauthor_list = []\n\telif journal == \"PNAS Engineering\":\n\t\tauthor_list=raw_author_list[0]['name'].split(', ')\n\telse: \n\t\t#journal == 'Nature Photonics' or journal == 'Nature Methods' or journal == 'Nature' or journal == 'Nature Communications' or journal == \"Light: Science and Applications\" or journal == 'Nature BME':\n\t\tauthor_list = [s['name'] for s in raw_author_list]\n\n\tfor handle_query in author_handles_data.keys():\n\t\tfor author in author_list:\n\t\t\tif fuzz.ratio(normalize_text(author),normalize_text(handle_query)) > 90:\n\t\t\t\thandles_all = handles_all + author_handles_data[handle_query] + ' '\n\t\t\t\t#print(author+' matched with ' +handle_query)\n\t\t\t\tbreak\n\treturn handles_all\n\t\ndef scrape_image(raw, journal):\n\tif raw == '':\n\t\treturn False\n\t\n\tif isdir('./data/'):\n\t\trmtree('./data/')\n\t\t\n\tif journal == 'Journal of The Electrochemical Society':\n\t\tmakedirs('./data/',exist_ok=True)\n#\t\traw=raw.replace('/cgi','')\n#\t\traw=raw.replace('/short','')\n#\t\traw=raw.replace('?rss=1','.figures-only')\n\t\t#soup = BeautifulSoup(urllib.request.urlopen(raw).read(),'lxml')\n\t\theaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'}\n\t\tsoup = BeautifulSoup(requests.get(raw,headers=headers).text,'lxml') # 17-7-2020 blocks bot. haven't figured it out yet\n\t\tlinks_raw = soup.find_all('a',{'class':'btn btn-primary fig-dwnld-hi-img'})\t\t\n\t\t#links=[dirname(raw)+'/'+x['href'].replace('expansion.html','large.jpg') for x in links_raw]\n\t\tif len(links)>0:\n\t\t\tpic_raw = choice(links)\n\t\telse:\n\t\t\treturn False\n\t\t#this section is required for JPS and probably others\n\t\topener = urllib.request.build_opener()\n\t\topener.addheaders = [('User-agent', 'Mozilla/5.0')]\n\t\turllib.request.install_opener(opener)\t\n\t\turllib.request.urlretrieve(pic_raw,'./data/pic_raw'+'.jpg')\n\t\tcall(['convert','-density','300','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off','./data/pic_raw.jpg','./data/tweet_pic.png'])\n\t\t\n\t\t#print(raw)\n#\t\tmakedirs('./data/',exist_ok=True)\n#\t\tsoup = BeautifulSoup(raw,'lxml')\n#\t\tif len(soup.find_all('img', src=True))==0:\n#\t\t\treturn False\n#\t\tlink = soup.find_all('img', src=True)[0]['src']\n#\t\textension = splitext(urllib.parse.urlparse(link).path)[-1]\n#\t\turllib.request.urlretrieve(link,'./data/tweet_pic'+extension)\n#\t\tcall(['convert','-density','300','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off','./data/tweet_pic'+extension,'./data/tweet_pic.png'])\n\n\telif journal in ['Journal of Power Sources','Electrochimica Acta','Journal of Electroanalytical Chemistry','Energy Storage Materials','Advanced Materials',\n\t\t\t\t 'Advanced Energy Materials','ACS Energy Letters','Batteries & Supercaps','Nano Energy','Chemistry of Materials',\n\t\t\t\t 'Small','Advanced Functional Materials','ACS Applied Materials','ACS Nano','ACS Central Science','Nano Letters']:\n\t\tmakedirs('./data/',exist_ok=True)\n\t\tsoup = BeautifulSoup(raw,'lxml')\n\t\tlinks_raw = soup.find_all('img')\t\t\n\t\tlinks = [x['src'] for x in links_raw]\n\t\tif len(links) == 0:\n\t\t\treturn False\n\t\telse:\n\t\t\tpic_raw = choice(links)\n\t\t\n\t\t\t#this section is required for JPS and probably others\n\t\t\topener = urllib.request.build_opener()\n\t\t\topener.addheaders = [('User-agent', 'Mozilla/5.0')]\n\t\t\turllib.request.install_opener(opener)\t\t\n\t\t\t\n\t\t\turllib.request.urlretrieve(pic_raw,'./data/pic_raw'+'.jpg')\n\t\t\tcall(['convert','-density','300','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off','./data/pic_raw.jpg','./data/tweet_pic.png'])\n\n\telif journal in ['Energy & Environment Science','JMCA','Materials Horizons']:\n\t\tmakedirs('./data/',exist_ok=True)\n\t\tif 'GA?' in raw.summary:\n\t\t\tprint('EES: graphical abstract available')\n\t\t\tsoup = BeautifulSoup(raw.summary,'lxml')\n\t\t\tlinks_raw = soup.find_all('img')\n\t\t\tfor link in links_raw:\n\t\t\t\tif 'GA?' in link['src']:\n\t\t\t\t\tpic_raw = 'http://pubs.rsc.org'+link['src']\n\t\telse:\n\t\t\tprint('EES: graphical abstract unavailable, trying to pull pdf')\n\t\t\tlink = raw.title_detail.base.lower()\n\t\t\tlink = link.replace('articlelanding','articlepdf')\n\t\t\ttry:\n\t\t\t\t#this section is required for JPS and probably others\n\t\t\t\topener = urllib.request.build_opener()\n\t\t\t\topener.addheaders = [('User-agent', 'Mozilla/5.0')]\n\t\t\t\turllib.request.install_opener(opener)\t\n\t\t\t\turllib.request.urlretrieve(link,'./data/paper.pdf')\n\t\t\t\tdoc = fitz.open('./data/paper.pdf')\n\t\t\t\timg_pgs = []\n\t\t\t\tfor i in range(1,len(doc)):\n\t\t\t\t\tif len(doc.getPageImageList(i)) > 0:\n\t\t\t\t\t\timg_pgs.append(str(i)) # pages with images\n\t\t\t\tif len(img_pgs) > 0:\n\t\t\t\t\tpg_choice = choice(img_pgs)\n\t\t\t\t\tcall(['convert','-density','150','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off','./data/paper.pdf['+ pg_choice+']','./data/tweet_pic.png'])\n\t\t\t\t\tprint('Page %s saved as image.' % pg_choice)\n\t\t\t\telse:\n\t\t\t\t\treturn False\t\t\t\t\n\t\t\t\t\n\t\t\texcept PermissionError or FileNotFoundError:\n\t\t\t\tprint('pdf pull denied, sorry no image')\n\t\t\t\treturn False\n\n\telif journal == \"Joule\":\n\t\tmakedirs('./data/',exist_ok=True)\n\t\t#paper_id = urllib.parse.urlparse(raw).path.split('/')[-1]\n\t\t#paper_path = 'https://www.biorxiv.org/content/10.1101/' + paper_id + '.full'\n\t\topener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor()) # site requires cookie processing\n\t\tsoup = BeautifulSoup(opener.open(raw).read(),'lxml')\n\t\tlinks_raw = soup.find_all('a',{'class':'download-links__download-Hi-res'})\n\t\tif len(links_raw) == 0:\n\t\t\treturn False\n\t\telse:\n\t\t\tlinks = []\n\t\t\tfor link in links_raw:\n\t\t\t\tlinks.append('http://'+link['href'][2:])\n\t\t\tpic_raw = choice(links)\n\t\t\turllib.request.urlretrieve(pic_raw,'./data/pic_raw'+'.jpg')\n\t\t\tcall(['convert','-density','300','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off','./data/pic_raw.jpg','./data/tweet_pic.png'])\n\n\t\t\n\telif journal == \"Arxiv Optics\":\n\t\tmakedirs('./data/',exist_ok=True)\n\t\turllib.request.urlretrieve(raw.replace('abs','e-print'),'source')\n\t\tif isdir('./data/'):\n\t\t\trmtree('./data/')\n\t\tmakedirs('./data/',exist_ok=True)\n\t\ttry:\t\n\t\t\tpatoolib.extract_archive(\"source\", outdir=\"./data/\")\n\t\texcept:\n\t\t\tprint('Arxiv: eprint not a zip file, so probably PDF.')\n\t\t\tdoc = fitz.open('source')\n\t\t\timg_pgs = []\n\t\t\tfor i in range(len(doc)):\n\t\t\t\tif len(doc.getPageImageList(i)) > 0:\n\t\t\t\t\timg_pgs.append(str(i)) # pages with images\n\t\t\tif len(img_pgs) > 0:\n\t\t\t\tpg_choice = choice(img_pgs)\n\t\t\t\tcall(['convert','-density','150','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off','./source['+ pg_choice+']','./data/tweet_pic.png'])\n\t\t\t\tprint('Page %s saved as image.' % pg_choice)\n\t\t\telse:\n\t\t\t\treturn False\n\t\t\t\n\t\t\t#return False\t\n\t#\tif glob.glob('./data/' + '**/*.tex', recursive=True) !=[]:\n\t\tfiles = glob.glob('./data/' + '**/*.png', recursive=True)\n\t\tif files != []:\n\t\t\tpicraw = choice(files)\n\t\t\tcall(['convert','-density','300','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off', picraw+'[0]','./data/tweet_pic.png'])\n\t\t\treturn True\n\t\telse:\n\t\t\totherfiles = glob.glob('./data/' + '**/*.pdf', recursive=True) + glob.glob('./data/' + '**/*.eps', recursive=True) + glob.glob('./data/' + '**/*.ps', recursive=True)\n\t\t\tif otherfiles != []:\n\t\t\t\tpicraw = choice(otherfiles)\n\t\t\t\tcall(['convert','-density','300','-define', 'trim:percent-background=2%','-trim','+repage','-background', 'white', '-alpha', 'remove', '-alpha', 'off', picraw+'[0]','./data/tweet_pic.png'])\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\t\t\n\t\n\tif isfile('./data/tweet_pic.png'):\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef compute_proba(titles):\n\tvectorizer = HashingVectorizer(ngram_range=(1, 3))\n\t\n\ttitles = pd.DataFrame(titles,columns=['title','link','journal_name','abstract'])\n\ttitles['abstract'] = [re.sub(r'^(.*?)<br\\/>','',str(s)) for s in titles['abstract']] # remove all text up to and including <br\\>\n\ttitles['title'] = [re.sub(r'\\[[^\\[\\]]*\\]','',str(s)).strip() for s in titles['title']] # remove all text within [] brackets\n\ttitles['abstract'] = [re.sub(r'\\[[^\\[\\]]*\\]','',str(s)) for s in titles['abstract']] # remove all text within [] brackets\n\ttitles['abstract'] = [strip_html(s) for s in titles['abstract']]\n\ttitles['text'] = [normalize_text(re.sub(r'\\([^()]*\\)', '', str(s))) for s in titles['title']+' '+titles['abstract']] \n\tX_test = vectorizer.fit_transform(titles['text'])\n\tclf = joblib.load('new_trained_model.pkl')\n\t\n\tpred = clf.predict_proba(X_test)\n\t#arr = np.empty((np.size(titles,0),4),dtype=object)\n\tarr = [None] * 5\n\tarr[0] = titles['title'][0]\n\tarr[1] = titles['link'][0]\n\tarr[2] = titles['journal_name'][0]\n\tarr[3] = titles['abstract'][0]\n\tarr[4] = float(pred[:,1])\n\treturn arr\n\t\n\ndef tweet_post(line,image_flag):\n\tauth = tweepy.OAuthHandler(environ['TWITTER_CONSUMER_KEY'], environ['TWITTER_CONSUMER_SECRET'])\n\tauth.set_access_token(environ['TWITTER_ACCESS_TOKEN'], environ['TWITTER_ACCESS_SECRET'])\n\tapi = tweepy.API(auth,retry_count=10, retry_delay=5, retry_errors=set([503]))\t\n\ttry:\n\t\tif image_flag == False:\n\t\t\tapi.update_status(line)\n\t\t\tsleep(30*60) \n\t\t\treturn True\n\t\telse:\n\t\t\ttry:\n\t\t\t\tapi.update_with_media('./data/tweet_pic.png',line)\n\t\t\texcept:\n\t\t\t\tapi.update_status(line)\n\t\t\tsleep(30*60) \n\t\t\treturn True\n\texcept tweepy.TweepError as e:\n\t\tprint(e.args[0][0]['message'])\n\t\treturn False\n\n#def shorten_link(link):\n#\tb = bitly_api.Connection(API_USER, API_KEY)\n#\tresponse = b.shorten(link)\n#\treturn response['url']\n\t\t\ndef retweet_old(number):\n\tauth = tweepy.OAuthHandler(environ['TWITTER_CONSUMER_KEY'], environ['TWITTER_CONSUMER_SECRET'])\n\tauth.set_access_token(environ['TWITTER_ACCESS_TOKEN'], environ['TWITTER_ACCESS_SECRET'])\n\tapi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True,retry_count=10, retry_delay=15, retry_errors=set([503]))\n\ttweets = []\n\t# retweeting tweets\n\ttweets = api.user_timeline(count = 400)\n\t\n\tfor i in range(number):\n\t\t#while 1:\n\t\ttweet = choice(tweets)\n\t\t#\tif tweet.retweeted == False:\n\t\t#\t\tbreak\n\t\ttry:\n\t\t\tapi.retweet(tweet.id)\n\t\t\tsleep(30*60)\t\n\t\texcept:\n\t\t\tpass\n\treturn \t\n\t" ]
[ [ "sklearn.feature_extraction.text.HashingVectorizer", "sklearn.externals.joblib.load", "pandas.DataFrame" ] ]
IsnainiNurul/backup_ta
[ "4dea359aef8277b9ccbe0938a2a97f698fa34b2d" ]
[ "public/predict.py" ]
[ "import pickle\nimport pandas as pd\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import punkt\nfrom flask import Flask\nfrom nltk.corpus.reader import wordnet\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport sys\n\n\npath_models = \"C:/Users/asus-pc/Documents/PBA/Tugas Akhir/04. Model Training/Models/\"\n\n# SVM\npath_svm = path_models + 'best_lrc.pickle'\nwith open(path_svm, 'rb') as data:\n svc_model = pickle.load(data)\n\npath_tfidf = \"C:/Users/asus-pc/Documents/PBA/Tugas Akhir/03. Feature Engineering/Pickles_title/tfidf.pickle\"\nwith open(path_tfidf, 'rb') as data:\n tfidf = pickle.load(data)\n\nlabel_codes = {\n 'notification of information': 0,\n 'donation': 1,\n 'criticisms': 2,\n 'hoax': 3,\n}\n\npunctuation_signs = list(\"?:!.,;\")\nSTOPWORDS= stopwords.words('Indonesian')\nSTOPWORDS.extend(['covid','covid-19','covid-19,','korona','2020','corona', 'corona,','2021','0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','ribu','juta','-'])\nstop_words = list(STOPWORDS) #membuang kata yang tidak digunakan\ndef create_features_from_text(text):\n \n # Dataframe creation\n lemmatized_text_list = []\n df = pd.DataFrame(columns=['title'])\n df.loc[0] = text\n df['title_parsed_1'] = df['title'].str.replace(\"\\r\", \" \")\n df['title_parsed_1'] = df['title_parsed_1'].str.replace(\"\\n\", \" \")\n df['title_parsed_1'] = df['title_parsed_1'].str.replace(\" \", \" \")\n df['title_parsed_1'] = df['title_parsed_1'].str.replace('\"', '')\n df['title_parsed_2'] = df['title_parsed_1'].str.lower()\n df['title_parsed_3'] = df['title_parsed_2']\n for punct_sign in punctuation_signs:\n df['title_parsed_3'] = df['title_parsed_3'].str.replace(punct_sign, '')\n df['title_parsed_4'] = df['title_parsed_3'].str.replace(\"'s\", \"\")\n wordnet_lemmatizer = WordNetLemmatizer()\n lemmatized_list = []\n text = df.loc[0]['title_parsed_4']\n text_words = text.split(\" \")\n for word in text_words:\n lemmatized_list.append(wordnet_lemmatizer.lemmatize(word, pos=\"v\"))\n lemmatized_text = \" \".join(lemmatized_list) \n lemmatized_text_list.append(lemmatized_text)\n df['title_parsed_5'] = lemmatized_text_list\n df['title_parsed_6'] = df['title_parsed_5']\n for stop_word in stop_words:\n regex_stopword = r\"\\b\" + stop_word + r\"\\b\"\n df['title_parsed_6'] = df['title_parsed_6'].str.replace(regex_stopword, '')\n df = df.rename(columns={'title_parsed_6': 'title_parsed'})\n df = df['title_parsed']\n #df = df.rename(columns={'title_parsed_6': 'title_parsed'})\n\n # TF-IDF\n features = tfidf.transform(df).toarray()\n \n return features\n\ndef get_category_name(category_id):\n for category, id_ in label_codes.items(): \n if id_ == category_id:\n return category\n\ndef predict_from_text(text):\n \n # Predict using the input model\n prediction_svc = svc_model.predict(create_features_from_text(text))[0]\n prediction_svc_proba = svc_model.predict_proba(create_features_from_text(text))[0]\n \n # Return result\n category_svc = get_category_name(prediction_svc)\n \n return category_svc,prediction_svc_proba.max()*100\n\ntext=\"\"\nfor x in range(1,len(sys.argv)):\n if(x>1):\n text=text+\" \"\n text = text+sys.argv[x]\n\ntes1,tes2=predict_from_text(text)\nprint(tes1,tes2)" ]
[ [ "pandas.DataFrame" ] ]
tensorflow/transform
[ "f4dd0395fddc0bfdb4912c4cf871e494e6a3d0a6" ]
[ "tensorflow_transform/analyzer_nodes.py" ]
[ "# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Nodes that define analyzers.\n\n`OperationNode`s are objects that describe how to perform a full pass analysis\nover some input tensors. They are described by an `OperationDef`. This module\ncontains the `OperationDef` subclasses that define specific operations such as\ncomputing a mean or vocabulary. It also contains a special `OperationDef`,\n`ExtractTensors` which represents the operation of extracting the values of a\ntuple of `Tensor`s into a `PCollection`.\n\"\"\"\n\nimport abc\nimport json\nimport os\nimport struct\nfrom typing import Optional, Type\nimport uuid\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow_transform import common_types\nfrom tensorflow_transform import nodes\nfrom tensorflow_transform import tf2_utils\nfrom tensorflow_transform import tf_utils\nfrom tensorflow_transform.graph_context import TFGraphContext\n# TODO(https://issues.apache.org/jira/browse/SPARK-22674): Switch to\n# `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is\n# resolved.\nfrom tfx_bsl.types import tfx_namedtuple\n\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.framework import func_graph\nfrom tensorflow.python.framework import ops\n# pylint: disable=g-enable-tensorflow-import\n\n# Key for graph collection containing `TensorSink` objects representing TFT\n# analyzers.\nTENSOR_REPLACEMENTS = 'tft_tensor_replacements'\n# Key for graph collection containing `TensorSink` objects representing TFT\n# analyzers irrespective of whether they have been evaluated or not.\nALL_REPLACEMENTS = 'tft_all_replacements'\n\n\ndef sanitize_label(label: str) -> str:\n return label.replace('/', '#')\n\n\ndef _make_label(cls: Type[nodes.OperationDef],\n label: Optional[str] = None) -> str:\n if label is None:\n scope = tf.compat.v1.get_default_graph().get_name_scope()\n label = '{}[{}]'.format(cls.__name__, scope)\n return sanitize_label(label)\n\n\nclass TensorInfo(\n tfx_namedtuple.namedtuple('TensorInfo',\n ['dtype', 'shape', 'temporary_asset_value'])):\n \"\"\"A container for attributes of output tensors from analyzers.\n\n Fields:\n dtype: The TensorFlow dtype.\n shape: The shape of the tensor.\n temporary_asset_value: A temporary value to write to an asset file while\n tracing the TF graph.\n \"\"\"\n\n def __new__(cls, dtype, shape, temporary_asset_value):\n if not isinstance(dtype, tf.DType):\n raise TypeError('dtype must be a TensorFlow dtype, got {}'.format(dtype))\n if temporary_asset_value is not None and not isinstance(\n temporary_asset_value, bytes):\n raise TypeError(\n 'temporary_asset_value should be bytes or None, got {}'.format(\n temporary_asset_value))\n return super(TensorInfo, cls).__new__(\n cls,\n dtype=dtype,\n shape=shape,\n temporary_asset_value=temporary_asset_value)\n\n\nclass TensorSource(\n tfx_namedtuple.namedtuple('TensorSource', ['tensors', 'label']),\n nodes.OperationDef):\n \"\"\"An `OperationDef` that defines extracting a tuple of tensor values.\n\n This `OperationDef` defines an operation that extracts the values of the given\n tensors into a PCollection of tuples of values. It is used as a source for\n analyzers, which further transform\n\n This OperationDef accepts zero inputs and return a single output representing\n the PCollection of tuples of values. It will be converted in\n tensorflow_transform.beam.analysis_graph_builder.build to an operation that\n extracts the tensors for a dictionary of tensors, after running a beam.ParDo\n to produce tensor values by running the graph on its inputs.\n\n Fields:\n tensors: The tensors whose values should be extracted.\n label: A unique label for this operation.\n \"\"\"\n\n def __new__(cls, tensors):\n for tensor in tensors:\n if not isinstance(tensor, tf.Tensor):\n raise TypeError('tensor must be a Tensor, got {} of type {}'.format(\n tensor, type(tensor)))\n return super(TensorSource, cls).__new__(\n cls, tensors=tensors, label=_make_label(cls))\n\n\ndef get_input_tensors_value_nodes(tensor_inputs):\n return nodes.apply_operation(TensorSource, tensors=tensor_inputs)\n\n\nTensorSink = tfx_namedtuple.namedtuple(\n 'TensorSink', ['tensor', 'future', 'is_asset_filepath'])\n\n\ndef _bind_future_as_tensor_v1(future: nodes.ValueNode,\n tensor_info: TensorInfo,\n name: Optional[str] = None) -> tf.Tensor:\n \"\"\"Bind a future value as a tensor to a TF1 graph.\"\"\"\n result = tf.compat.v1.placeholder(tensor_info.dtype, tensor_info.shape, name)\n is_asset_filepath = tensor_info.temporary_asset_value is not None\n tf.compat.v1.add_to_collection(TENSOR_REPLACEMENTS,\n TensorSink(result, future, is_asset_filepath))\n return result\n\n\n_TemporaryAnalyzerOutputWrapper = tfx_namedtuple.namedtuple(\n '_TemporaryAnalyzerOutputWrapper', ['eager_asset_path', 'graph_tensor'])\n\n\ndef _get_temporary_analyzer_output(\n temp_dir: str,\n tensor_info: TensorInfo,\n name: Optional[str] = None) -> _TemporaryAnalyzerOutputWrapper:\n \"\"\"Create a temporary graph tensor using attributes in `tensor_info`.\n\n Args:\n temp_dir: Path to a directory to write out any temporary asset files to.\n tensor_info: A `TensorInfo` object containing attributes to create the graph\n tensor.\n name: A string (or None). The created graph tensor uses this name.\n\n Returns:\n A named tuple `_TemporaryAnalyzerOutputWrapper` with:\n eager_asset_path: If the analyzer output is an asset file, an eager tensor\n pointing to the file path. Else, None.\n graph_tensor: The graph tensor representing the analyzer output.\n \"\"\"\n asset = None\n with tf.name_scope('temporary_analyzer_output'):\n is_asset_filepath = tensor_info.temporary_asset_value is not None\n if is_asset_filepath:\n # Placeholders cannot be used for assets, if this graph will be serialized\n # to a SavedModel, as they will be initialized with the init op. If a\n # `temp_dir` is provided, it is assumed that this graph will be\n # serialized and a temporary asset file is written out . Else, a\n # placeholder is returned.\n # TODO(b/164921571) Support temporary files in tfrecord format.\n # TODO(b/149997088): Reduce number of temporary files written out.\n if temp_dir:\n with tf.init_scope():\n # TODO(b/170111921): This temporary file should have a unique name to\n # avoid namespace collisions between temporary files that contain data\n # of different dtypes.\n temporary_asset_filepath = os.path.join(temp_dir, uuid.uuid4().hex)\n with tf.io.gfile.GFile(temporary_asset_filepath, 'w') as f:\n f.write(tensor_info.temporary_asset_value)\n asset = tf.constant(temporary_asset_filepath)\n graph_tensor = tf.constant(\n temporary_asset_filepath,\n dtype=tensor_info.dtype,\n shape=tensor_info.shape,\n name=name)\n else:\n graph_tensor = tf.raw_ops.Placeholder(\n dtype=tensor_info.dtype, shape=tensor_info.shape, name=name)\n else:\n # Using a placeholder with no default value causes tracing to fail if\n # there is any control flow dependent on a child tensor of this\n # placeholder. Hence, provide a temporary default value for it.\n # If dtype is string, we want a tensor that contains '0's instead of b'[]\n # to allow string to numeric conversion ops to trace successfully.\n temporary_dtype = (\n tf.int64 if tensor_info.dtype == tf.string else tensor_info.dtype)\n temporary_tensor = tf2_utils.supply_missing_tensor(\n 1, tf.TensorShape(tensor_info.shape), temporary_dtype)\n if tensor_info.dtype == tf.string:\n temporary_tensor = tf.strings.as_string(temporary_tensor)\n graph_tensor = tf.raw_ops.PlaceholderWithDefault(\n input=temporary_tensor, shape=tensor_info.shape, name=name)\n return _TemporaryAnalyzerOutputWrapper(asset, graph_tensor)\n\n\ndef _bind_future_as_tensor_v2(\n future: nodes.ValueNode,\n tensor_info: TensorInfo,\n name: Optional[str] = None) -> common_types.TemporaryAnalyzerOutputType:\n \"\"\"Bind a future value as a tensor to a TF2 FuncGraph.\n\n If the future is expected to write out an asset file and this method is\n invoked within a `TFGraphContext` that was provided a temporary directory,\n a temporary file is written out by this method.\n\n This could write out a significant number of temporary files depending on\n number of times the `preprocessing_fn` is traced and number of asset files\n in each tracing.\n\n Args:\n future: Future whose result should replace the graph tensor to which its\n bound.\n tensor_info: A `TensorInfo` object containing attributes to create the graph\n tensor.\n name: (Optional) If provided, the graph tensor created uses this name.\n\n Returns:\n A graph tensor or `tf.saved_model.Asset` that this future is bound to. If\n this future has already been evaluated in a previous TFT phase, it is\n directly returned.\n \"\"\"\n graph = ops.get_default_graph()\n temp_dir = TFGraphContext.get_or_create_temp_dir()\n temporary_analyzer_info = _get_temporary_analyzer_output(\n temp_dir, tensor_info, name)\n is_asset_filepath = tensor_info.temporary_asset_value is not None\n\n # TODO(b/149997088): Switch to using a counter instead of tensor names.\n # Check if an evaluated value exists for this analyzer node.\n evaluated_replacements = TFGraphContext.get_evaluated_replacements()\n # evaluated_replacements is a dictionary from placeholder name to evaluated\n # tensor.\n # If `preprocessing_fn` was traced previously and this future was then\n # evaluated in a TFT phase, the result will be present in this dictionary.\n analyzer_name = temporary_analyzer_info.graph_tensor.name\n tensor_sink = TensorSink(temporary_analyzer_info.graph_tensor, future,\n is_asset_filepath)\n graph.add_to_collection(ALL_REPLACEMENTS, tensor_sink)\n if (evaluated_replacements is not None and\n analyzer_name in evaluated_replacements):\n replaced_result = evaluated_replacements[analyzer_name]\n if is_asset_filepath:\n graph.add_to_collection(tf.compat.v1.GraphKeys.ASSET_FILEPATHS,\n replaced_result)\n return replaced_result\n else:\n # Without the identity wrapper some V2 tests fail with AttributeError:\n # Tensor.name is meaningless when eager execution is enabled.\n # TODO(b/149997088): Remove the identity wrapper once we no longer rely on\n # tensor names.\n return tf.identity(replaced_result)\n else:\n graph.add_to_collection(TENSOR_REPLACEMENTS, tensor_sink)\n eager_asset_path = temporary_analyzer_info.eager_asset_path\n if is_asset_filepath and eager_asset_path is not None:\n tf_utils.track_asset_analyzer_output(eager_asset_path,\n temporary_analyzer_info.graph_tensor)\n graph.add_to_collection(tf.compat.v1.GraphKeys.ASSET_FILEPATHS,\n eager_asset_path)\n return temporary_analyzer_info.graph_tensor\n\n\ndef bind_future_as_tensor(\n future: nodes.ValueNode,\n tensor_info: TensorInfo,\n name: Optional[str] = None) -> common_types.TemporaryAnalyzerOutputType:\n \"\"\"Bind a future value as a tensor.\"\"\"\n # TODO(b/165884902): Use tf.inside_function after dropping TF 2.3 support.\n if isinstance(ops.get_default_graph(), func_graph.FuncGraph):\n # If the default graph is a `FuncGraph`, tf.function was used to trace the\n # preprocessing fn.\n return _bind_future_as_tensor_v2(future, tensor_info, name)\n else:\n return _bind_future_as_tensor_v1(future, tensor_info, name)\n\n\ndef wrap_as_tensor(\n output_value_node: nodes.ValueNode\n) -> common_types.TemporaryAnalyzerOutputType:\n analyzer_def = output_value_node.parent_operation.operation_def\n assert isinstance(analyzer_def, AnalyzerDef)\n return bind_future_as_tensor(\n output_value_node,\n analyzer_def.output_tensor_infos[output_value_node.value_index])\n\n\nclass Combiner:\n \"\"\"Analyze using combiner function.\n\n This object mirrors a beam.CombineFn, that will receive a beam PCollection\n representing the batched input tensors.\n \"\"\"\n\n def __repr__(self):\n return '<{}>'.format(self.__class__.__name__)\n\n def create_accumulator(self):\n \"\"\"Return a fresh, empty accumulator.\n\n Returns: An empty accumulator. This can be any Python value.\n \"\"\"\n raise NotImplementedError\n\n def add_input(self, accumulator, batch_values):\n \"\"\"Return result of folding a batch of inputs into accumulator.\n\n Args:\n accumulator: the current accumulator\n batch_values: A list of ndarrays representing the values of the inputs for\n a batch, which should be added to the accumulator.\n\n Returns: An accumulator that includes the batch of inputs.\n \"\"\"\n raise NotImplementedError\n\n def merge_accumulators(self, accumulators):\n \"\"\"Merges several accumulators to a single accumulator value.\n\n Args:\n accumulators: the accumulators to merge\n\n Returns: The sole merged accumulator.\n \"\"\"\n raise NotImplementedError\n\n def compact(self, accumulator):\n \"\"\"Returns an equivalent but more compact represenation of the accumulator.\n\n Args:\n accumulator: the current accumulator.\n\n Returns: A more compact accumulator.\n \"\"\"\n return accumulator\n\n def extract_output(self, accumulator):\n \"\"\"Return result of converting accumulator into the output value.\n\n Args:\n accumulator: the final accumulator value.\n\n Returns: A list of ndarrays representing the result of this combiner.\n \"\"\"\n raise NotImplementedError\n\n def output_tensor_infos(self):\n \"\"\"Return the number / types of outputs that are produced by extract_output.\n\n Returns: An iterable of `TensorInfo` describing how the outputs that\n extract_output will produce should be wrapped as `Tensor`s.\n\n Types are required to be TensorFlow dtypes.\n \"\"\"\n raise NotImplementedError\n\n @property\n def accumulator_coder(self):\n return JsonNumpyCacheCoder()\n\n\nclass CacheCoder(metaclass=abc.ABCMeta):\n \"\"\"A coder iterface for encoding and decoding cache items.\"\"\"\n\n def __repr__(self):\n return '<{}>'.format(self.__class__.__name__)\n\n @abc.abstractmethod\n def encode_cache(self, cache):\n pass\n\n @abc.abstractmethod\n def decode_cache(self, encoded_cache):\n pass\n\n\nclass JsonNumpyCacheCoder(CacheCoder):\n \"\"\"An accumulator cache coder that can handle lists.\"\"\"\n\n def _convert_numpy_dtype(self, x):\n if hasattr(x, 'tolist'):\n return x.tolist()\n return x\n\n def encode_cache(self, accumulator):\n if isinstance(accumulator, (list, tuple)):\n primitive_accumulator = [\n self._convert_numpy_dtype(a) for a in accumulator\n ]\n else:\n primitive_accumulator = self._convert_numpy_dtype(accumulator)\n # Need to wrap in np.array and call tolist to make it JSON serializable.\n return tf.compat.as_bytes(json.dumps(primitive_accumulator))\n\n def decode_cache(self, encoded_accumulator):\n return np.array(json.loads(tf.compat.as_text(encoded_accumulator)))\n\n\nclass AnalyzerDef(nodes.OperationDef, metaclass=abc.ABCMeta):\n \"\"\"A subclass of OperationDef whose outputs can be constant tensors.\n\n An AnalyzerDef is an OperationDef that also provides enough information to\n wrap each of its outputs as constant `Tensor`s in the graph. By inserting\n the output of the AnalyzerDef back into the graph, the user can define\n multiple levels of anaylsis and transformation.\n\n All `OperationDef`s are placeholders for operations that will be implemented\n as `beam.PTransform`s. This is done by a registration system. The subclasses\n defined below that inherit from `AnalyzerDef` have there implementations\n registered in the module `tensorflow_transform.beam.analyzer_impls`.\n \"\"\"\n\n @property\n @abc.abstractmethod\n def output_tensor_infos(self):\n \"\"\"A description on how to wrap the outputs of this AnalyzerDef.\n\n An `OperationDef` defines the number of outputs it creates. An\n `AnalyzerDef` must implemented this property that defines not only the\n number of outputs but how to wrap each output as a tensor.\n \"\"\"\n pass\n\n @property\n def num_outputs(self):\n \"\"\"The number of outputs returned by this operation.\"\"\"\n return len(self.output_tensor_infos)\n\n\n# We do the packing of combiners after the caching optimization. Hence, we don't\n# name the packed operations as cacheable. The rationale behind doing the\n# combiner packing after the cache optimization is that this optimization is\n# more of a Beam execution level optimization and we want to keep it towards the\n# end. So that, once Beam can automatically pack combines, we can remove this.\nclass PackedCombineAccumulate(\n tfx_namedtuple.namedtuple('PackedCombineAccumulate',\n ['combiners', 'label']), nodes.OperationDef):\n \"\"\"An analyzer that packs a list of combiners into a single beam CombineFn.\n\n Fields:\n combiners: A list of `analysis_graph_builder._CombinerOpWrapper` objects.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiners, label):\n return super(PackedCombineAccumulate, cls).__new__(\n cls, combiners=combiners, label=_make_label(cls, label))\n\n @property\n def num_outputs(self):\n return 1\n\n # Note that this will not have any effect as packing of combiners is done\n # after the caching optimization.\n @property\n def is_partitionable(self):\n return True\n\n\nclass PackedCombineMerge(\n tfx_namedtuple.namedtuple('PackedCombineMerge', ['combiners', 'label']),\n nodes.OperationDef):\n \"\"\"An analyzer that packs a list of combiners into a single beam CombineFn.\n\n Fields:\n combiners: A list of `analysis_graph_builder._CombinerOpWrapper` objects.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiners, label):\n return super(PackedCombineMerge, cls).__new__(\n cls, combiners=combiners, label=_make_label(cls, label))\n\n @property\n def num_outputs(self):\n return 1\n\n\nclass CacheableCombineAccumulate(\n tfx_namedtuple.namedtuple('CacheableCombineAccumulate',\n ['combiner', 'label']), nodes.OperationDef):\n \"\"\"An analyzer that runs a beam CombineFn to accumulate without merging.\n\n This analyzer reduces the values that it accepts as inputs, using the\n provided `Combiner`. The `Combiner` is applied to the data by wrapping it as\n a `beam.CombineFn` and applying `beam.Combine`.\n\n Fields:\n combiner: The Combiner to be applies to the inputs.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiner):\n return super(CacheableCombineAccumulate, cls).__new__(\n cls, combiner=combiner, label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n @property\n def is_partitionable(self):\n return True\n\n @property\n def cache_coder(self):\n return self.combiner.accumulator_coder\n\n\nclass CacheableCombineMerge(\n tfx_namedtuple.namedtuple('CacheableCombineMerge', ['combiner', 'label']),\n nodes.OperationDef):\n \"\"\"An analyzer that runs a beam CombineFn to only merge computed accumulators.\n\n This analyzer reduces the values that it accepts as inputs, using the\n provided `Combiner`. The `Combiner` is applied to the data by wrapping it as\n a `beam.CombineFn` and applying `beam.Combine`.\n\n Fields:\n combiner: The Combiner to be applied to the inputs.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiner):\n return super(CacheableCombineMerge, cls).__new__(\n cls, combiner=combiner, label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n\nclass _CombinerPerKeyAccumulatorCoder(CacheCoder):\n \"\"\"Coder for per-key combiner accumulators.\"\"\"\n\n def __init__(self, value_coder):\n self._combiner_coder = value_coder\n self._vocabulary_coder = _BaseKVCoder()\n super().__init__()\n\n def __repr__(self):\n return '<{}[{}[{}]]>'.format(self.__class__.__name__,\n repr(self._vocabulary_coder),\n repr(self._combiner_coder))\n\n def encode_cache(self, accumulator):\n key, value = accumulator\n encoded_value = self._combiner_coder.encode_cache(value)\n return self._vocabulary_coder.encode_cache((key, encoded_value))\n\n def decode_cache(self, encoded_accumulator):\n accumulator = self._vocabulary_coder.decode_cache(encoded_accumulator)\n key, encoded_value = accumulator\n value = self._combiner_coder.decode_cache(encoded_value)\n return (key, value)\n\n\nclass CacheableCombinePerKeyAccumulate(\n tfx_namedtuple.namedtuple('CacheableCombinePerKeyAccumulate',\n ['combiner', 'label']), AnalyzerDef):\n \"\"\"An analyzer that runs `beam.CombinePerKey` to accumulate without merging.\n\n This analyzer reduces the values that it accepts as inputs, using the\n provided `Combiner`. The `Combiner` is applied to the data by wrapping it as\n a `beam.CombineFn` and applying `beam.CombinePerKey`.\n\n This analyzer is implemented by\n `tensorflow_transform.beam.analyzer_impls._IntermediateAccumulateCombineImpl`.\n\n Fields:\n combiner: The Combiner to be applied to the inputs.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiner):\n return super(CacheableCombinePerKeyAccumulate, cls).__new__(\n cls, combiner=combiner, label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n @property\n def is_partitionable(self):\n return True\n\n @property\n def cache_coder(self):\n return _CombinerPerKeyAccumulatorCoder(self.combiner.accumulator_coder)\n\n\nclass CacheableCombinePerKeyMerge(\n tfx_namedtuple.namedtuple('CacheableCombinePerKeyMerge',\n ['combiner', 'label']), nodes.OperationDef):\n \"\"\"An analyzer that runs `beam.CombinePerKey` to only merge accumulators.\n\n This analyzer reduces the values that it accepts as inputs, using the\n provided `Combiner`. The `Combiner` is applied to the data by wrapping it as\n a `beam.CombineFn` and applying `beam.CombinePerKey`.\n\n This analyzer is implemented by\n `tensorflow_transform.beam.analyzer_impls._MergeAccumulatorsCombinePerKeyImpl`\n\n Fields:\n combiner: The Combiner to use for merging and extracting outputs.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiner):\n return super(CacheableCombinePerKeyMerge, cls).__new__(\n cls, combiner=combiner, label=_make_label(cls))\n\n\nclass CacheableCombinePerKeyFormatKeys(\n tfx_namedtuple.namedtuple('CacheableCombinePerKeyFormatKeys',\n ['combiner', 'label']), AnalyzerDef):\n \"\"\"An analyzer that formats output for the non-stored per-key case.\n\n This analyzer converts the (key, output) pairs into a tuple of keys (of type\n string) and outputs.\n\n This analyzer is implemented by\n `tensorflow_transform.beam.analyzer_impls._CombinePerKeyFormatKeysImpl`\n\n Fields:\n combiner: The Combiner to use for extracting outputs.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, combiner):\n return super(CacheableCombinePerKeyFormatKeys, cls).__new__(\n cls, combiner=combiner, label=_make_label(cls))\n\n @property\n def output_tensor_infos(self):\n # Returns a key vocab and one output per combiner output.\n return [TensorInfo(tf.string, (None,), None)] + [\n TensorInfo(info.dtype, (None,) + info.shape, info.temporary_asset_value)\n for info in self.combiner.output_tensor_infos()\n ]\n\n\nclass CacheableCombinePerKeyFormatLarge(\n tfx_namedtuple.namedtuple('CacheableCombinePerKeyFormatLarge', ['label']),\n nodes.OperationDef):\n \"\"\"An analyzer that formats output prior to writing to file for per-key case.\n\n This operation operates on the output of CacheableCombinePerKeyAccumulate and\n is implemented by `tensorflow_transform.beam.analyzer_impls.\n _CombinePerKeyFormatLargeImpl`.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls):\n return super(CacheableCombinePerKeyFormatLarge, cls).__new__(\n cls, label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n\nclass ScaleAndFlattenPerKeyBucketBouandaries(\n tfx_namedtuple.namedtuple('PostProcessPerKeyBucketBoundaries',\n ['output_tensor_dtype', 'label']), AnalyzerDef):\n \"\"\"An analyzer which takes quantile boundaries per key and combines them.\n\n It receives a 2-d array of boundaries, computes scales and shifts to each\n row separately, a new boundaries 1-d array which is a combination of\n boundaries for all the keys, and the number of buckets defined for each key.\n\n This outputs boundaries, scale_factor_per_key, shift_per_key, num_buckets.\n\n For example, for an input boundaries matrix, [[0, 1, 2], [0, 1, 2]] it will\n return:\n boundaries: [0, 0.5, 1, 1.5, 2]\n scale_factor_per_key: [0.5, 0.5]\n shift_per_key: [0, 1]\n num_buckets: 4\n\n So the transformation of each input x before computing its bucket should be:\n F(x, key) = x * scale_factor_per_key[key] + shift_per_key[key]\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, output_tensor_dtype):\n return super(ScaleAndFlattenPerKeyBucketBouandaries, cls).__new__(\n cls, output_tensor_dtype=output_tensor_dtype, label=_make_label(cls))\n\n @property\n def output_tensor_infos(self):\n # Boundaries, scale_factor_per_key, shift_per_key, num_buckets.\n return [TensorInfo(self.output_tensor_dtype,\n (None,), None)] * 3 + [TensorInfo(tf.int64, (), None)]\n\n\nclass VocabularyAccumulate(\n tfx_namedtuple.namedtuple('VocabularyAccumulate',\n ['vocab_ordering_type', 'input_dtype', 'label']),\n nodes.OperationDef):\n \"\"\"An operation that accumulates unique words with their frequency or weight.\n\n This operation is implemented by\n `tensorflow_transform.beam.analyzer_impls._VocabularyAccumulateImpl`.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, vocab_ordering_type, input_dtype=tf.string.name):\n return super(VocabularyAccumulate, cls).__new__(\n cls,\n vocab_ordering_type=vocab_ordering_type,\n input_dtype=input_dtype,\n label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n @property\n def is_partitionable(self):\n return True\n\n @property\n def cache_coder(self):\n return _VocabularyAccumulatorCoder(input_dtype=self.input_dtype)\n\n\nclass _BaseKVCoder(CacheCoder):\n \"\"\"Coder for key-value based accumulators.\"\"\"\n\n def __init__(self):\n self._lengths_prefix_format = 'qq'\n self._lengths_prefix_length = struct.calcsize(self._lengths_prefix_format)\n super().__init__()\n\n def encode_cache(self, accumulator):\n token, value = accumulator\n len_token, len_value = len(token), len(value)\n return struct.pack(\n '{}{}s{}s'.format(self._lengths_prefix_format, len_token, len_value),\n len_token, len_value, token, value)\n\n def decode_cache(self, encoded_accumulator):\n (len_token, len_value) = struct.unpack_from(\n self._lengths_prefix_format,\n encoded_accumulator[:self._lengths_prefix_length])\n accumulator = struct.unpack_from(\n '{}s{}s'.format(len_token, len_value),\n encoded_accumulator[self._lengths_prefix_length:])\n return accumulator\n\n\nclass _VocabularyAccumulatorCoder(_BaseKVCoder):\n \"\"\"Coder for vocabulary accumulators.\"\"\"\n\n def __init__(self, input_dtype=tf.string.name):\n self._input_dtype = tf.dtypes.as_dtype(input_dtype)\n super().__init__()\n\n def encode_cache(self, accumulator):\n token, value = accumulator\n if self._input_dtype is not tf.string:\n token = tf.compat.as_bytes(json.dumps(token))\n # If the value is a _WeightedMeanAndVarAccumulator, cast each field to a\n # list for serialization.\n if isinstance(value, tuple):\n value = [\n a.tolist()\n for a in (value.count, value.mean, value.variance, value.weight)\n ]\n value = tf.compat.as_bytes(json.dumps(value))\n return super().encode_cache((token, value))\n\n def decode_cache(self, encoded_accumulator):\n accumulator = super().decode_cache(encoded_accumulator)\n token, value = accumulator\n if self._input_dtype is not tf.string:\n token = json.loads(tf.compat.as_text(token))\n\n value = json.loads(tf.compat.as_text(value))\n if isinstance(value, list):\n # If the value is a _WeightedMeanAndVarAccumulator (serialized to tuple),\n # cast each field back to a np.array.\n (count, mean, variance, weight) = value\n value = (np.array(count), np.array(mean), np.array(variance),\n np.array(weight))\n return token, value\n\n\nclass VocabularyCount(\n tfx_namedtuple.namedtuple('VocabularyCount', ['label']),\n nodes.OperationDef):\n \"\"\"An operation counts the total number of tokens in a vocabulary.\n\n This operation takes in the output of VocabularyAccumulate and is implemented\n by `tensorflow_transform.beam.analyzer_impls._VocabularyCountImpl`.\n\n The output of this operation is a singleton Integer.\n\n Fields:\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, label):\n return super().__new__(cls, label=_make_label(cls, label))\n\n @property\n def num_outputs(self):\n return 1\n\n\nclass VocabularyMerge(\n tfx_namedtuple.namedtuple('VocabularyMerge', [\n 'vocab_ordering_type', 'use_adjusted_mutual_info', 'min_diff_from_avg',\n 'label'\n ]), nodes.OperationDef):\n \"\"\"An operation that merges the accumulators produced by VocabularyAccumulate.\n\n This operation operates on the output of VocabularyAccumulate and is\n implemented by `tensorflow_transform.beam.analyzer_impls._VocabularyMergeImpl`\n .\n\n See `tft.vocabulary` for a description of the parameters.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, vocab_ordering_type, use_adjusted_mutual_info,\n min_diff_from_avg):\n return super(VocabularyMerge, cls).__new__(\n cls,\n vocab_ordering_type=vocab_ordering_type,\n use_adjusted_mutual_info=use_adjusted_mutual_info,\n min_diff_from_avg=min_diff_from_avg,\n label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n\nclass VocabularyPrune(\n tfx_namedtuple.namedtuple('VocabularyPrune', [\n 'top_k', 'frequency_threshold', 'informativeness_threshold',\n 'coverage_top_k', 'coverage_frequency_threshold',\n 'coverage_informativeness_threshold', 'key_fn',\n 'filter_newline_characters', 'input_dtype', 'label'\n ]), nodes.OperationDef):\n \"\"\"An operation that filters and orders a computed vocabulary.\n\n This operation operates on the output of VocabularyMerge and is implemented by\n `tensorflow_transform.beam.analyzer_impls._VocabularyPruneImpl`.\n\n See `tft.vocabulary` for a description of the parameters.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls,\n top_k,\n frequency_threshold,\n input_dtype,\n informativeness_threshold=float('-inf'),\n coverage_top_k=None,\n coverage_frequency_threshold=0,\n coverage_informativeness_threshold=float('-inf'),\n key_fn=None,\n filter_newline_characters=True):\n return super(VocabularyPrune, cls).__new__(\n cls,\n top_k=top_k,\n frequency_threshold=frequency_threshold,\n informativeness_threshold=informativeness_threshold,\n coverage_top_k=coverage_top_k,\n coverage_frequency_threshold=coverage_frequency_threshold,\n coverage_informativeness_threshold=coverage_informativeness_threshold,\n key_fn=key_fn,\n filter_newline_characters=filter_newline_characters,\n input_dtype=input_dtype,\n label=_make_label(cls))\n\n @property\n def num_outputs(self):\n return 1\n\n\nclass VocabularyOrderAndWrite(\n tfx_namedtuple.namedtuple('VocabularyOrderAndWrite', [\n 'vocab_filename', 'store_frequency', 'input_dtype', 'label',\n 'fingerprint_shuffle', 'file_format', 'input_is_sorted'\n ]), AnalyzerDef):\n \"\"\"An analyzer that writes vocabulary files from an accumulator.\n\n This operation operates on the output of VocabularyPrune and is implemented by\n `tensorflow_transform.beam.analyzer_impls._VocabularyOrderAndWriteImpl`.\n\n See `tft.vocabulary` for a description of the parameters.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls,\n vocab_filename,\n store_frequency,\n fingerprint_shuffle,\n file_format,\n input_dtype=tf.string.name,\n input_is_sorted=False):\n return super(VocabularyOrderAndWrite, cls).__new__(\n cls,\n vocab_filename=vocab_filename,\n store_frequency=store_frequency,\n fingerprint_shuffle=fingerprint_shuffle,\n file_format=file_format,\n input_dtype=input_dtype,\n input_is_sorted=input_is_sorted,\n label=_make_label(cls))\n\n @property\n def output_tensor_infos(self):\n # Define temporary data for this node to write to a file before the actual\n # vocab file is evaluated and written out.\n temporary_asset_value = (b'TEMPORARY_ASSET_VALUE' if tf.dtypes.as_dtype(\n self.input_dtype) == tf.string else b'-777777')\n if self.store_frequency:\n temporary_asset_value = b'1 %s' % temporary_asset_value\n\n return [TensorInfo(tf.string, [], temporary_asset_value)]\n\n\nclass PTransform(\n tfx_namedtuple.namedtuple(\n 'PTransform', ['ptransform', 'output_tensor_info_list', 'label']),\n AnalyzerDef):\n \"\"\"(Experimental) OperationDef for PTransform anaylzer.\n\n This analyzer is implemented by\n `tensorflow_transform.beam.analyzer_impls._ptransform_impl`.\n\n Fields:\n ptransform: The `beam.PTransform` to be applied to the inputs.\n output_tensor_info_list: A list of `TensorInfo`s that defines the outputs of\n this `PTransform`.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, ptransform, output_tensor_info_list):\n return super(PTransform, cls).__new__(\n cls,\n ptransform=ptransform,\n output_tensor_info_list=output_tensor_info_list,\n label=_make_label(cls))\n\n @property\n def output_tensor_infos(self):\n return self.output_tensor_info_list\n\n\nclass EncodeCache(\n tfx_namedtuple.namedtuple('EncodeCache', ['coder', 'label']),\n nodes.OperationDef):\n \"\"\"OperationDef for encoding a cache instance.\n\n Fields:\n coder: An instance of CacheCoder used to encode cache.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n @property\n def is_partitionable(self):\n return True\n\n\nclass DecodeCache(\n tfx_namedtuple.namedtuple('DecodeCache',\n ['dataset_key', 'cache_key', 'coder', 'label']),\n nodes.OperationDef):\n \"\"\"OperationDef for decoding a cache instance.\n\n Fields:\n coder: An instance of CacheCoder used to decode cache.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def get_field_str(self, field_name):\n if field_name == 'cache_key':\n return '<bytes>'\n return super().get_field_str(field_name)\n\n @property\n def is_partitionable(self):\n return True\n\n\nclass AddKey(\n tfx_namedtuple.namedtuple('AddKey', ['key', 'label']), nodes.OperationDef):\n \"\"\"An operation that represents adding a key to a value.\n\n This operation represents a `beam.Map` that is applied to a PCollection.\n For each element of the PCollection, this corresponding element of the output\n PCollection is a tuple of (key, value).\n\n Attributes:\n key: The key which should be added to each element of the input PCollection.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n @property\n def is_partitionable(self):\n return True\n\n\nclass FlattenLists(\n tfx_namedtuple.namedtuple('FlattenLists', ['label']), nodes.OperationDef):\n \"\"\"An operation that represents flattening a PCollection of lists.\n\n Attributes:\n label: A unique label for this operation.\n \"\"\"\n\n def __new__(cls):\n return super(FlattenLists, cls).__new__(cls, label=_make_label(cls))\n\n @property\n def is_partitionable(self):\n return True\n\n\nclass ExtractCombineMergeOutputs(\n tfx_namedtuple.namedtuple('ExtractOutputs',\n ['output_tensor_info_list', 'label']),\n AnalyzerDef):\n \"\"\"An operation that represents extracting outputs of a combine merge.\n\n This operation represents a `beam.Map` that is applied to a PCollection.\n For each element of the PCollection, this corresponding element of the output\n PCollection is a tuple of outputs.\n\n Attributes:\n output_tensor_info_list: A list of `TensorInfo`s that defines the outputs of\n this operation.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, output_tensor_info_list):\n return super(ExtractCombineMergeOutputs, cls).__new__(\n cls,\n output_tensor_info_list=output_tensor_info_list,\n label=_make_label(cls))\n\n @property\n def output_tensor_infos(self):\n return self.output_tensor_info_list\n\n\nclass ExtractPackedCombineMergeOutputs(\n tfx_namedtuple.namedtuple('ExtractOutputs',\n ['output_tensor_info_list', 'label']),\n AnalyzerDef):\n \"\"\"An operation that represents extracting outputs of a packed combine merge.\n\n This operation represents a `beam.Map` that is applied to a PCollection.\n For each element of the PCollection, this corresponding element of the output\n PCollection is a tuple of outputs.\n\n Attributes:\n output_tensor_info_list: A list of `TensorInfo`s that defines the outputs of\n this operation.\n label: A unique label for this operation.\n \"\"\"\n __slots__ = ()\n\n @property\n def output_tensor_infos(self):\n return self.output_tensor_info_list\n" ]
[ [ "tensorflow.compat.v1.get_default_graph", "tensorflow.raw_ops.PlaceholderWithDefault", "tensorflow.constant", "tensorflow.TensorShape", "tensorflow.strings.as_string", "tensorflow.io.gfile.GFile", "tensorflow.identity", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.compat.v1.placeholder", "tensorflow.raw_ops.Placeholder", "tensorflow.init_scope", "tensorflow.name_scope", "numpy.array", "tensorflow.compat.as_text", "tensorflow.dtypes.as_dtype" ] ]
DiMesq/olfaction-prediction
[ "eda9ca029d3c78718afc6c1ba78f2831068de168" ]
[ "opc_python/gerkin/fit2.py" ]
[ "import warnings\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor,ExtraTreesRegressor\nfrom sklearn.model_selection import ShuffleSplit,cross_val_score\nfrom sklearn.linear_model import RandomizedLasso,Ridge\n\nfrom opc_python import * # Import constants. \nfrom opc_python.utils import scoring,prog,loading\nfrom opc_python.gerkin import dream\n\n# Use random forest regression to fit the entire training data set, \n# one descriptor set at a time. \ndef rfc_final(X,Y_imp,Y_mask,\n max_features,min_samples_leaf,max_depth,et,use_mask,trans_weight,\n trans_params,X_test_int=None,X_test_other=None,Y_test=None,\n n_estimators=100,seed=0,quiet=False):\n \n if X_test_int is None:\n X_test_int = X\n if X_test_other is None:\n X_test_other = X\n if Y_test is None:\n Y_test = Y_mask\n\n\n Y_imp = {'mean':Y_imp.mean(axis=1,level=1),\n 'std':Y_imp.std(axis=1,level=1)}\n Y_mask = {'mean':Y_mask.mean(axis=1),\n 'std':Y_mask.std(axis=1)}\n descriptors = loading.get_descriptors(format=True)\n\n def rfc_maker(n_estimators=n_estimators,max_features=max_features,\n min_samples_leaf=min_samples_leaf,max_depth=max_depth,\n et=False):\n if not et: \n kls = RandomForestRegressor\n kwargs = {'oob_score':False}\n else:\n kls = ExtraTreesRegressor\n kwargs = {}\n\n return kls(n_estimators=n_estimators, max_features=max_features,\n min_samples_leaf=min_samples_leaf, max_depth=max_depth,\n n_jobs=-1, random_state=seed, **kwargs)\n \n rfcs = {x:{} for x in ('mean','std')}\n for d,descriptor in enumerate(descriptors*2):\n prog(d,2*len(descriptors))\n kind = 'std' if d >= len(descriptors) else 'mean'\n rfcs[kind][descriptor] = rfc_maker(n_estimators=n_estimators,\n max_features=max_features[d],\n min_samples_leaf=min_samples_leaf[d],\n max_depth=max_depth[d],\n et=et[d])\n\n if use_mask[d]:\n rfcs[kind][descriptor].fit(X,Y_mask[kind][descriptor])\n else:\n rfcs[kind][descriptor].fit(X,Y_imp[kind][descriptor])\n \n columns = pd.MultiIndex.from_product([descriptors,('mean','std')],\n names=['Descriptor','Moment'])\n predicted = pd.DataFrame(index=X_test_int.index,columns=columns)\n for d,descriptor in enumerate(descriptors*2):\n X_test = X_test_int if descriptor == 'Intensity' else X_test_other\n kind = 'std' if d >= len(descriptors) else 'mean'\n if et[d] or not np.array_equal(X,X_test_int):\n # Possibly check in-sample fit because there isn't any alternative. \n predicted[(descriptor,kind)] = rfcs[kind][descriptor].predict(X_test)\n else:\n try:\n predicted[(descriptor,kind)] = \\\n rfcs[kind][descriptor].oob_prediction_\n except AttributeError:\n predicted[(descriptor,kind)] = \\\n rfcs[kind][descriptor].predict(X_test)\n\n def f_transform(x, k0, k1):\n return 100*(k0*(x/100)**(k1*0.5) - k0*(x/100)**(k1*2))\n\n for d,descriptor in enumerate(descriptors):\n tw = trans_weight[d]\n k0,k1 = trans_params[d]\n p_m = predicted[(descriptor,'mean')]\n p_s = predicted[(descriptor,'std')]\n predicted[(descriptor,kind)] = tw*f_transform(p_m,k0,k1) + (1-tw)*p_s\n \n predicted = predicted.stack('Descriptor')\n observed = Y_test\n score = scoring.score2(predicted,observed)\n rs = {}\n for kind in ['int','ple','dec']:\n rs[kind] = {}\n for moment in ['mean','std']:\n rs[kind][moment] = scoring.r2(kind,moment,predicted,observed)\n \n if not quiet:\n print(\"For subchallenge 2:\")\n print(\"\\tScore = %.2f\" % score)\n for kind in ['int','ple','dec']:\n for moment in ['mean','std']: \n print(\"\\t%s_%s = %.3f\" % (kind,moment,rs[kind][moment]))\n \n return (rfcs,score,rs)\n\ndef rfc_(X_train,Y_train,X_test_int,X_test_other,Y_test,\n max_features=1500,n_estimators=1000,max_depth=None,min_samples_leaf=1):\n print(max_features)\n def rfc_maker():\n return RandomForestRegressor(max_features=max_features,\n n_estimators=n_estimators,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n n_jobs=-1,\n oob_score=True,\n random_state=0)\n \n rfc = rfc_maker()\n rfc.fit(X_train,Y_train)\n scores = {}\n for phase,X,Y in [('train',X_train,Y_train),\n ('test',(X_test_int,X_test_other),Y_test)]:\n if phase == 'train':\n predicted = rfc.oob_prediction_\n else:\n predicted = rfc.predict(X[1])\n predicted_int = rfc.predict(X[0])\n predicted[:,0] = predicted_int[:,0]\n predicted[:,21] = predicted_int[:,21]\n observed = Y\n score = scoring.score2(predicted,observed)\n r_int = scoring.r2('int','mean',predicted,observed)\n r_ple = scoring.r2('ple','mean',predicted,observed)\n r_dec = scoring.r2('dec','mean',predicted,observed)\n r_int_sig = scoring.r2('int','std',predicted,observed)\n r_ple_sig = scoring.r2('ple','std',predicted,observed)\n r_dec_sig = scoring.r2('dec','std',predicted,observed)\n print((\"For subchallenge 2, %s phase, \"\n \"score = %.2f (%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\"\n % (phase,score,r_int,r_ple,r_dec,r_int_sig,r_ple_sig,r_dec_sig)))\n scores[phase] = (score,r_int,r_ple,r_dec,r_int_sig,r_ple_sig,r_dec_sig)\n\n return rfc,scores['train'],scores['test']\n\n# Show that random forest regression also works really well out of sample. \ndef rfc_cv(X,Y_imp,Y_mask,Y_test=None,n_splits=10,n_estimators=100,\n max_features=1500,min_samples_leaf=1,max_depth=None,rfc=True):\n if Y_mask is None:\n use_Y_mask = False\n Y_mask = Y_imp\n else:\n use_Y_mask = True\n if Y_test is None:\n Y_test = Y_mask\n if rfc:\n rfc_imp = RandomForestRegressor(max_features=max_features,\n n_estimators=n_estimators,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n oob_score=False,n_jobs=-1,random_state=0)\n rfc_mask = RandomForestRegressor(max_features=max_features,\n n_estimators=n_estimators,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n oob_score=False,n_jobs=-1,random_state=0)\n else:\n rfc_imp = ExtraTreesRegressor(max_features=max_features,\n n_estimators=n_estimators,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n oob_score=False,n_jobs=-1,random_state=0)\n rfc_mask = ExtraTreesRegressor(max_features=max_features,\n n_estimators=n_estimators,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n oob_score=False,n_jobs=-1,random_state=0)\n test_size = 0.2\n shuffle_split = ShuffleSplit(n_splits,test_size=test_size,random_state=0)\n n_molecules = len(Y_imp)\n test_size *= n_molecules\n rs = {'int':{'mean':[],'std':[],'trans':[]},\n 'ple':{'mean':[],'std':[]},\n 'dec':{'mean':[],'std':[]}}\n scores = []\n for train_index,test_index in shuffle_split.split(range(n_molecules)):\n rfc_imp.fit(X[train_index],Y_imp[train_index])\n predicted_imp = rfc_imp.predict(X[test_index])\n if use_Y_mask:\n rfc_mask.fit(X[train_index],Y_mask[train_index])\n predicted_mask = rfc_mask.predict(X[test_index])\n else:\n predicted_mask = predicted_imp\n observed = Y_test[test_index]\n rs_ = {'int':{},'ple':{},'dec':{}}\n for kind1 in ['int','ple','dec']:\n for kind2 in ['mean','std']:\n if kind2 in rs[kind1]:\n if '%s_%s' % (kind1,kind2) in ['int_mean','ple_mean',\n 'dec_mean']:\n r_ = scoring.r2(kind1,kind2,predicted_imp,observed)\n else:\n r_ = scoring.r2(kind1,kind2,predicted_mask,observed)\n rs_[kind1][kind2] = r_\n rs[kind1][kind2].append(r_)\n score = scoring.rs2score2(rs_)\n scores.append(score)\n rs['int']['trans'].append(scoring.r2(None,None,\n f_int(predicted_imp[:,0]),\n observed[:,21]))\n for kind1 in ['int','ple','dec']:\n for kind2 in ['mean','std','trans']:\n if kind2 in rs[kind1]:\n mean = np.mean(rs[kind1][kind2])\n sem = np.std(rs[kind1][kind2])/np.sqrt(n_splits)\n rs[kind1][kind2] = {'mean':mean,\n 'sem':sem}\n scores = {'mean':np.mean(scores),'sem':np.std(scores)/np.sqrt(n_splits)}\n #print(\"For subchallenge 2, using cross-validation with:\")\n #print(\"\\tat most %s features:\" % max_features)\n #print(\"\\tat least %s samples per leaf:\" % min_samples_leaf)\n #print(\"\\tat most %s depth:\" % max_depth)\n #print(\"\\tscore = %.2f+/- %.2f\" % (scores['mean'],scores['sem']))\n for kind2 in ['mean','std','trans']:\n for kind1 in ['int','ple','dec']:\n if kind2 in rs[kind1]:\n pass#print(\"\\t%s_%s = %.3f+/- %.3f\" % (kind1,kind2,rs[kind1][kind2]['mean'],rs[kind1][kind2]['sem']))\n \n return scores,rs\n\ndef f_int(x, k0=0.718, k1=1.08):\n return 100*(k0*(x/100)**(k1*0.5) - k0*(x/100)**(k1*2))\n\ndef scan(X_train,Y_train,X_test_int,X_test_other,Y_test,max_features=None,\n n_estimators=100):\n rfcs_max_features = {}\n ns = np.logspace(1,3.48,15)\n scores_train = []\n scores_test = []\n for n in ns:\n rfc_max_features,score_train,score_test = \\\n rfc_(X_train,Y_train['mean_std'],X_test_int,X_test_other,\n Y_test['mean_std'],max_features=int(n),n_estimators=100)\n scores_train.append(score_train)\n scores_test.append(score_test)\n rfcs_max_features[n] = rfc_max_features\n rs = ['int_m','ple_m','dec_m','int_s','ple_s','dec_s']\n for i,ri in enumerate(rs):\n print(ri)\n print('maxf ',ns.round(2))\n print('train',np.array(scores_train)[:,i].round(3))\n print('test ',np.array(scores_test)[:,i].round(3))\n \n return rfc_max_features,scores_train,scores_test\n #for n,train,test in zip(ns,scores_train,scores_test):\n # print(\"max_features = %d, train = %.2f, test = %.2f\" % (int(n),train,test))\n #return rfcs_max_features\n\n\ndef mask_vs_impute(X):\n print(2)\n Y_median,imputer = dream.make_Y_obs(['training','leaderboard'],\n target_dilution=None,imputer='median')\n Y_mask,imputer = dream.make_Y_obs(['training','leaderboard'],\n target_dilution=None,imputer='mask')\n r2s_median = rfc_cv(X,Y_median['mean_std'],Y_test=Y_mask['mean_std'],\n n_splits=20,max_features=1500,n_estimators=200,\n min_samples_leaf=1,rfc=True)\n r2s_mask = rfc_cv(X,Y_mask['mean_std'],n_splits=20,max_features=1500,\n n_estimators=200,min_samples_leaf=1,rfc=True)\n return (r2s_median,r2s_mask)\n\n\ndef compute_linear_feature_ranks(X,Y,n_resampling=10):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n \n X = X.drop(['mean_dilution'],1)\n \n # Matrix to store the score rankings. \n lin_ranked = np.zeros((21,X.shape[1])).astype(int) \n \n rl = RandomizedLasso(alpha=0.025,selection_threshold=0.025,\n n_resampling=n_resampling,random_state=25,n_jobs=1)\n for col in range(21):\n print(\"Computing feature ranks for descriptor #%d\" % col)\n observed = Y[:,col]\n rl.fit(X,observed)\n lin_ranked[col,:] = np.argsort(rl.all_scores_.ravel())[::-1]\n return lin_ranked\n\n\ndef compute_linear_feature_ranks_cv(X,Y,n_resampling=10,n_splits=25):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n \n # Matrix to store the score rankings. \n lin_ranked = np.zeros((n_splits,21,X.shape[1])).astype(int) \n n_molecules = int(X.shape[0]/2) # Expects an array with two dilutions\n # for each molecule\n shuffle_split = ShuffleSplit(n_splits,test_size=0.17,\n random_state=0) # This will produce the splits \n # in train/test_big that I \n # put on GitHub\n rl = RandomizedLasso(alpha=0.025,selection_threshold=0.025,\n n_resampling=n_resampling,random_state=25,n_jobs=1)\n for col in range(21):\n # Produce the correct train and test indices. \n cv = utils.DoubleSS(shuffle_split, n_molecules, col, X[:,-1]) \n for j,(train,test) in enumerate(cv):\n print(\"Computing feature ranks for descriptor #%d, split #%d\" \\\n % (col,j))\n observed = Y[train,col]\n rl.fit(X[train,:],observed)\n lin_ranked[j,col,:] = np.argsort(rl.all_scores_.ravel())[::-1]\n return lin_ranked\n\n\ndef master_cv(X,Y,n_estimators=50,n_splits=25,model='rf',\n alpha=10.0,random_state=0,feature_list=slice(None)):\n rs = np.zeros((21,n_splits))\n n_molecules = int(X.shape[0]/2)\n # This random state *must* be zero. \n shuffle_split = ShuffleSplit(n_splits,test_size=0.17,random_state=0) \n \n for col in range(21):\n print(col)\n observed = Y[:,col]\n cv = utils.DoubleSS(shuffle_split, n_molecules, col, X[:,-1])\n for j,(train,test) in enumerate(cv):\n #print(col,j)\n if model == 'rf':\n if col==0:\n est = ExtraTreesRegressor(n_estimators=n_estimators,\n max_features=max_features[col], \n max_depth=max_depth[col], \n min_samples_leaf=min_samples_leaf[col],\n n_jobs=8,random_state=0) \n else:\n est = RandomForestRegressor(n_estimators=n_estimators,\n max_features=max_features[col], \n max_depth=max_depth[col], \n min_samples_leaf=min_samples_leaf[col],\n oob_score=False,n_jobs=8,\n random_state=0)\n elif model == 'ridge':\n est = Ridge(alpha=alpha,random_state=random_state)\n features = feature_list[j,col,:]\n est.fit(X[train,:][:,features],observed[train])\n predicted = est.predict(X[test,:][:,features])\n rs[col,j] = np.corrcoef(predicted,observed[test])[1,0]\n\n mean = rs[col,:].mean()\n sem = rs[col,:].std()/np.sqrt(n_splits)\n print(('Desc. %d: %.3f' % (col,mean)))\n return rs\n\n\ndef feature_sweep(X,Y,n_estimators=50,n_splits=25,\n n_features=[1,2,3,4,5,10,33,100,333,1000,3333,10000],\n model='rf',wrong_split=False,max_features='auto',\n max_depth=None,min_samples_leaf=1,alpha=1.0,\n lin_ranked=None,random_state=0):\n if model == 'ridge' and lin_ranked is None:\n raise Exception('Must provided \"lin_ranked\" to use the linear model')\n rs = np.ma.zeros((21,len(n_features),n_splits)) # Empty matrix to store correlations. \n n_molecules = int(X_all.shape[0]/2) # Number of molecules. \n shuffle_split = ShuffleSplit(n_molecules,n_splits,test_size=0.17,\n random_state=0) \n # This will produce the splits in train/test_big that I \n # put on GitHub\n \n for col in range(0,21): # For each descriptor. \n observed = Y[:,col] # Perceptual data for this descriptor. \n n_features_ = list(np.array(n_features)+(col==0))\n # Produce the correct train and test indices. \n cv = DoubleSS(shuffle_split, n_molecules, col, X_all[:,-1]) \n for j,(train,test) in enumerate(cv):\n print('Fitting descriptor #%d, split #%d' % (col,j))\n if model == 'rf': # If the model is random forest regression. \n if col==0:\n est = ExtraTreesRegressor(n_estimators=n_estimators,\n max_features=max_features,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n n_jobs=8,\n random_state=random_state)\n else:\n est = RandomForestRegressor(n_estimators=n_estimators,\n max_features=max_features,\n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n oob_score=False,n_jobs=8,\n random_state=random_state)\n elif model == 'ridge': # If the model is ridge regression. \n est = Ridge(alpha=alpha,fit_intercept=True,normalize=False, \n copy_X=True,max_iter=None,tol=0.001,solver='auto',\n random_state=random_state)\n if rfe: \n rfe = RFE(estimator=est, step=n_features_, \n n_features_to_select=1)\n rfe.fit(X[train,:],observed[train]) \n else: \n # Fit the model on the training data. \n est.fit(X[train,:],observed[train]) \n if model == 'rf':\n # Use feature importances to get ranks.\n import_ranks = np.argsort(est.feature_importances_)[::-1] \n elif model == 'ridge':\n # Use the pre-computed ranks.\n import_ranks = lin_ranked[int(j+wrong_split)%n_splits,col,:] \n for i,n_feat in enumerate(n_features_):\n if col==0:\n # Add one for intensity since negLogD is worthless when\n # all concentrations are 1/1000. \n n_feat += 1 \n if hasattr(est,'max_features') \\\n and est.max_features not in [None,'auto']:\n if n_feat < est.max_features:\n est.max_features = n_feat\n if rfe:\n est.fit(X[train,:][:,rfe.ranking_<=(1+i)],observed[train])\n predicted = est.predict(X[test,:][:,rfe.ranking_<=(1+i)])\n else:\n #est.max_features = None\n # Fit the model on the training data\n # with 'max_features' features.\n est.fit(X[train,:][:,import_ranks[:n_feat]],observed[train])\n # Predict the test data. \n predicted = est.predict(X[test,:][:,import_ranks[:n_feat]]) \n # Compute the correlation coefficient.\n rs[col,i,j] = np.corrcoef(predicted,observed[test])[1,0] \n return rs" ]
[ [ "sklearn.ensemble.RandomForestRegressor", "sklearn.linear_model.RandomizedLasso", "sklearn.model_selection.ShuffleSplit", "numpy.sqrt", "numpy.array_equal", "numpy.logspace", "pandas.DataFrame", "numpy.std", "sklearn.linear_model.Ridge", "numpy.mean", "pandas.MultiIndex.from_product", "sklearn.ensemble.ExtraTreesRegressor", "numpy.corrcoef", "numpy.argsort", "numpy.array", "numpy.zeros" ] ]
venclov/PSMNet
[ "77d2a4ea46f55b7dee44258c80917228d2c3f212", "77d2a4ea46f55b7dee44258c80917228d2c3f212" ]
[ "main.py", "dataloader/trimbotLoader.py" ]
[ "from __future__ import print_function\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport numpy as np\nimport time\nimport math\nfrom dataloader import listflowfile as lt\nfrom dataloader import SecenFlowLoader as DA\nfrom models import *\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nparser = argparse.ArgumentParser(description='PSMNet')\nparser.add_argument('--maxdisp', type=int ,default=192,\n help='maxium disparity')\nparser.add_argument('--model', default='stackhourglass',\n help='select model')\nparser.add_argument('--datapath', default='/vol/bitbucket/pv819/sceneflow_data/',\n help='datapath')\nparser.add_argument('--epochs', type=int, default=0,\n help='number of epochs to train')\nparser.add_argument('--loadmodel', default= None,\n help='load model')\nparser.add_argument('--savemodel', default='./',\n help='save model')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\nall_left_img, all_right_img, all_left_disp, test_left_img, test_right_img, test_left_disp = lt.dataloader(args.datapath)\n\nTrainImgLoader = torch.utils.data.DataLoader(\n DA.myImageFloder(all_left_img,all_right_img,all_left_disp, True), \n batch_size= 3, shuffle= True, num_workers= 8, drop_last=False)\n\n# TestImgLoader = torch.utils.data.DataLoader(\n# DA.myImageFloder(test_left_img[:100],test_right_img[:100],test_left_disp[:100], False), \n# batch_size= 2, shuffle= False, num_workers= 4, drop_last=False)\n\nwriter = SummaryWriter('/vol/bitbucket/pv819/logs_validate/further/')\n\n\n\nif args.model == 'stackhourglass':\n model = stackhourglass(args.maxdisp)\nelif args.model == 'basic':\n model = basic(args.maxdisp)\nelse:\n print('no model')\n\nif args.cuda:\n model = nn.DataParallel(model)\n model.cuda()\n\nif args.loadmodel is not None:\n print('Load pretrained model')\n pretrain_dict = torch.load(args.loadmodel)\n model.load_state_dict(pretrain_dict['state_dict'])\n\nprint('Number of model parameters: {}'.format(sum([p.data.nelement() for p in model.parameters()])))\n\noptimizer = optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999))\n\ndef train(imgL,imgR, disp_L):\n model.train()\n\n if args.cuda:\n imgL, imgR, disp_true = imgL.cuda(), imgR.cuda(), disp_L.cuda()\n else:\n disp_true = disp_L\n\n #---------\n mask = disp_true < args.maxdisp\n mask.detach_()\n #----\n optimizer.zero_grad()\n \n if args.model == 'stackhourglass':\n output1, output2, output3 = model(imgL,imgR)\n output1 = torch.squeeze(output1,1)\n output2 = torch.squeeze(output2,1)\n output3 = torch.squeeze(output3,1)\n loss = 0.5*F.smooth_l1_loss(output1[mask], disp_true[mask], size_average=True) + 0.7*F.smooth_l1_loss(output2[mask], disp_true[mask], size_average=True) + F.smooth_l1_loss(output3[mask], disp_true[mask], size_average=True) \n elif args.model == 'basic':\n output_pred, output_var = model(imgL,imgR)\n print('After model Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n output_pred = torch.squeeze(output_pred,1)\n output_var= torch.squeeze(output_var,1)\n var_weigth = 1\n var = output_var[mask] * var_weigth \n shape = output_pred.shape\n loss_pred = F.smooth_l1_loss(output_pred[mask], disp_true[mask], reduction='none')\n loss1 = torch.mul(torch.exp(-var), loss_pred)\n loss2 = var\n loss = 1/2 * (loss1 + loss2)\n loss_mean = loss.mean() \n\n print('Before mean Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n loss_mean.backward()\n optimizer.step()\n\n return loss_mean.item()\n\ndef validate(imgL,imgR,disp_L):\n if args.cuda:\n imgL, imgR, disp_true = imgL.cuda(), imgR.cuda(), disp_L.cuda()\n else:\n disp_true = disp_L\n\n #---------\n mask = disp_true < args.maxdisp\n mask.detach_()\n #----\n \n if args.model == 'stackhourglass':\n output1, output2, output3 = model(imgL,imgR)\n output1 = torch.squeeze(output1,1)\n output2 = torch.squeeze(output2,1)\n output3 = torch.squeeze(output3,1)\n loss = 0.5*F.smooth_l1_loss(output1[mask], disp_true[mask], size_average=True) + 0.7*F.smooth_l1_loss(output2[mask], disp_true[mask], size_average=True) + F.smooth_l1_loss(output3[mask], disp_true[mask], size_average=True) \n elif args.model == 'basic':\n # print('Before model Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n output_pred, output_var = model(imgL,imgR)\n # print('Before after Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n output_pred = torch.squeeze(output_pred,1)\n output_var= torch.squeeze(output_var,1)\n var_weigth = 1\n var = output_var[mask] * var_weigth \n shape = output_pred.shape\n loss_pred = F.smooth_l1_loss(output_pred[mask], disp_true[mask], reduction='none')\n loss1 = torch.mul(torch.exp(-var), loss_pred)\n loss2 = var\n loss = 1/2 * (loss1 + loss2)\n loss_mean = loss.mean() \n\n return loss_mean.item()\n\n\ndef test(imgL,imgR,disp_true):\n\n model.eval()\n \n if args.cuda:\n imgL, imgR, disp_true = imgL.cuda(), imgR.cuda(), disp_true.cuda()\n #---------\n mask = disp_true < 192\n #----\n\n if imgL.shape[2] % 16 != 0:\n times = imgL.shape[2]//16 \n top_pad = (times+1)*16 -imgL.shape[2]\n else:\n top_pad = 0\n\n if imgL.shape[3] % 16 != 0:\n times = imgL.shape[3]//16 \n right_pad = (times+1)*16-imgL.shape[3]\n else:\n right_pad = 0 \n\n imgL = F.pad(imgL,(0,right_pad, top_pad,0))\n imgR = F.pad(imgR,(0,right_pad, top_pad,0))\n\n with torch.no_grad():\n output3 = model(imgL,imgR)\n output3 = torch.squeeze(output3)\n \n if top_pad !=0:\n img = output3[:,top_pad:,:]\n else:\n img = output3\n\n if len(disp_true[mask])==0:\n loss = 0\n else:\n loss = F.l1_loss(img[mask],disp_true[mask]) #torch.mean(torch.abs(img[mask]-disp_true[mask])) # end-point-error\n\n return loss.data.cpu()\n\ndef adjust_learning_rate(optimizer, epoch):\n lr = 0.001\n print(lr)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef main():\n\n epoch_len = len(TrainImgLoader)\n print(f\"Epoch len is {epoch_len} iterations\")\n start_full_time = time.time()\n for epoch in range(0, args.epochs):\n print('This is %d-th epoch' %(epoch))\n total_train_loss = 0\n adjust_learning_rate(optimizer,epoch)\n\n # training ##\n for batch_idx, (imgL_crop, imgR_crop, disp_crop_L) in enumerate(TrainImgLoader):\n start_time = time.time()\n loss = train(imgL_crop,imgR_crop, disp_crop_L)\n print('Iter %d training loss = %.3f , time = %.2f' %(batch_idx, loss, time.time() - start_time))\n total_train_loss += loss\n \n if batch_idx % 3 == 0:\n # log loss\n writer.add_scalar('Loss/train', loss, batch_idx + epoch_len * epoch)\n\n # if batch_idx % 5 == 0:\n # # validate model\n # # print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n # with torch.no_grad():\n # total_val_loss = 0\n # for batch_idx_v, (imgL_crop_v, imgR_crop_v, disp_crop_L_v) in enumerate(TestImgLoader):\n # loss_v = validate(imgL_crop_v,imgR_crop_v, disp_crop_L_v)\n # total_val_loss += loss_v\n # writer.add_scalar('Loss/validation', total_val_loss / len(TestImgLoader), batch_idx + epoch_len * epoch)\n # print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')\n\n\n\n print('epoch %d total training loss = %.3f' %(epoch, total_train_loss/len(TrainImgLoader)))\n #SAVE\n savefilename = args.savemodel+'/checkpoint_'+str(epoch)+'.tar'\n torch.save({\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'train_loss': total_train_loss/len(TrainImgLoader),\n }, savefilename)\n\n print('full training time = %.2f HR' %((time.time() - start_full_time)/3600))\n\n\t#------------- TEST ------------------------------------------------------------\n\t# total_test_loss = 0\n\t# for batch_idx, (imgL, imgR, disp_L) in enumerate(TestImgLoader):\n\t# test_loss = test(imgL,imgR, disp_L)\n\t# print('Iter %d test loss = %.3f' %(batch_idx, test_loss))\n\t# total_test_loss += test_loss\n\n\t# print('total test loss = %.3f' %(total_test_loss/len(TestImgLoader)))\n\t# #----------------------------------------------------------------------------------\n\t# #SAVE test information\n\t# savefilename = args.savemodel+'testinformation.tar'\n\t# torch.save({\n\t# \t 'test_loss': total_test_loss/len(TestImgLoader),\n\t# \t}, savefilename)\n\n\nif __name__ == '__main__':\n main()\n \n", "\nimport os\nimport torch\nimport torch.utils.data as data\nimport torch\nimport torchvision.transforms as transforms\nimport random\nfrom PIL import Image, ImageOps\nfrom . import preprocess \nfrom . import listflowfile as lt\nfrom . import readpfm as rp\nimport numpy as np\n\n\n\nIMG_EXTENSIONS = [\n '.jpg', '.JPG', '.jpeg', '.JPEG',\n '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',\n]\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\ndef default_loader(path):\n return Image.open(path).convert('RGB')\n\ndef disparity_loader(path):\n with open(path, 'rb') as f:\n x = np.fromfile(f, dtype='>f4', sep='')\n a = np.reshape(x, [480, 640], order='F')\n return a\n\nclass myImageFloder(data.Dataset):\n def __init__(self, left, right, left_disparity, training, loader=default_loader, dploader= disparity_loader):\n \n self.left = left\n self.right = right\n self.disp_L = left_disparity\n self.loader = loader\n self.dploader = dploader\n self.training = training\n\n def __getitem__(self, index):\n left = self.left[index]\n right = self.right[index]\n disp_L= self.disp_L[index]\n\n\n left_img = self.loader(left)\n right_img = self.loader(right)\n dataL, scaleL = self.dploader(disp_L)\n dataL = np.ascontiguousarray(dataL,dtype=np.float32)\n\n if self.training: \n w, h = left_img.size\n th, tw = 256, 512\n\n x1 = random.randint(0, w - tw)\n y1 = random.randint(0, h - th)\n\n left_img = left_img.crop((x1, y1, x1 + tw, y1 + th))\n right_img = right_img.crop((x1, y1, x1 + tw, y1 + th))\n\n dataL = dataL[y1:y1 + th, x1:x1 + tw]\n\n processed = preprocess.get_transform(augment=False) \n left_img = processed(left_img)\n right_img = processed(right_img)\n\n return left_img, right_img, dataL\n else:\n processed = preprocess.get_transform(augment=False) \n left_img = processed(left_img)\n right_img = processed(right_img) \n return left_img, right_img, dataL\n\n def __len__(self):\n return len(self.left)\n" ]
[ [ "torch.cuda.manual_seed", "torch.load", "torch.squeeze", "torch.manual_seed", "torch.nn.functional.l1_loss", "torch.exp", "torch.no_grad", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available", "torch.nn.functional.smooth_l1_loss", "torch.cuda.memory_allocated", "torch.nn.DataParallel", "torch.nn.functional.pad" ], [ "numpy.reshape", "numpy.fromfile", "numpy.ascontiguousarray" ] ]
michalk8/NeuralEE
[ "8946abf919770e2f75ee68c27fc66f96c290f871" ]
[ "neuralee/_aux/error.py" ]
[ "import torch\nimport math\n\n\n@torch.no_grad()\ndef error_ee(X, Wp, Wn, lam):\n \"\"\"Elastic embedding loss function.\n\n It's quite straightforward, may unapplicable when size is large,\n and the alternative error_ee_cpu and error_ee_cuda are designed to\n release computation stress.\n\n :param X: sample-coordinates matrix.\n :type X: torch.FloatTensor\n :param Wp: attractive weights.\n :type Wp: torch.FloatTensor\n :param Wn: repulsive weights.\n :type Wn: torch.FloatTensor\n :param lam: trade-off factor of elastic embedding function.\n :returns: elastic embedding loss value and the kernel matrix.\n \"\"\"\n sqd = sqdist(X)\n ker = torch.exp(-sqd)\n error = Wp.view(-1).dot(sqd.view(-1)) + lam * Wn.view(-1).dot(ker.view(-1))\n return error, ker\n\n\n@torch.no_grad()\ndef sqdist(X):\n \"\"\"Euclidean distance of coordinates.\n\n :param X: sample-coordinates matrix.\n :type X: torch.FloatTensor\n :return: Euclidean distance.\n :rtype: torch.FloatTensor\n \"\"\"\n x = (X ** 2).sum(dim=1, keepdim=True)\n sqd = x - 2 * X @ X.t() + x.t()\n ind = torch.arange(X.shape[0]).tolist()\n sqd[ind, ind] = torch.zeros(\n X.shape[0], device=X.device, dtype=torch.float32)\n sqd = sqd.clamp_min(0)\n return sqd\n\n\n@torch.no_grad()\ndef error_ee_split(X, Wp, Wn, lam, memory=2, device=None):\n \"\"\"Elastic embedding loss function deployed on GPU.\n\n It splits X, Wp, Wn into pieces and summarizes respective loss values\n to release computation stress.\n\n :param X: sample-coordinates matrix\n :type X: torch.FloatTensor\n :param Wp: attractive weights.\n :type Wp: torch.FloatTensor\n :param Wn: repulsive weights.\n :type Wn: torch.FloatTensor\n :param lam: trade-off factor of elastic embedding function.\n :param memory: memory(GB) allocated to computer error.\n :type device: torch.device\n :param device: device chosen to operate.\n If None, set as torch.device('cpu').\n :type device: torch.device\n :returns: elastic embedding loss value.\n \"\"\"\n device = X.device if device is None else device\n X = X.to(device)\n N = X.shape[0]\n B = math.floor((memory * 1024 ** 3) / (2 * N * 8))\n error = 0\n i1 = 0\n i2 = min(N, B)\n X2 = X ** 2\n x2 = X2.sum(dim=1, keepdim=True)\n\n while i1 < N:\n sqd = X2[i1: i2, :].sum(dim=1, keepdim=True) - \\\n 2 * X[i1: i2, :] @ X.t() + x2.t()\n ker = (-sqd).exp()\n error += Wp[i1: i2, :].to(device).view(-1).dot(sqd.view(-1)) + \\\n lam * Wn[i1: i2, :].to(device).view(-1).dot(ker.view(-1))\n i1 = i1 + B\n i2 = min(N, i1 + B)\n return error\n" ]
[ [ "torch.exp", "torch.no_grad", "torch.arange", "torch.zeros" ] ]
scopatz/openmc
[ "689d7b31677bc945aa21fa710801ac85562f1e87" ]
[ "openmc/mgxs/mgxs.py" ]
[ "from __future__ import division\n\nfrom collections import Iterable, OrderedDict\nfrom numbers import Integral\nimport warnings\nimport os\nimport sys\nimport copy\nimport abc\n\nimport numpy as np\n\nimport openmc\nimport openmc.checkvalue as cv\nfrom openmc.mgxs import EnergyGroups\n\n\nif sys.version_info[0] >= 3:\n basestring = str\n\n\n# Supported cross section types\nMGXS_TYPES = ['total',\n 'transport',\n 'nu-transport',\n 'absorption',\n 'capture',\n 'fission',\n 'nu-fission',\n 'kappa-fission',\n 'scatter',\n 'nu-scatter',\n 'scatter matrix',\n 'nu-scatter matrix',\n 'multiplicity matrix',\n 'nu-fission matrix',\n 'chi']\n\n\n# Supported domain types\n# TODO: Implement Mesh domains\nDOMAIN_TYPES = ['cell',\n 'distribcell',\n 'universe',\n 'material']\n\n# Supported domain classes\n# TODO: Implement Mesh domains\n_DOMAINS = (openmc.Cell,\n openmc.Universe,\n openmc.Material)\n\n\nclass MGXS(object):\n \"\"\"An abstract multi-group cross section for some energy group structure\n within some spatial domain.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations.\n\n NOTE: Users should instantiate the subclasses of this abstract class.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n # This is an abstract class which cannot be instantiated\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, domain=None, domain_type=None,\n energy_groups=None, by_nuclide=False, name=''):\n\n self._name = ''\n self._rxn_type = None\n self._by_nuclide = None\n self._nuclides = None\n self._domain = None\n self._domain_type = None\n self._energy_groups = None\n self._tally_trigger = None\n self._tallies = None\n self._rxn_rate_tally = None\n self._xs_tally = None\n self._sparse = False\n self._loaded_sp = False\n self._derived = False\n self._hdf5_key = None\n\n self.name = name\n self.by_nuclide = by_nuclide\n\n if domain_type is not None:\n self.domain_type = domain_type\n if domain is not None:\n self.domain = domain\n if energy_groups is not None:\n self.energy_groups = energy_groups\n\n def __deepcopy__(self, memo):\n existing = memo.get(id(self))\n\n # If this is the first time we have tried to copy this object, copy it\n if existing is None:\n clone = type(self).__new__(type(self))\n clone._name = self.name\n clone._rxn_type = self.rxn_type\n clone._by_nuclide = self.by_nuclide\n clone._nuclides = copy.deepcopy(self._nuclides)\n clone._domain = self.domain\n clone._domain_type = self.domain_type\n clone._energy_groups = copy.deepcopy(self.energy_groups, memo)\n clone._tally_trigger = copy.deepcopy(self.tally_trigger, memo)\n clone._rxn_rate_tally = copy.deepcopy(self._rxn_rate_tally, memo)\n clone._xs_tally = copy.deepcopy(self._xs_tally, memo)\n clone._sparse = self.sparse\n clone._derived = self.derived\n\n clone._tallies = OrderedDict()\n for tally_type, tally in self.tallies.items():\n clone.tallies[tally_type] = copy.deepcopy(tally, memo)\n\n memo[id(self)] = clone\n\n return clone\n\n # If this object has been copied before, return the first copy made\n else:\n return existing\n\n @property\n def name(self):\n return self._name\n\n @property\n def rxn_type(self):\n return self._rxn_type\n\n @property\n def by_nuclide(self):\n return self._by_nuclide\n\n @property\n def domain(self):\n return self._domain\n\n @property\n def domain_type(self):\n return self._domain_type\n\n @property\n def energy_groups(self):\n return self._energy_groups\n\n @property\n def tally_trigger(self):\n return self._tally_trigger\n\n @property\n def num_groups(self):\n return self.energy_groups.num_groups\n\n @property\n def scores(self):\n return ['flux', self.rxn_type]\n\n @property\n def filters(self):\n group_edges = self.energy_groups.group_edges\n energy_filter = openmc.Filter('energy', group_edges)\n return [[energy_filter]] * len(self.scores)\n\n @property\n def tally_keys(self):\n return self.scores\n\n @property\n def estimator(self):\n return 'tracklength'\n\n @property\n def tallies(self):\n\n # Instantiate tallies if they do not exist\n if self._tallies is None:\n\n # Initialize a collection of Tallies\n self._tallies = OrderedDict()\n\n # Create a domain Filter object\n domain_filter = openmc.Filter(self.domain_type, self.domain.id)\n\n # Create each Tally needed to compute the multi group cross section\n tally_metadata = zip(self.scores, self.tally_keys, self.filters)\n for score, key, filters in tally_metadata:\n self._tallies[key] = openmc.Tally(name=self.name)\n self._tallies[key].scores = [score]\n self._tallies[key].estimator = self.estimator\n self._tallies[key].filters = [domain_filter]\n\n # If a tally trigger was specified, add it to each tally\n if self.tally_trigger:\n trigger_clone = copy.deepcopy(self.tally_trigger)\n trigger_clone.scores = [score]\n self._tallies[key].triggers.append(trigger_clone)\n\n # Add non-domain specific Filters (e.g., 'energy') to the Tally\n for add_filter in filters:\n self._tallies[key].filters.append(add_filter)\n\n # If this is a by-nuclide cross-section, add nuclides to Tally\n if self.by_nuclide and score != 'flux':\n all_nuclides = self.get_all_nuclides()\n for nuclide in all_nuclides:\n self._tallies[key].nuclides.append(nuclide)\n else:\n self._tallies[key].nuclides.append('total')\n\n return self._tallies\n\n @property\n def rxn_rate_tally(self):\n if self._rxn_rate_tally is None:\n self._rxn_rate_tally = self.tallies[self.rxn_type]\n self._rxn_rate_tally.sparse = self.sparse\n\n return self._rxn_rate_tally\n\n @property\n def xs_tally(self):\n if self._xs_tally is None:\n if self.tallies is None:\n msg = 'Unable to get xs_tally since tallies have ' \\\n 'not been loaded from a statepoint'\n raise ValueError(msg)\n\n self._xs_tally = self.rxn_rate_tally / self.tallies['flux']\n self._compute_xs()\n\n return self._xs_tally\n\n @property\n def sparse(self):\n return self._sparse\n\n @property\n def num_subdomains(self):\n domain_filter = self.xs_tally.find_filter(self.domain_type)\n return domain_filter.num_bins\n\n @property\n def num_nuclides(self):\n if self.by_nuclide:\n return len(self.get_all_nuclides())\n else:\n return 1\n\n @property\n def nuclides(self):\n if self.by_nuclide:\n return self.get_all_nuclides()\n else:\n return 'sum'\n\n @property\n def loaded_sp(self):\n return self._loaded_sp\n\n @property\n def derived(self):\n return self._derived\n\n @property\n def hdf5_key(self):\n if self._hdf5_key is not None:\n return self._hdf5_key\n else:\n return self._rxn_type\n\n @name.setter\n def name(self, name):\n cv.check_type('name', name, basestring)\n self._name = name\n\n @by_nuclide.setter\n def by_nuclide(self, by_nuclide):\n cv.check_type('by_nuclide', by_nuclide, bool)\n self._by_nuclide = by_nuclide\n\n @nuclides.setter\n def nuclides(self, nuclides):\n cv.check_iterable_type('nuclides', nuclides, basestring)\n self._nuclides = nuclides\n\n @domain.setter\n def domain(self, domain):\n cv.check_type('domain', domain, _DOMAINS)\n self._domain = domain\n\n # Assign a domain type\n if self.domain_type is None:\n if isinstance(domain, openmc.Material):\n self._domain_type = 'material'\n elif isinstance(domain, openmc.Cell):\n self._domain_type = 'cell'\n elif isinstance(domain, openmc.Universe):\n self._domain_type = 'universe'\n\n @domain_type.setter\n def domain_type(self, domain_type):\n cv.check_value('domain type', domain_type, DOMAIN_TYPES)\n self._domain_type = domain_type\n\n @energy_groups.setter\n def energy_groups(self, energy_groups):\n cv.check_type('energy groups', energy_groups, openmc.mgxs.EnergyGroups)\n self._energy_groups = energy_groups\n\n @tally_trigger.setter\n def tally_trigger(self, tally_trigger):\n cv.check_type('tally trigger', tally_trigger, openmc.Trigger)\n self._tally_trigger = tally_trigger\n\n @sparse.setter\n def sparse(self, sparse):\n \"\"\"Convert tally data from NumPy arrays to SciPy list of lists (LIL)\n sparse matrices, and vice versa.\n\n This property may be used to reduce the amount of data in memory during\n tally data processing. The tally data will be stored as SciPy LIL\n matrices internally within the Tally object. All tally data access\n properties and methods will return data as a dense NumPy array.\n\n \"\"\"\n\n cv.check_type('sparse', sparse, bool)\n\n # Sparsify or densify the derived MGXS tallies and the base tallies\n if self._xs_tally:\n self.xs_tally.sparse = sparse\n if self._rxn_rate_tally:\n self.rxn_rate_tally.sparse = sparse\n\n for tally_name in self.tallies:\n self.tallies[tally_name].sparse = sparse\n\n self._sparse = sparse\n\n @staticmethod\n def get_mgxs(mgxs_type, domain=None, domain_type=None,\n energy_groups=None, by_nuclide=False, name=''):\n \"\"\"Return a MGXS subclass object for some energy group structure within\n some spatial domain for some reaction type.\n\n This is a factory method which can be used to quickly create MGXS\n subclass objects for various reaction types.\n\n Parameters\n ----------\n mgxs_type : {'total', 'transport', 'nu-transport', 'absorption', 'capture', 'fission', 'nu-fission', 'kappa-fission', 'scatter', 'nu-scatter', 'scatter matrix', 'nu-scatter matrix', 'multiplicity matrix', 'nu-fission matrix', chi'}\n The type of multi-group cross section object to return\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain.\n Defaults to False\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file. Defaults to the empty string.\n\n Returns\n -------\n openmc.mgxs.MGXS\n A subclass of the abstract MGXS class for the multi-group cross\n section type requested by the user\n\n \"\"\"\n\n cv.check_value('mgxs_type', mgxs_type, MGXS_TYPES)\n\n if mgxs_type == 'total':\n mgxs = TotalXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'transport':\n mgxs = TransportXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'nu-transport':\n mgxs = NuTransportXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'absorption':\n mgxs = AbsorptionXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'capture':\n mgxs = CaptureXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'fission':\n mgxs = FissionXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'nu-fission':\n mgxs = NuFissionXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'kappa-fission':\n mgxs = KappaFissionXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'scatter':\n mgxs = ScatterXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'nu-scatter':\n mgxs = NuScatterXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'scatter matrix':\n mgxs = ScatterMatrixXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'nu-scatter matrix':\n mgxs = NuScatterMatrixXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'multiplicity matrix':\n mgxs = MultiplicityMatrixXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'nu-fission matrix':\n mgxs = NuFissionMatrixXS(domain, domain_type, energy_groups)\n elif mgxs_type == 'chi':\n mgxs = Chi(domain, domain_type, energy_groups)\n\n mgxs.by_nuclide = by_nuclide\n mgxs.name = name\n return mgxs\n\n def get_all_nuclides(self):\n \"\"\"Get all nuclides in the cross section's spatial domain.\n\n Returns\n -------\n list of str\n A list of the string names for each nuclide in the spatial domain\n (e.g., ['U-235', 'U-238', 'O-16'])\n\n Raises\n ------\n ValueError\n When this method is called before the spatial domain has been set.\n\n \"\"\"\n\n if self.domain is None:\n raise ValueError('Unable to get all nuclides without a domain')\n\n # If the user defined nuclides, return them\n if self._nuclides:\n return self._nuclides\n\n # Otherwise, return all nuclides in the spatial domain\n else:\n nuclides = self.domain.get_all_nuclides()\n return list(nuclides.keys())\n\n def get_nuclide_density(self, nuclide):\n \"\"\"Get the atomic number density in units of atoms/b-cm for a nuclide\n in the cross section's spatial domain.\n\n Parameters\n ----------\n nuclide : str\n A nuclide name string (e.g., 'U-235')\n\n Returns\n -------\n float\n The atomic number density (atom/b-cm) for the nuclide of interest\n\n Raises\n -------\n ValueError\n When the density is requested for a nuclide which is not found in\n the spatial domain.\n\n \"\"\"\n\n cv.check_type('nuclide', nuclide, basestring)\n\n # Get list of all nuclides in the spatial domain\n nuclides = self.domain.get_all_nuclides()\n\n if nuclide not in nuclides:\n msg = 'Unable to get density for nuclide \"{0}\" which is not in ' \\\n '{1} \"{2}\"'.format(nuclide, self.domain_type, self.domain.id)\n ValueError(msg)\n\n density = nuclides[nuclide][1]\n return density\n\n def get_nuclide_densities(self, nuclides='all'):\n \"\"\"Get an array of atomic number densities in units of atom/b-cm for all\n nuclides in the cross section's spatial domain.\n\n Parameters\n ----------\n nuclides : Iterable of str or 'all' or 'sum'\n A list of nuclide name strings (e.g., ['U-235', 'U-238']). The\n special string 'all' will return the atom densities for all nuclides\n in the spatial domain. The special string 'sum' will return the atom\n density summed across all nuclides in the spatial domain. Defaults\n to 'all'.\n\n Returns\n -------\n numpy.ndarray of float\n An array of the atomic number densities (atom/b-cm) for each of the\n nuclides in the spatial domain\n\n Raises\n ------\n ValueError\n When this method is called before the spatial domain has been set.\n\n \"\"\"\n\n if self.domain is None:\n raise ValueError('Unable to get nuclide densities without a domain')\n\n # Sum the atomic number densities for all nuclides\n if nuclides == 'sum':\n nuclides = self.get_all_nuclides()\n densities = np.zeros(1, dtype=np.float)\n for nuclide in nuclides:\n densities[0] += self.get_nuclide_density(nuclide)\n\n # Tabulate the atomic number densities for all nuclides\n elif nuclides == 'all':\n nuclides = self.get_all_nuclides()\n densities = np.zeros(self.num_nuclides, dtype=np.float)\n for i, nuclide in enumerate(nuclides):\n densities[i] += self.get_nuclide_density(nuclide)\n\n # Tabulate the atomic number densities for each specified nuclide\n else:\n densities = np.zeros(len(nuclides), dtype=np.float)\n for i, nuclide in enumerate(nuclides):\n densities[i] = self.get_nuclide_density(nuclide)\n\n return densities\n\n def _compute_xs(self):\n \"\"\"Performs generic cleanup after a subclass' uses tally arithmetic to\n compute a multi-group cross section as a derived tally.\n\n This method replaces CrossNuclides generated by tally arithmetic with\n the original Nuclide objects in the xs_tally instance attribute. The\n simple Nuclides allow for cleaner output through Pandas DataFrames as\n well as simpler data access through the get_xs(...) class method.\n\n In addition, this routine resets NaNs in the multi group cross section\n array to 0.0. This may be needed occur if no events were scored in\n certain tally bins, which will lead to a divide-by-zero situation.\n\n \"\"\"\n\n # If computing xs for each nuclide, replace CrossNuclides with originals\n if self.by_nuclide:\n self.xs_tally._nuclides = []\n nuclides = self.get_all_nuclides()\n for nuclide in nuclides:\n self.xs_tally.nuclides.append(openmc.Nuclide(nuclide))\n\n # Remove NaNs which may have resulted from divide-by-zero operations\n self.xs_tally._mean = np.nan_to_num(self.xs_tally.mean)\n self.xs_tally._std_dev = np.nan_to_num(self.xs_tally.std_dev)\n self.xs_tally.sparse = self.sparse\n\n def load_from_statepoint(self, statepoint):\n \"\"\"Extracts tallies in an OpenMC StatePoint with the data needed to\n compute multi-group cross sections.\n\n This method is needed to compute cross section data from tallies\n in an OpenMC StatePoint object.\n\n NOTE: The statepoint must first be linked with an OpenMC Summary object.\n\n Parameters\n ----------\n statepoint : openmc.StatePoint\n An OpenMC StatePoint object with tally data\n\n Raises\n ------\n ValueError\n When this method is called with a statepoint that has not been\n linked with a summary object.\n\n \"\"\"\n\n cv.check_type('statepoint', statepoint, openmc.statepoint.StatePoint)\n\n if statepoint.summary is None:\n msg = 'Unable to load data from a statepoint which has not been ' \\\n 'linked with a summary file'\n raise ValueError(msg)\n\n # Override the domain object that loaded from an OpenMC summary file\n # NOTE: This is necessary for micro cross-sections which require\n # the isotopic number densities as computed by OpenMC\n if self.domain_type == 'cell' or self.domain_type == 'distribcell':\n self.domain = statepoint.summary.get_cell_by_id(self.domain.id)\n elif self.domain_type == 'universe':\n self.domain = statepoint.summary.get_universe_by_id(self.domain.id)\n elif self.domain_type == 'material':\n self.domain = statepoint.summary.get_material_by_id(self.domain.id)\n else:\n msg = 'Unable to load data from a statepoint for domain type {0} ' \\\n 'which is not yet supported'.format(self.domain_type)\n raise ValueError(msg)\n\n # Use tally \"slicing\" to ensure that tallies correspond to our domain\n # NOTE: This is important if tally merging was used\n if self.domain_type != 'distribcell':\n filters = [self.domain_type]\n filter_bins = [(self.domain.id,)]\n # Distribcell filters only accept single cell - neglect it when slicing\n else:\n filters = []\n filter_bins = []\n\n # Clear any tallies previously loaded from a statepoint\n if self.loaded_sp:\n self._tallies = None\n self._xs_tally = None\n self._rxn_rate_tally = None\n self._loaded_sp = False\n\n # Find, slice and store Tallies from StatePoint\n # The tally slicing is needed if tally merging was used\n for tally_type, tally in self.tallies.items():\n sp_tally = statepoint.get_tally(\n tally.scores, tally.filters, tally.nuclides,\n estimator=tally.estimator, exact_filters=True)\n sp_tally = sp_tally.get_slice(\n tally.scores, filters, filter_bins, tally.nuclides)\n sp_tally.sparse = self.sparse\n self.tallies[tally_type] = sp_tally\n\n self._loaded_sp = True\n\n def get_xs(self, groups='all', subdomains='all', nuclides='all',\n xs_type='macro', order_groups='increasing',\n value='mean', **kwargs):\n \"\"\"Returns an array of multi-group cross sections.\n\n This method constructs a 2D NumPy array for the requested multi-group\n cross section data data for one or more energy groups and subdomains.\n\n Parameters\n ----------\n groups : Iterable of Integral or 'all'\n Energy groups of interest. Defaults to 'all'.\n subdomains : Iterable of Integral or 'all'\n Subdomain IDs of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n A list of nuclide name strings (e.g., ['U-235', 'U-238']). The\n special string 'all' will return the cross sections for all nuclides\n in the spatial domain. The special string 'sum' will return the\n cross section summed over all nuclides. Defaults to 'all'.\n xs_type: {'macro', 'micro'}\n Return the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n order_groups: {'increasing', 'decreasing'}\n Return the cross section indexed according to increasing or\n decreasing energy groups (decreasing or increasing energies).\n Defaults to 'increasing'.\n value : {'mean', 'std_dev', 'rel_err'}\n A string for the type of value to return. Defaults to 'mean'.\n\n Returns\n -------\n numpy.ndarray\n A NumPy array of the multi-group cross section indexed in the order\n each group, subdomain and nuclide is listed in the parameters.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n cv.check_value('value', value, ['mean', 'std_dev', 'rel_err'])\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n filters = []\n filter_bins = []\n\n # Construct a collection of the domain filter bins\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=2)\n for subdomain in subdomains:\n filters.append(self.domain_type)\n filter_bins.append((subdomain,))\n\n # Construct list of energy group bounds tuples for all requested groups\n if not isinstance(groups, basestring):\n cv.check_iterable_type('groups', groups, Integral)\n for group in groups:\n filters.append('energy')\n filter_bins.append((self.energy_groups.get_group_bounds(group),))\n\n # Construct a collection of the nuclides to retrieve from the xs tally\n if self.by_nuclide:\n if nuclides == 'all' or nuclides == 'sum' or nuclides == ['sum']:\n query_nuclides = self.get_all_nuclides()\n else:\n query_nuclides = nuclides\n else:\n query_nuclides = ['total']\n\n # If user requested the sum for all nuclides, use tally summation\n if nuclides == 'sum' or nuclides == ['sum']:\n xs_tally = self.xs_tally.summation(nuclides=query_nuclides)\n xs = xs_tally.get_values(filters=filters,\n filter_bins=filter_bins, value=value)\n else:\n xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins,\n nuclides=query_nuclides, value=value)\n\n # Divide by atom number densities for microscopic cross sections\n if xs_type == 'micro':\n if self.by_nuclide:\n densities = self.get_nuclide_densities(nuclides)\n else:\n densities = self.get_nuclide_densities('sum')\n if value == 'mean' or value == 'std_dev':\n xs /= densities[np.newaxis, :, np.newaxis]\n\n # Reverse data if user requested increasing energy groups since\n # tally data is stored in order of increasing energies\n if order_groups == 'increasing':\n if groups == 'all':\n num_groups = self.num_groups\n else:\n num_groups = len(groups)\n\n # Reshape tally data array with separate axes for domain and energy\n num_subdomains = int(xs.shape[0] / num_groups)\n new_shape = (num_subdomains, num_groups) + xs.shape[1:]\n xs = np.reshape(xs, new_shape)\n\n # Reverse energies to align with increasing energy groups\n xs = xs[:, ::-1, :]\n\n # Eliminate trivial dimensions\n xs = np.squeeze(xs)\n xs = np.atleast_1d(xs)\n return xs\n\n def get_condensed_xs(self, coarse_groups):\n \"\"\"Construct an energy-condensed version of this cross section.\n\n Parameters\n ----------\n coarse_groups : openmc.mgxs.EnergyGroups\n The coarse energy group structure of interest\n\n Returns\n -------\n MGXS\n A new MGXS condensed to the group structure of interest\n\n \"\"\"\n\n cv.check_type('coarse_groups', coarse_groups, EnergyGroups)\n cv.check_less_than('coarse groups', coarse_groups.num_groups,\n self.num_groups, equality=True)\n cv.check_value('upper coarse energy', coarse_groups.group_edges[-1],\n [self.energy_groups.group_edges[-1]])\n cv.check_value('lower coarse energy', coarse_groups.group_edges[0],\n [self.energy_groups.group_edges[0]])\n\n # Clone this MGXS to initialize the condensed version\n condensed_xs = copy.deepcopy(self)\n condensed_xs._rxn_rate_tally = None\n condensed_xs._xs_tally = None\n condensed_xs._sparse = False\n condensed_xs._energy_groups = coarse_groups\n\n # Build energy indices to sum across\n energy_indices = []\n for group in range(coarse_groups.num_groups, 0, -1):\n low, high = coarse_groups.get_group_bounds(group)\n low_index = np.where(self.energy_groups.group_edges == low)[0][0]\n energy_indices.append(low_index)\n\n fine_edges = self.energy_groups.group_edges\n\n # Condense each of the tallies to the coarse group structure\n for tally_type, tally in condensed_xs.tallies.items():\n\n # Make condensed tally derived and null out sum, sum_sq\n tally._derived = True\n tally._sum = None\n tally._sum_sq = None\n\n # Get tally data arrays reshaped with one dimension per filter\n mean = tally.get_reshaped_data(value='mean')\n std_dev = tally.get_reshaped_data(value='std_dev')\n\n # Sum across all applicable fine energy group filters\n for i, tally_filter in enumerate(tally.filters):\n if 'energy' not in tally_filter.type:\n continue\n elif len(tally_filter.bins) != len(fine_edges):\n continue\n elif not np.allclose(tally_filter.bins, fine_edges):\n continue\n else:\n tally_filter.bins = coarse_groups.group_edges\n mean = np.add.reduceat(mean, energy_indices, axis=i)\n std_dev = np.add.reduceat(std_dev**2, energy_indices, axis=i)\n std_dev = np.sqrt(std_dev)\n\n # Reshape condensed data arrays with one dimension for all filters\n mean = np.reshape(mean, tally.shape)\n std_dev = np.reshape(std_dev, tally.shape)\n\n # Override tally's data with the new condensed data\n tally._mean = mean\n tally._std_dev = std_dev\n\n # Compute the energy condensed multi-group cross section\n condensed_xs.sparse = self.sparse\n return condensed_xs\n\n def get_subdomain_avg_xs(self, subdomains='all'):\n \"\"\"Construct a subdomain-averaged version of this cross section.\n\n This method is useful for averaging cross sections across distribcell\n instances. The method performs spatial homogenization to compute the\n scalar flux-weighted average cross section across the subdomains.\n\n Parameters\n ----------\n subdomains : Iterable of Integral or 'all'\n The subdomain IDs to average across. Defaults to 'all'.\n\n Returns\n -------\n openmc.mgxs.MGXS\n A new MGXS averaged across the subdomains of interest\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n # Construct a collection of the subdomain filter bins to average across\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral)\n elif self.domain_type == 'distribcell':\n subdomains = np.arange(self.num_subdomains)\n else:\n subdomains = None\n\n # Clone this MGXS to initialize the subdomain-averaged version\n avg_xs = copy.deepcopy(self)\n\n if self.derived:\n avg_xs._rxn_rate_tally = avg_xs.rxn_rate_tally.average(\n filter_type=self.domain_type, filter_bins=subdomains)\n else:\n avg_xs._rxn_rate_tally = None\n avg_xs._xs_tally = None\n\n # Average each of the tallies across subdomains\n for tally_type, tally in avg_xs.tallies.items():\n tally_avg = tally.average(filter_type=self.domain_type,\n filter_bins=subdomains)\n avg_xs.tallies[tally_type] = tally_avg\n\n avg_xs._domain_type = 'avg({0})'.format(self.domain_type)\n avg_xs.sparse = self.sparse\n return avg_xs\n\n def get_slice(self, nuclides=[], groups=[]):\n \"\"\"Build a sliced MGXS for the specified nuclides and energy groups.\n\n This method constructs a new MGXS to encapsulate a subset of the data\n represented by this MGXS. The subset of data to include in the tally\n slice is determined by the nuclides and energy groups specified in\n the input parameters.\n\n Parameters\n ----------\n nuclides : list of str\n A list of nuclide name strings\n (e.g., ['U-235', 'U-238']; default is [])\n groups : list of int\n A list of energy group indices starting at 1 for the high energies\n (e.g., [1, 2, 3]; default is [])\n\n Returns\n -------\n openmc.mgxs.MGXS\n A new MGXS object which encapsulates the subset of data requested\n for the nuclide(s) and/or energy group(s) requested in the\n parameters.\n\n \"\"\"\n\n cv.check_iterable_type('nuclides', nuclides, basestring)\n cv.check_iterable_type('energy_groups', groups, Integral)\n\n # Build lists of filters and filter bins to slice\n if len(groups) == 0:\n filters = []\n filter_bins = []\n else:\n filter_bins = []\n for group in groups:\n group_bounds = self.energy_groups.get_group_bounds(group)\n filter_bins.append(group_bounds)\n filter_bins = [tuple(filter_bins)]\n filters = ['energy']\n\n # Clone this MGXS to initialize the sliced version\n slice_xs = copy.deepcopy(self)\n slice_xs._rxn_rate_tally = None\n slice_xs._xs_tally = None\n\n # Slice each of the tallies across nuclides and energy groups\n for tally_type, tally in slice_xs.tallies.items():\n slice_nuclides = [nuc for nuc in nuclides if nuc in tally.nuclides]\n if len(groups) != 0 and tally.contains_filter('energy'):\n tally_slice = tally.get_slice(filters=filters,\n filter_bins=filter_bins, nuclides=slice_nuclides)\n else:\n tally_slice = tally.get_slice(nuclides=slice_nuclides)\n slice_xs.tallies[tally_type] = tally_slice\n\n # Assign sliced energy group structure to sliced MGXS\n if groups:\n new_group_edges = []\n for group in groups:\n group_edges = self.energy_groups.get_group_bounds(group)\n new_group_edges.extend(group_edges)\n new_group_edges = np.unique(new_group_edges)\n slice_xs.energy_groups.group_edges = sorted(new_group_edges)\n\n # Assign sliced nuclides to sliced MGXS\n if nuclides:\n slice_xs.nuclides = nuclides\n\n slice_xs.sparse = self.sparse\n return slice_xs\n\n def can_merge(self, other):\n \"\"\"Determine if another MGXS can be merged with this one\n\n If results have been loaded from a statepoint, then MGXS are only\n mergeable along one and only one of enegy groups or nuclides.\n\n Parameters\n ----------\n other : openmc.mgxs.MGXS\n MGXS to check for merging\n\n \"\"\"\n\n if not isinstance(other, type(self)):\n return False\n\n # Compare reaction type, energy groups, nuclides, domain type\n if self.rxn_type != other.rxn_type:\n return False\n elif not self.energy_groups.can_merge(other.energy_groups):\n return False\n elif self.by_nuclide != other.by_nuclide:\n return False\n elif self.domain_type != other.domain_type:\n return False\n elif 'distribcell' not in self.domain_type and self.domain != other.domain:\n return False\n elif not self.xs_tally.can_merge(other.xs_tally):\n return False\n elif not self.rxn_rate_tally.can_merge(other.rxn_rate_tally):\n return False\n\n # If all conditionals pass then MGXS are mergeable\n return True\n\n def merge(self, other):\n \"\"\"Merge another MGXS with this one\n\n MGXS are only mergeable if their energy groups and nuclides are either\n identical or mutually exclusive. If results have been loaded from a\n statepoint, then MGXS are only mergeable along one and only one of\n energy groups or nuclides.\n\n Parameters\n ----------\n other : openmc.mgxs.MGXS\n MGXS to merge with this one\n\n Returns\n -------\n merged_mgxs : openmc.mgxs.MGXS\n Merged MGXS\n\n \"\"\"\n\n if not self.can_merge(other):\n raise ValueError('Unable to merge MGXS')\n\n # Create deep copy of tally to return as merged tally\n merged_mgxs = copy.deepcopy(self)\n merged_mgxs._derived = True\n\n # Merge energy groups\n if self.energy_groups != other.energy_groups:\n merged_groups = self.energy_groups.merge(other.energy_groups)\n merged_mgxs.energy_groups = merged_groups\n\n # Merge nuclides\n if self.nuclides != other.nuclides:\n\n # The nuclides must be mutually exclusive\n for nuclide in self.nuclides:\n if nuclide in other.nuclides:\n msg = 'Unable to merge MGXS with shared nuclides'\n raise ValueError(msg)\n\n # Concatenate lists of nuclides for the merged MGXS\n merged_mgxs.nuclides = self.nuclides + other.nuclides\n\n # Null base tallies but merge reaction rate and cross section tallies\n merged_mgxs._tallies = OrderedDict()\n merged_mgxs._rxn_rate_tally = self.rxn_rate_tally.merge(other.rxn_rate_tally)\n merged_mgxs._xs_tally = self.xs_tally.merge(other.xs_tally)\n\n return merged_mgxs\n\n def print_xs(self, subdomains='all', nuclides='all', xs_type='macro'):\n \"\"\"Print a string representation for the multi-group cross section.\n\n Parameters\n ----------\n subdomains : Iterable of Integral or 'all'\n The subdomain IDs of the cross sections to include in the report.\n Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the report. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will report the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will report\n the cross sections summed over all nuclides. Defaults to 'all'.\n xs_type: {'macro', 'micro'}\n Return the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n\n \"\"\"\n\n # Construct a collection of the subdomains to report\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral)\n elif self.domain_type == 'distribcell':\n subdomains = np.arange(self.num_subdomains, dtype=np.int)\n else:\n subdomains = [self.domain.id]\n\n # Construct a collection of the nuclides to report\n if self.by_nuclide:\n if nuclides == 'all':\n nuclides = self.get_all_nuclides()\n elif nuclides == 'sum':\n nuclides = ['sum']\n else:\n cv.check_iterable_type('nuclides', nuclides, basestring)\n else:\n nuclides = ['sum']\n\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n # Build header for string with type and domain info\n string = 'Multi-Group XS\\n'\n string += '{0: <16}=\\t{1}\\n'.format('\\tReaction Type', self.rxn_type)\n string += '{0: <16}=\\t{1}\\n'.format('\\tDomain Type', self.domain_type)\n string += '{0: <16}=\\t{1}\\n'.format('\\tDomain ID', self.domain.id)\n\n # If cross section data has not been computed, only print string header\n if self.tallies is None:\n print(string)\n return\n\n # Loop over all subdomains\n for subdomain in subdomains:\n\n if self.domain_type == 'distribcell':\n string += '{0: <16}=\\t{1}\\n'.format('\\tSubdomain', subdomain)\n\n # Loop over all Nuclides\n for nuclide in nuclides:\n\n # Build header for nuclide type\n if nuclide != 'sum':\n string += '{0: <16}=\\t{1}\\n'.format('\\tNuclide', nuclide)\n\n # Build header for cross section type\n if xs_type == 'macro':\n string += '{0: <16}\\n'.format('\\tCross Sections [cm^-1]:')\n else:\n string += '{0: <16}\\n'.format('\\tCross Sections [barns]:')\n\n template = '{0: <12}Group {1} [{2: <10} - {3: <10}MeV]:\\t'\n\n # Loop over energy groups ranges\n for group in range(1, self.num_groups+1):\n bounds = self.energy_groups.get_group_bounds(group)\n string += template.format('', group, bounds[0], bounds[1])\n average = self.get_xs([group], [subdomain], [nuclide],\n xs_type=xs_type, value='mean')\n rel_err = self.get_xs([group], [subdomain], [nuclide],\n xs_type=xs_type, value='rel_err')\n average = average.flatten()[0]\n rel_err = rel_err.flatten()[0] * 100.\n string += '{:.2e} +/- {:1.2e}%'.format(average, rel_err)\n string += '\\n'\n string += '\\n'\n string += '\\n'\n\n print(string)\n\n def build_hdf5_store(self, filename='mgxs.h5', directory='mgxs',\n subdomains='all', nuclides='all',\n xs_type='macro', row_column='inout', append=True):\n \"\"\"Export the multi-group cross section data to an HDF5 binary file.\n\n This method constructs an HDF5 file which stores the multi-group\n cross section data. The data is stored in a hierarchy of HDF5 groups\n from the domain type, domain id, subdomain id (for distribcell domains),\n nuclides and cross section type. Two datasets for the mean and standard\n deviation are stored for each subdomain entry in the HDF5 file.\n\n NOTE: This requires the h5py Python package.\n\n Parameters\n ----------\n filename : str\n Filename for the HDF5 file. Defaults to 'mgxs.h5'.\n directory : str\n Directory for the HDF5 file. Defaults to 'mgxs'.\n subdomains : Iterable of Integral or 'all'\n The subdomain IDs of the cross sections to include in the report.\n Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the report. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will report the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will report\n the cross sections summed over all nuclides. Defaults to 'all'.\n xs_type: {'macro', 'micro'}\n Store the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n row_column: {'inout', 'outin'}\n Store scattering matrices indexed first by incoming group and\n second by outgoing group ('inout'), or vice versa ('outin').\n Defaults to 'inout'.\n append : bool\n If true, appends to an existing HDF5 file with the same filename\n directory (if one exists). Defaults to True.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n ImportError\n When h5py is not installed.\n\n \"\"\"\n\n import h5py\n\n # Make directory if it does not exist\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n filename = os.path.join(directory, filename)\n filename = filename.replace(' ', '-')\n\n if append and os.path.isfile(filename):\n xs_results = h5py.File(filename, 'a')\n else:\n xs_results = h5py.File(filename, 'w')\n\n # Construct a collection of the subdomains to report\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral)\n elif self.domain_type == 'distribcell':\n subdomains = np.arange(self.num_subdomains, dtype=np.int)\n elif self.domain_type == 'avg(distribcell)':\n domain_filter = self.xs_tally.find_filter('avg(distribcell)')\n subdomains = domain_filter.bins\n else:\n subdomains = [self.domain.id]\n\n # Construct a collection of the nuclides to report\n if self.by_nuclide:\n if nuclides == 'all':\n nuclides = self.get_all_nuclides()\n densities = np.zeros(len(nuclides), dtype=np.float)\n elif nuclides == 'sum':\n nuclides = ['sum']\n else:\n cv.check_iterable_type('nuclides', nuclides, basestring)\n else:\n nuclides = ['sum']\n\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n # Create an HDF5 group within the file for the domain\n domain_type_group = xs_results.require_group(self.domain_type)\n domain_group = domain_type_group.require_group(str(self.domain.id))\n\n # Determine number of digits to pad subdomain group keys\n num_digits = len(str(self.num_subdomains))\n\n # Create a separate HDF5 group for each subdomain\n for i, subdomain in enumerate(subdomains):\n\n # Create an HDF5 group for the subdomain\n if self.domain_type == 'distribcell':\n group_name = ''.zfill(num_digits)\n subdomain_group = domain_group.require_group(group_name)\n else:\n subdomain_group = domain_group\n\n # Create a separate HDF5 group for this cross section\n rxn_group = subdomain_group.require_group(self.hdf5_key)\n\n # Create a separate HDF5 group for each nuclide\n for j, nuclide in enumerate(nuclides):\n\n if nuclide != 'sum':\n density = densities[j]\n nuclide_group = rxn_group.require_group(nuclide)\n nuclide_group.require_dataset('density', dtype=np.float64,\n data=[density], shape=(1,))\n else:\n nuclide_group = rxn_group\n\n # Extract the cross section for this subdomain and nuclide\n average = self.get_xs(subdomains=[subdomain], nuclides=[nuclide],\n xs_type=xs_type, value='mean', row_column=row_column)\n std_dev = self.get_xs(subdomains=[subdomain], nuclides=[nuclide],\n xs_type=xs_type, value='std_dev', row_column=row_column)\n average = average.squeeze()\n std_dev = std_dev.squeeze()\n\n # Add MGXS results data to the HDF5 group\n nuclide_group.require_dataset('average', dtype=np.float64,\n shape=average.shape, data=average)\n nuclide_group.require_dataset('std. dev.', dtype=np.float64,\n shape=std_dev.shape, data=std_dev)\n\n # Close the results HDF5 file\n xs_results.close()\n\n def export_xs_data(self, filename='mgxs', directory='mgxs',\n format='csv', groups='all', xs_type='macro'):\n \"\"\"Export the multi-group cross section data to a file.\n\n This method leverages the functionality in the Pandas library to export\n the multi-group cross section data in a variety of output file formats\n for storage and/or post-processing.\n\n Parameters\n ----------\n filename : str\n Filename for the exported file. Defaults to 'mgxs'.\n directory : str\n Directory for the exported file. Defaults to 'mgxs'.\n format : {'csv', 'excel', 'pickle', 'latex'}\n The format for the exported data file. Defaults to 'csv'.\n groups : Iterable of Integral or 'all'\n Energy groups of interest. Defaults to 'all'.\n xs_type: {'macro', 'micro'}\n Store the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n\n \"\"\"\n\n cv.check_type('filename', filename, basestring)\n cv.check_type('directory', directory, basestring)\n cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex'])\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n # Make directory if it does not exist\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n filename = os.path.join(directory, filename)\n filename = filename.replace(' ', '-')\n\n # Get a Pandas DataFrame for the data\n df = self.get_pandas_dataframe(groups=groups, xs_type=xs_type)\n\n # Capitalize column label strings\n df.columns = df.columns.astype(str)\n df.columns = map(str.title, df.columns)\n\n # Export the data using Pandas IO API\n if format == 'csv':\n df.to_csv(filename + '.csv', index=False)\n elif format == 'excel':\n df.to_excel(filename + '.xls', index=False)\n elif format == 'pickle':\n df.to_pickle(filename + '.pkl')\n elif format == 'latex':\n if self.domain_type == 'distribcell':\n msg = 'Unable to export distribcell multi-group cross section' \\\n 'data to a LaTeX table'\n raise NotImplementedError(msg)\n\n df.to_latex(filename + '.tex', bold_rows=True,\n longtable=True, index=False)\n\n # Surround LaTeX table with code needed to run pdflatex\n with open(filename + '.tex','r') as original:\n data = original.read()\n with open(filename + '.tex','w') as modified:\n modified.write(\n '\\\\documentclass[preview, 12pt, border=1mm]{standalone}\\n')\n modified.write('\\\\usepackage{caption}\\n')\n modified.write('\\\\usepackage{longtable}\\n')\n modified.write('\\\\usepackage{booktabs}\\n')\n modified.write('\\\\begin{document}\\n\\n')\n modified.write(data)\n modified.write('\\n\\\\end{document}')\n\n def get_pandas_dataframe(self, groups='all', nuclides='all',\n xs_type='macro', distribcell_paths=True):\n \"\"\"Build a Pandas DataFrame for the MGXS data.\n\n This method leverages :meth:`openmc.Tally.get_pandas_dataframe`, but\n renames the columns with terminology appropriate for cross section data.\n\n Parameters\n ----------\n groups : Iterable of Integral or 'all'\n Energy groups of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the dataframe. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will include the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will\n include the cross sections summed over all nuclides. Defaults\n to 'all'.\n xs_type: {'macro', 'micro'}\n Return macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n distribcell_paths : bool, optional\n Construct columns for distribcell tally filters (default is True).\n The geometric information in the Summary object is embedded into\n a Multi-index column with a geometric \"path\" to each distribcell\n instance.\n\n Returns\n -------\n pandas.DataFrame\n A Pandas DataFrame for the cross section data.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n if not isinstance(groups, basestring):\n cv.check_iterable_type('groups', groups, Integral)\n if nuclides != 'all' and nuclides != 'sum':\n cv.check_iterable_type('nuclides', nuclides, basestring)\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n # Get a Pandas DataFrame from the derived xs tally\n if self.by_nuclide and nuclides == 'sum':\n\n # Use tally summation to sum across all nuclides\n query_nuclides = self.get_all_nuclides()\n xs_tally = self.xs_tally.summation(nuclides=query_nuclides)\n df = xs_tally.get_pandas_dataframe(\n distribcell_paths=distribcell_paths)\n\n # Remove nuclide column since it is homogeneous and redundant\n df.drop('nuclide', axis=1, inplace=True)\n\n # If the user requested a specific set of nuclides\n elif self.by_nuclide and nuclides != 'all':\n xs_tally = self.xs_tally.get_slice(nuclides=nuclides)\n df = xs_tally.get_pandas_dataframe(\n distribcell_paths=distribcell_paths)\n\n # If the user requested all nuclides, keep nuclide column in dataframe\n else:\n df = self.xs_tally.get_pandas_dataframe(\n distribcell_paths=distribcell_paths)\n\n # Remove the score column since it is homogeneous and redundant\n df = df.drop('score', axis=1)\n\n # Override energy groups bounds with indices\n all_groups = np.arange(self.num_groups, 0, -1, dtype=np.int)\n all_groups = np.repeat(all_groups, self.num_nuclides)\n if 'energy low [MeV]' in df and 'energyout low [MeV]' in df:\n df.rename(columns={'energy low [MeV]': 'group in'},\n inplace=True)\n in_groups = np.tile(all_groups, self.num_subdomains)\n in_groups = np.repeat(in_groups, df.shape[0] / in_groups.size)\n df['group in'] = in_groups\n del df['energy high [MeV]']\n\n df.rename(columns={'energyout low [MeV]': 'group out'},\n inplace=True)\n out_groups = np.repeat(all_groups, self.xs_tally.num_scores)\n out_groups = np.tile(out_groups, df.shape[0] / out_groups.size)\n df['group out'] = out_groups\n del df['energyout high [MeV]']\n columns = ['group in', 'group out']\n\n elif 'energyout low [MeV]' in df:\n df.rename(columns={'energyout low [MeV]': 'group out'},\n inplace=True)\n in_groups = np.tile(all_groups, self.num_subdomains)\n df['group out'] = in_groups\n del df['energyout high [MeV]']\n columns = ['group out']\n\n elif 'energy low [MeV]' in df:\n df.rename(columns={'energy low [MeV]': 'group in'}, inplace=True)\n in_groups = np.tile(all_groups, self.num_subdomains)\n df['group in'] = in_groups\n del df['energy high [MeV]']\n columns = ['group in']\n\n # Select out those groups the user requested\n if not isinstance(groups, basestring):\n if 'group in' in df:\n df = df[df['group in'].isin(groups)]\n if 'group out' in df:\n df = df[df['group out'].isin(groups)]\n\n # If user requested micro cross sections, divide out the atom densities\n if xs_type == 'micro':\n if self.by_nuclide:\n densities = self.get_nuclide_densities(nuclides)\n else:\n densities = self.get_nuclide_densities('sum')\n tile_factor = df.shape[0] / len(densities)\n df['mean'] /= np.tile(densities, tile_factor)\n df['std. dev.'] /= np.tile(densities, tile_factor)\n\n # Sort the dataframe by domain type id (e.g., distribcell id) and\n # energy groups such that data is from fast to thermal\n df.sort_values(by=[self.domain_type] + columns, inplace=True)\n return df\n\n\nclass MatrixMGXS(MGXS):\n \"\"\"An abstract multi-group cross section for some energy group structure\n within some spatial domain. This class is specifically intended for\n cross sections which depend on both the incoming and outgoing energy groups\n and are therefore represented by matrices. Examples of this include the\n scattering and nu-fission matrices.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations.\n\n NOTE: Users should instantiate the subclasses of this abstract class.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n # This is an abstract class which cannot be instantiated\n __metaclass__ = abc.ABCMeta\n\n @property\n def filters(self):\n # Create the non-domain specific Filters for the Tallies\n group_edges = self.energy_groups.group_edges\n energy = openmc.Filter('energy', group_edges)\n energyout = openmc.Filter('energyout', group_edges)\n\n return [[energy], [energy, energyout]]\n\n @property\n def estimator(self):\n return 'analog'\n\n def get_xs(self, in_groups='all', out_groups='all',\n subdomains='all', nuclides='all',\n xs_type='macro', order_groups='increasing',\n row_column='inout', value='mean', **kwargs):\n \"\"\"Returns an array of multi-group cross sections.\n\n This method constructs a 2D NumPy array for the requested multi-group\n matrix data for one or more energy groups and subdomains.\n\n Parameters\n ----------\n in_groups : Iterable of Integral or 'all'\n Incoming energy groups of interest. Defaults to 'all'.\n out_groups : Iterable of Integral or 'all'\n Outgoing energy groups of interest. Defaults to 'all'.\n subdomains : Iterable of Integral or 'all'\n Subdomain IDs of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n A list of nuclide name strings (e.g., ['U-235', 'U-238']). The\n special string 'all' will return the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will\n return the cross section summed over all nuclides. Defaults to\n 'all'.\n xs_type: {'macro', 'micro'}\n Return the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n order_groups: {'increasing', 'decreasing'}\n Return the cross section indexed according to increasing or\n decreasing energy groups (decreasing or increasing energies).\n Defaults to 'increasing'.\n row_column: {'inout', 'outin'}\n Return the cross section indexed first by incoming group and\n second by outgoing group ('inout'), or vice versa ('outin').\n Defaults to 'inout'.\n value : {'mean', 'std_dev', 'rel_err'}\n A string for the type of value to return. Defaults to 'mean'.\n\n Returns\n -------\n ndarray\n A NumPy array of the multi-group cross section indexed in the order\n each group and subdomain is listed in the parameters.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n cv.check_value('value', value, ['mean', 'std_dev', 'rel_err'])\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n filters = []\n filter_bins = []\n\n # Construct a collection of the domain filter bins\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral,\n max_depth=2)\n for subdomain in subdomains:\n filters.append(self.domain_type)\n filter_bins.append((subdomain,))\n\n # Construct list of energy group bounds tuples for all requested groups\n if not isinstance(in_groups, basestring):\n cv.check_iterable_type('groups', in_groups, Integral)\n for group in in_groups:\n filters.append('energy')\n filter_bins.append((\n self.energy_groups.get_group_bounds(group),))\n\n # Construct list of energy group bounds tuples for all requested groups\n if not isinstance(out_groups, basestring):\n cv.check_iterable_type('groups', out_groups, Integral)\n for group in out_groups:\n filters.append('energyout')\n filter_bins.append((\n self.energy_groups.get_group_bounds(group),))\n\n # Construct a collection of the nuclides to retrieve from the xs tally\n if self.by_nuclide:\n if nuclides == 'all' or nuclides == 'sum' or nuclides == ['sum']:\n query_nuclides = self.get_all_nuclides()\n else:\n query_nuclides = nuclides\n else:\n query_nuclides = ['total']\n\n # Use tally summation if user requested the sum for all nuclides\n if nuclides == 'sum' or nuclides == ['sum']:\n xs_tally = self.xs_tally.summation(nuclides=query_nuclides)\n xs = xs_tally.get_values(filters=filters, filter_bins=filter_bins,\n value=value)\n else:\n xs = self.xs_tally.get_values(filters=filters,\n filter_bins=filter_bins,\n nuclides=query_nuclides, value=value)\n\n xs = np.nan_to_num(xs)\n\n # Divide by atom number densities for microscopic cross sections\n if xs_type == 'micro':\n if self.by_nuclide:\n densities = self.get_nuclide_densities(nuclides)\n else:\n densities = self.get_nuclide_densities('sum')\n if value == 'mean' or value == 'std_dev':\n xs /= densities[np.newaxis, :, np.newaxis]\n\n # Reverse data if user requested increasing energy groups since\n # tally data is stored in order of increasing energies\n if order_groups == 'increasing':\n if in_groups == 'all':\n num_in_groups = self.num_groups\n else:\n num_in_groups = len(in_groups)\n if out_groups == 'all':\n num_out_groups = self.num_groups\n else:\n num_out_groups = len(out_groups)\n\n # Reshape tally data array with separate axes for domain and energy\n num_subdomains = int(xs.shape[0] /\n (num_in_groups * num_out_groups))\n new_shape = (num_subdomains, num_in_groups, num_out_groups)\n new_shape += xs.shape[1:]\n xs = np.reshape(xs, new_shape)\n\n # Transpose the matrix if requested by user\n if row_column == 'outin':\n xs = np.swapaxes(xs, 1, 2)\n\n # Reverse energies to align with increasing energy groups\n xs = xs[:, ::-1, ::-1, :]\n\n # Eliminate trivial dimensions\n xs = np.squeeze(xs)\n xs = np.atleast_2d(xs)\n\n return xs\n\n def get_slice(self, nuclides=[], in_groups=[], out_groups=[]):\n \"\"\"Build a sliced MatrixMGXS object for the specified nuclides and\n energy groups.\n\n This method constructs a new MGXS to encapsulate a subset of the data\n represented by this MGXS. The subset of data to include in the tally\n slice is determined by the nuclides and energy groups specified in\n the input parameters.\n\n Parameters\n ----------\n nuclides : list of str\n A list of nuclide name strings\n (e.g., ['U-235', 'U-238']; default is [])\n in_groups : list of int\n A list of incoming energy group indices starting at 1 for the high\n energies (e.g., [1, 2, 3]; default is [])\n out_groups : list of int\n A list of outgoing energy group indices starting at 1 for the high\n energies (e.g., [1, 2, 3]; default is [])\n\n Returns\n -------\n openmc.mgxs.MatrixMGXS\n A new MatrixMGXS object which encapsulates the subset of data\n requested for the nuclide(s) and/or energy group(s) requested in\n the parameters.\n\n \"\"\"\n\n # Call super class method and null out derived tallies\n slice_xs = super(MatrixMGXS, self).get_slice(nuclides, in_groups)\n slice_xs._rxn_rate_tally = None\n slice_xs._xs_tally = None\n\n # Slice outgoing energy groups if needed\n if len(out_groups) != 0:\n filter_bins = []\n for group in out_groups:\n group_bounds = self.energy_groups.get_group_bounds(group)\n filter_bins.append(group_bounds)\n filter_bins = [tuple(filter_bins)]\n\n # Slice each of the tallies across energyout groups\n for tally_type, tally in slice_xs.tallies.items():\n if tally.contains_filter('energyout'):\n tally_slice = tally.get_slice(filters=['energyout'],\n filter_bins=filter_bins)\n slice_xs.tallies[tally_type] = tally_slice\n\n slice_xs.sparse = self.sparse\n return slice_xs\n\n def print_xs(self, subdomains='all', nuclides='all', xs_type='macro'):\n \"\"\"Prints a string representation for the multi-group cross section.\n\n Parameters\n ----------\n subdomains : Iterable of Integral or 'all'\n The subdomain IDs of the cross sections to include in the report.\n Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the report. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will report the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will\n report the cross sections summed over all nuclides. Defaults to\n 'all'.\n xs_type: {'macro', 'micro'}\n Return the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n\n \"\"\"\n\n # Construct a collection of the subdomains to report\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral)\n elif self.domain_type == 'distribcell':\n subdomains = np.arange(self.num_subdomains, dtype=np.int)\n else:\n subdomains = [self.domain.id]\n\n # Construct a collection of the nuclides to report\n if self.by_nuclide:\n if nuclides == 'all':\n nuclides = self.get_all_nuclides()\n if nuclides == 'sum':\n nuclides = ['sum']\n else:\n cv.check_iterable_type('nuclides', nuclides, basestring)\n else:\n nuclides = ['sum']\n\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n # Build header for string with type and domain info\n string = 'Multi-Group XS\\n'\n string += '{0: <16}=\\t{1}\\n'.format('\\tReaction Type', self.rxn_type)\n string += '{0: <16}=\\t{1}\\n'.format('\\tDomain Type', self.domain_type)\n string += '{0: <16}=\\t{1}\\n'.format('\\tDomain ID', self.domain.id)\n\n # If cross section data has not been computed, only print string header\n if self.tallies is None:\n print(string)\n return\n\n string += '{0: <16}\\n'.format('\\tEnergy Groups:')\n template = '{0: <12}Group {1} [{2: <10} - {3: <10}MeV]\\n'\n\n # Loop over energy groups ranges\n for group in range(1, self.num_groups + 1):\n bounds = self.energy_groups.get_group_bounds(group)\n string += template.format('', group, bounds[0], bounds[1])\n\n # Loop over all subdomains\n for subdomain in subdomains:\n\n if self.domain_type == 'distribcell':\n string += \\\n '{0: <16}=\\t{1}\\n'.format('\\tSubdomain', subdomain)\n\n # Loop over all Nuclides\n for nuclide in nuclides:\n\n # Build header for nuclide type\n if xs_type != 'sum':\n string += '{0: <16}=\\t{1}\\n'.format('\\tNuclide', nuclide)\n\n # Build header for cross section type\n if xs_type == 'macro':\n string += '{0: <16}\\n'.format('\\tCross Sections [cm^-1]:')\n else:\n string += '{0: <16}\\n'.format('\\tCross Sections [barns]:')\n\n template = '{0: <12}Group {1} -> Group {2}:\\t\\t'\n\n # Loop over incoming/outgoing energy groups ranges\n for in_group in range(1, self.num_groups + 1):\n for out_group in range(1, self.num_groups + 1):\n string += template.format('', in_group, out_group)\n average = \\\n self.get_xs([in_group], [out_group],\n [subdomain], [nuclide],\n xs_type=xs_type, value='mean')\n rel_err = \\\n self.get_xs([in_group], [out_group],\n [subdomain], [nuclide],\n xs_type=xs_type, value='rel_err')\n average = average.flatten()[0]\n rel_err = rel_err.flatten()[0] * 100.\n string += '{:1.2e} +/- {:1.2e}%'.format(average,\n rel_err)\n string += '\\n'\n string += '\\n'\n string += '\\n'\n string += '\\n'\n\n print(string)\n\n\nclass TotalXS(MGXS):\n r\"\"\"A total multi-group cross section.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group total cross sections for multi-group neutronics calculations. At\n a minimum, one needs to set the :attr:`TotalXS.energy_groups` and\n :attr:`TotalXS.domain` properties. Tallies for the flux and appropriate\n reaction rates over the specified domain are generated automatically via the\n :attr:`TotalXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`TotalXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n total cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\sigma_t (r, E) \\psi (r, E, \\Omega)}{\\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`TotalXS.tally_keys` property and values\n are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(TotalXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'total'\n\n\nclass TransportXS(MGXS):\n r\"\"\"A transport-corrected total multi-group cross section.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`TransportXS.energy_groups` and\n :attr:`TransportXS.domain` properties. Tallies for the flux and appropriate\n reaction rates over the specified domain are generated automatically via the\n :attr:`TransportXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`TransportXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n transport-corrected total cross section is calculated as:\n\n .. math::\n\n \\langle \\sigma_t \\phi \\rangle &= \\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\sigma_t (r, E) \\psi\n (r, E, \\Omega) \\\\\n \\langle \\sigma_{s1} \\phi \\rangle &= \\int_{r \\in V} dr\n \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\int_{4\\pi}\n d\\Omega' \\int_0^\\infty dE' \\int_{-1}^1 d\\mu \\; \\mu \\sigma_s\n (r, E' \\rightarrow E, \\Omega' \\cdot \\Omega)\n \\phi (r, E', \\Omega) \\\\\n \\langle \\phi \\rangle &= \\int_{r \\in V} dr \\int_{4\\pi} d\\Omega\n \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega) \\\\\n \\sigma_{tr} &= \\frac{\\langle \\sigma_t \\phi \\rangle - \\langle \\sigma_{s1}\n \\phi \\rangle}{\\langle \\phi \\rangle}\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`TransportXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(TransportXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'transport'\n\n @property\n def scores(self):\n return ['flux', 'total', 'scatter-1']\n\n @property\n def filters(self):\n group_edges = self.energy_groups.group_edges\n energy_filter = openmc.Filter('energy', group_edges)\n energyout_filter = openmc.Filter('energyout', group_edges)\n return [[energy_filter], [energy_filter], [energyout_filter]]\n\n @property\n def estimator(self):\n return 'analog'\n\n @property\n def rxn_rate_tally(self):\n if self._rxn_rate_tally is None:\n self.tallies['scatter-1'].filters[-1].type = 'energy'\n self._rxn_rate_tally = \\\n self.tallies['total'] - self.tallies['scatter-1']\n self._rxn_rate_tally.sparse = self.sparse\n\n return self._rxn_rate_tally\n\n\nclass NuTransportXS(TransportXS):\n r\"\"\"A transport-corrected total multi-group cross section which\n accounts for neutron multiplicity in scattering reactions.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`NuTransportXS.energy_groups` and\n :attr:`NuTransportXS.domain` properties. Tallies for the flux and\n appropriate reaction rates over the specified domain are generated\n automatically via the :attr:`NuTransportXS.tallies` property, which can then\n be appended to a :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`NuTransportXS.xs_tally` property.\n\n The calculation of the transport-corrected cross section is the same as that\n for :class:`TransportXS` except that the scattering multiplicity is\n accounted for.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`NuTransportXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(NuTransportXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'nu-transport'\n\n @property\n def scores(self):\n return ['flux', 'total', 'nu-scatter-1']\n\n @property\n def tally_keys(self):\n return ['flux', 'total', 'scatter-1']\n\n\nclass AbsorptionXS(MGXS):\n r\"\"\"An absorption multi-group cross section.\n\n Absorption is defined as all reactions that do not produce secondary\n neutrons (disappearance) plus fission reactions.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group absorption cross sections for multi-group neutronics\n calculations. At a minimum, one needs to set the\n :attr:`AbsorptionXS.energy_groups` and :attr:`AbsorptionXS.domain`\n properties. Tallies for the flux and appropriate reaction rates over the\n specified domain are generated automatically via the\n :attr:`AbsorptionXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`AbsorptionXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n absorption cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\sigma_a (r, E) \\psi (r, E, \\Omega)}{\\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`AbsorptionXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(AbsorptionXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'absorption'\n\n\nclass CaptureXS(MGXS):\n r\"\"\"A capture multi-group cross section.\n\n The neutron capture reaction rate is defined as the difference between\n OpenMC's 'absorption' and 'fission' reaction rate score types. This includes\n not only radiative capture, but all forms of neutron disappearance aside\n from fission (i.e., MT > 100).\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group capture cross sections for multi-group neutronics\n calculations. At a minimum, one needs to set the\n :attr:`CaptureXS.energy_groups` and :attr:`CaptureXS.domain`\n properties. Tallies for the flux and appropriate reaction rates over the\n specified domain are generated automatically via the\n :attr:`CaptureXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`CaptureXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n capture cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\left [ \\sigma_a (r, E) \\psi (r, E, \\Omega) - \\sigma_f (r, E) \\psi (r, E,\n \\Omega) \\right ]}{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega\n \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`CaptureXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(CaptureXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'capture'\n\n @property\n def scores(self):\n return ['flux', 'absorption', 'fission']\n\n @property\n def rxn_rate_tally(self):\n if self._rxn_rate_tally is None:\n self._rxn_rate_tally = \\\n self.tallies['absorption'] - self.tallies['fission']\n self._rxn_rate_tally.sparse = self.sparse\n return self._rxn_rate_tally\n\n\nclass FissionXS(MGXS):\n r\"\"\"A fission multi-group cross section.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group fission cross sections for multi-group neutronics\n calculations. At a minimum, one needs to set the\n :attr:`FissionXS.energy_groups` and :attr:`FissionXS.domain`\n properties. Tallies for the flux and appropriate reaction rates over the\n specified domain are generated automatically via the\n :attr:`FissionXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`FissionXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n fission cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\sigma_f (r, E) \\psi (r, E, \\Omega)}{\\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`FissionXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(FissionXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'fission'\n\n\nclass NuFissionXS(MGXS):\n r\"\"\"A fission neutron production multi-group cross section.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group fission neutron production cross sections for multi-group\n neutronics calculations. At a minimum, one needs to set the\n :attr:`NuFissionXS.energy_groups` and :attr:`NuFissionXS.domain`\n properties. Tallies for the flux and appropriate reaction rates over the\n specified domain are generated automatically via the\n :attr:`NuFissionXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`NuFissionXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n fission neutron production cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\nu\\sigma_f (r, E) \\psi (r, E, \\Omega)}{\\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`NuFissionXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(NuFissionXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'nu-fission'\n\n\nclass KappaFissionXS(MGXS):\n r\"\"\"A recoverable fission energy production rate multi-group cross section.\n\n The recoverable energy per fission, :math:`\\kappa`, is defined as the\n fission product kinetic energy, prompt and delayed neutron kinetic energies,\n prompt and delayed :math:`\\gamma`-ray total energies, and the total energy\n released by the delayed :math:`\\beta` particles. The neutrino energy does\n not contribute to this response. The prompt and delayed :math:`\\gamma`-rays\n are assumed to deposit their energy locally.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`KappaFissionXS.energy_groups` and\n :attr:`KappaFissionXS.domain` properties. Tallies for the flux and appropriate\n reaction rates over the specified domain are generated automatically via the\n :attr:`KappaFissionXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`KappaFissionXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n recoverable fission energy production rate cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\kappa\\sigma_f (r, E) \\psi (r, E, \\Omega)}{\\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`KappaFissionXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(KappaFissionXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'kappa-fission'\n\n\nclass ScatterXS(MGXS):\n r\"\"\"A scattering multi-group cross section.\n\n The scattering cross section is defined as the difference between the total\n and absorption cross sections.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`ScatterXS.energy_groups` and\n :attr:`ScatterXS.domain` properties. Tallies for the flux and\n appropriate reaction rates over the specified domain are generated\n automatically via the :attr:`ScatterXS.tallies` property, which can\n then be appended to a :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`ScatterXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n scattering cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\left [ \\sigma_t (r, E) \\psi (r, E, \\Omega) - \\sigma_a (r, E) \\psi (r, E,\n \\Omega) \\right ]}{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega\n \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`ScatterXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(ScatterXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'scatter'\n\n\nclass NuScatterXS(MGXS):\n r\"\"\"A scattering neutron production multi-group cross section.\n\n The neutron production from scattering is defined as the average number of\n neutrons produced from all neutron-producing reactions except for fission.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`NuScatterXS.energy_groups` and\n :attr:`NuScatterXS.domain` properties. Tallies for the flux and appropriate\n reaction rates over the specified domain are generated automatically via the\n :attr:`NuScatterXS.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`NuScatterXS.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n scattering neutron production cross section is calculated as:\n\n .. math::\n\n \\frac{\\int_{r \\in V} dr \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\;\n \\sum_i \\upsilon_i \\sigma_i (r, E) \\psi (r, E, \\Omega)}{\\int_{r \\in V} dr\n \\int_{4\\pi} d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega)}.\n\n where :math:`\\upsilon_i` is the multiplicity of the :math:`i`-th scattering\n reaction.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`NuScatterXS.tally_keys` property and\n values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(NuScatterXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'nu-scatter'\n\n @property\n def estimator(self):\n return 'analog'\n\n\nclass ScatterMatrixXS(MatrixMGXS):\n r\"\"\"A scattering matrix multi-group cross section for one or more Legendre\n moments.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`ScatterMatrixXS.energy_groups` and\n :attr:`ScatterMatrixXS.domain` properties. Tallies for the flux and\n appropriate reaction rates over the specified domain are generated\n automatically via the :attr:`ScatterMatrixXS.tallies` property, which can\n then be appended to a :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`ScatterMatrixXS.xs_tally` property.\n\n For a spatial domain :math:`V`, incoming energy group\n :math:`[E_{g'},E_{g'-1}]`, and outgoing energy group :math:`[E_g,E_{g-1}]`,\n the scattering moments are calculated as:\n\n .. math::\n\n \\langle \\sigma_{s,\\ell,g'\\rightarrow g} \\phi \\rangle &= \\int_{r \\in V} dr\n \\int_{4\\pi} d\\Omega' \\int_{E_{g'}}^{E_{g'-1}} dE' \\int_{4\\pi} d\\Omega\n \\int_{E_g}^{E_{g-1}} dE \\; P_\\ell (\\Omega \\cdot \\Omega') \\sigma_s (r, E'\n \\rightarrow E, \\Omega' \\cdot \\Omega) \\psi(r, E', \\Omega')\\\\\n \\langle \\phi \\rangle &= \\int_{r \\in V} dr \\int_{4\\pi} d\\Omega\n \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega) \\\\\n \\sigma_{s,\\ell,g'\\rightarrow g} &= \\frac{\\langle\n \\sigma_{s,\\ell,g'\\rightarrow g} \\phi \\rangle}{\\langle \\phi \\rangle}\n\n If the order is zero and a :math:`P_0` transport-correction is applied\n (default), the scattering matrix elements are:\n\n .. math::\n\n \\sigma_{s,g'\\rightarrow g} = \\frac{\\langle \\sigma_{s,0,g'\\rightarrow g}\n \\phi \\rangle - \\delta_{gg'} \\sum_{g''} \\langle \\sigma_{s,1,g''\\rightarrow\n g} \\phi \\rangle}{\\langle \\phi \\rangle}\n\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n correction : 'P0' or None\n Apply the P0 correction to scattering matrices if set to 'P0'\n legendre_order : int\n The highest Legendre moment in the scattering matrix (default is 0)\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`ScatterMatrixXS.tally_keys` property\n and values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(ScatterMatrixXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'scatter'\n self._correction = 'P0'\n self._legendre_order = 0\n self._hdf5_key = 'scatter matrix'\n\n def __deepcopy__(self, memo):\n clone = super(ScatterMatrixXS, self).__deepcopy__(memo)\n clone._correction = self.correction\n clone._legendre_order = self.legendre_order\n return clone\n\n @property\n def correction(self):\n return self._correction\n\n @property\n def legendre_order(self):\n return self._legendre_order\n\n @property\n def scores(self):\n scores = ['flux']\n\n if self.correction == 'P0' and self.legendre_order == 0:\n scores += ['{}-0'.format(self.rxn_type),\n '{}-1'.format(self.rxn_type)]\n else:\n scores += ['{}-P{}'.format(self.rxn_type, self.legendre_order)]\n\n return scores\n\n @property\n def filters(self):\n group_edges = self.energy_groups.group_edges\n energy = openmc.Filter('energy', group_edges)\n energyout = openmc.Filter('energyout', group_edges)\n\n if self.correction == 'P0' and self.legendre_order == 0:\n filters = [[energy], [energy, energyout], [energyout]]\n else:\n filters = [[energy], [energy, energyout]]\n\n return filters\n\n @property\n def rxn_rate_tally(self):\n\n if self._rxn_rate_tally is None:\n\n # If using P0 correction subtract scatter-1 from the diagonal\n if self.correction == 'P0' and self.legendre_order == 0:\n scatter_p0 = self.tallies['{}-0'.format(self.rxn_type)]\n scatter_p1 = self.tallies['{}-1'.format(self.rxn_type)]\n energy_filter = scatter_p0.find_filter('energy')\n energy_filter = copy.deepcopy(energy_filter)\n scatter_p1 = scatter_p1.diagonalize_filter(energy_filter)\n self._rxn_rate_tally = scatter_p0 - scatter_p1\n\n # Extract scattering moment reaction rate Tally\n else:\n tally_key = '{}-P{}'.format(self.rxn_type, self.legendre_order)\n self._rxn_rate_tally = self.tallies[tally_key]\n\n self._rxn_rate_tally.sparse = self.sparse\n\n return self._rxn_rate_tally\n\n @correction.setter\n def correction(self, correction):\n cv.check_value('correction', correction, ('P0', None))\n\n if correction == 'P0' and self.legendre_order > 0:\n msg = 'The P0 correction will be ignored since the scattering ' \\\n 'order {} is greater than zero'.format(self.legendre_order)\n warnings.warn(msg)\n\n self._correction = correction\n\n @legendre_order.setter\n def legendre_order(self, legendre_order):\n cv.check_type('legendre_order', legendre_order, Integral)\n cv.check_greater_than('legendre_order', legendre_order, 0, equality=True)\n cv.check_less_than('legendre_order', legendre_order, 10, equality=True)\n\n if self.correction == 'P0' and legendre_order > 0:\n msg = 'The P0 correction will be ignored since the scattering ' \\\n 'order {} is greater than zero'.format(self.legendre_order)\n warnings.warn(msg, RuntimeWarning)\n self.correction = None\n\n self._legendre_order = legendre_order\n\n def load_from_statepoint(self, statepoint):\n \"\"\"Extracts tallies in an OpenMC StatePoint with the data needed to\n compute multi-group cross sections.\n\n This method is needed to compute cross section data from tallies\n in an OpenMC StatePoint object.\n\n NOTE: The statepoint must first be linked with an OpenMC Summary object.\n\n Parameters\n ----------\n statepoint : openmc.StatePoint\n An OpenMC StatePoint object with tally data\n\n Raises\n ------\n ValueError\n When this method is called with a statepoint that has not been\n linked with a summary object.\n\n \"\"\"\n\n # Clear any tallies previously loaded from a statepoint\n if self.loaded_sp:\n self._tallies = None\n self._xs_tally = None\n self._rxn_rate_tally = None\n self._loaded_sp = False\n\n # Expand scores to match the format in the statepoint\n # e.g., \"scatter-P2\" -> \"scatter-0\", \"scatter-1\", \"scatter-2\"\n if self.correction != 'P0' or self.legendre_order != 0:\n tally_key = '{}-P{}'.format(self.rxn_type, self.legendre_order)\n self.tallies[tally_key].scores = \\\n [self.rxn_type + '-{}'.format(i) for i in range(self.legendre_order+1)]\n\n super(ScatterMatrixXS, self).load_from_statepoint(statepoint)\n\n def get_slice(self, nuclides=[], in_groups=[], out_groups=[],\n legendre_order='same'):\n \"\"\"Build a sliced ScatterMatrix for the specified nuclides and\n energy groups.\n\n This method constructs a new MGXS to encapsulate a subset of the data\n represented by this MGXS. The subset of data to include in the tally\n slice is determined by the nuclides and energy groups specified in\n the input parameters.\n\n Parameters\n ----------\n nuclides : list of str\n A list of nuclide name strings\n (e.g., ['U-235', 'U-238']; default is [])\n in_groups : list of int\n A list of incoming energy group indices starting at 1 for the high\n energies (e.g., [1, 2, 3]; default is [])\n out_groups : list of int\n A list of outgoing energy group indices starting at 1 for the high\n energies (e.g., [1, 2, 3]; default is [])\n legendre_order : int or 'same'\n The highest Legendre moment in the sliced MGXS. If order is 'same'\n then the sliced MGXS will have the same Legendre moments as the\n original MGXS (default). If order is an integer less than the\n original MGXS' order, then only those Legendre moments up to that\n order will be included in the sliced MGXS.\n\n Returns\n -------\n openmc.mgxs.MatrixMGXS\n A new MatrixMGXS which encapsulates the subset of data requested\n for the nuclide(s) and/or energy group(s) requested in the\n parameters.\n\n \"\"\"\n\n # Call super class method and null out derived tallies\n slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, in_groups)\n slice_xs._rxn_rate_tally = None\n slice_xs._xs_tally = None\n\n # Slice the Legendre order if needed\n if legendre_order != 'same':\n cv.check_type('legendre_order', legendre_order, Integral)\n cv.check_less_than('legendre_order', legendre_order,\n self.legendre_order, equality=True)\n slice_xs.legendre_order = legendre_order\n\n # Slice the scattering tally\n tally_key = '{}-P{}'.format(self.rxn_type, self.legendre_order)\n expand_scores = \\\n [self.rxn_type + '-{}'.format(i) for i in range(self.legendre_order+1)]\n slice_xs.tallies[tally_key] = \\\n slice_xs.tallies[tally_key].get_slice(scores=expand_scores)\n\n # Slice outgoing energy groups if needed\n if len(out_groups) != 0:\n filter_bins = []\n for group in out_groups:\n group_bounds = self.energy_groups.get_group_bounds(group)\n filter_bins.append(group_bounds)\n filter_bins = [tuple(filter_bins)]\n\n # Slice each of the tallies across energyout groups\n for tally_type, tally in slice_xs.tallies.items():\n if tally.contains_filter('energyout'):\n tally_slice = tally.get_slice(filters=['energyout'],\n filter_bins=filter_bins)\n slice_xs.tallies[tally_type] = tally_slice\n\n slice_xs.sparse = self.sparse\n return slice_xs\n\n def get_xs(self, in_groups='all', out_groups='all',\n subdomains='all', nuclides='all', moment='all',\n xs_type='macro', order_groups='increasing',\n row_column='inout', value='mean', **kwargs):\n r\"\"\"Returns an array of multi-group cross sections.\n\n This method constructs a 2D NumPy array for the requested scattering\n matrix data data for one or more energy groups and subdomains.\n\n NOTE: The scattering moments are not multiplied by the :math:`(2l+1)/2`\n prefactor in the expansion of the scattering source into Legendre\n moments in the neutron transport equation.\n\n Parameters\n ----------\n in_groups : Iterable of Integral or 'all'\n Incoming energy groups of interest. Defaults to 'all'.\n out_groups : Iterable of Integral or 'all'\n Outgoing energy groups of interest. Defaults to 'all'.\n subdomains : Iterable of Integral or 'all'\n Subdomain IDs of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n A list of nuclide name strings (e.g., ['U-235', 'U-238']). The\n special string 'all' will return the cross sections for all nuclides\n in the spatial domain. The special string 'sum' will return the\n cross section summed over all nuclides. Defaults to 'all'.\n moment : int or 'all'\n The scattering matrix moment to return. All moments will be\n returned if the moment is 'all' (default); otherwise, a specific\n moment will be returned.\n xs_type: {'macro', 'micro'}\n Return the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n order_groups: {'increasing', 'decreasing'}\n Return the cross section indexed according to increasing or\n decreasing energy groups (decreasing or increasing energies).\n Defaults to 'increasing'.\n row_column: {'inout', 'outin'}\n Return the cross section indexed first by incoming group and\n second by outgoing group ('inout'), or vice versa ('outin').\n Defaults to 'inout'.\n value : {'mean', 'std_dev', 'rel_err'}\n A string for the type of value to return. Defaults to 'mean'.\n\n Returns\n -------\n ndarray\n A NumPy array of the multi-group cross section indexed in the order\n each group and subdomain is listed in the parameters.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n cv.check_value('value', value, ['mean', 'std_dev', 'rel_err'])\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n filters = []\n filter_bins = []\n\n # Construct a collection of the domain filter bins\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=2)\n for subdomain in subdomains:\n filters.append(self.domain_type)\n filter_bins.append((subdomain,))\n\n # Construct list of energy group bounds tuples for all requested groups\n if not isinstance(in_groups, basestring):\n cv.check_iterable_type('groups', in_groups, Integral)\n for group in in_groups:\n filters.append('energy')\n filter_bins.append((self.energy_groups.get_group_bounds(group),))\n\n # Construct list of energy group bounds tuples for all requested groups\n if not isinstance(out_groups, basestring):\n cv.check_iterable_type('groups', out_groups, Integral)\n for group in out_groups:\n filters.append('energyout')\n filter_bins.append((self.energy_groups.get_group_bounds(group),))\n\n # Construct CrossScore for requested scattering moment\n if moment != 'all':\n cv.check_type('moment', moment, Integral)\n cv.check_greater_than('moment', moment, 0, equality=True)\n cv.check_less_than(\n 'moment', moment, self.legendre_order, equality=True)\n scores = [self.xs_tally.scores[moment]]\n else:\n scores = []\n\n # Construct a collection of the nuclides to retrieve from the xs tally\n if self.by_nuclide:\n if nuclides == 'all' or nuclides == 'sum' or nuclides == ['sum']:\n query_nuclides = self.get_all_nuclides()\n else:\n query_nuclides = nuclides\n else:\n query_nuclides = ['total']\n\n # Use tally summation if user requested the sum for all nuclides\n if nuclides == 'sum' or nuclides == ['sum']:\n xs_tally = self.xs_tally.summation(nuclides=query_nuclides)\n xs = xs_tally.get_values(scores=scores, filters=filters,\n filter_bins=filter_bins, value=value)\n else:\n xs = self.xs_tally.get_values(scores=scores, filters=filters,\n filter_bins=filter_bins,\n nuclides=query_nuclides, value=value)\n\n xs = np.nan_to_num(xs)\n\n # Divide by atom number densities for microscopic cross sections\n if xs_type == 'micro':\n if self.by_nuclide:\n densities = self.get_nuclide_densities(nuclides)\n else:\n densities = self.get_nuclide_densities('sum')\n if value == 'mean' or value == 'std_dev':\n xs /= densities[np.newaxis, :, np.newaxis]\n\n # Reverse data if user requested increasing energy groups since\n # tally data is stored in order of increasing energies\n if order_groups == 'increasing':\n if in_groups == 'all':\n num_in_groups = self.num_groups\n else:\n num_in_groups = len(in_groups)\n if out_groups == 'all':\n num_out_groups = self.num_groups\n else:\n num_out_groups = len(out_groups)\n\n # Reshape tally data array with separate axes for domain and energy\n num_subdomains = int(xs.shape[0] / (num_in_groups * num_out_groups))\n new_shape = (num_subdomains, num_in_groups, num_out_groups)\n new_shape += xs.shape[1:]\n xs = np.reshape(xs, new_shape)\n\n # Transpose the scattering matrix if requested by user\n if row_column == 'outin':\n xs = np.swapaxes(xs, 1, 2)\n\n # Reverse energies to align with increasing energy groups\n xs = xs[:, ::-1, ::-1, :]\n\n # Eliminate trivial dimensions\n xs = np.squeeze(xs)\n xs = np.atleast_2d(xs)\n\n return xs\n\n def get_pandas_dataframe(self, groups='all', nuclides='all', moment='all',\n xs_type='macro', distribcell_paths=True):\n \"\"\"Build a Pandas DataFrame for the MGXS data.\n\n This method leverages :meth:`openmc.Tally.get_pandas_dataframe`, but\n renames the columns with terminology appropriate for cross section data.\n\n Parameters\n ----------\n groups : Iterable of Integral or 'all'\n Energy groups of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the dataframe. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will include the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will\n include the cross sections summed over all nuclides. Defaults\n to 'all'.\n moment : int or 'all'\n The scattering matrix moment to return. All moments will be\n returned if the moment is 'all' (default); otherwise, a specific\n moment will be returned.\n xs_type: {'macro', 'micro'}\n Return macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n distribcell_paths : bool, optional\n Construct columns for distribcell tally filters (default is True).\n The geometric information in the Summary object is embedded into a\n Multi-index column with a geometric \"path\" to each distribcell\n instance.\n\n Returns\n -------\n pandas.DataFrame\n A Pandas DataFrame for the cross section data.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n df = super(ScatterMatrixXS, self).get_pandas_dataframe(\n groups, nuclides, xs_type, distribcell_paths)\n\n # Add a moment column to dataframe\n if self.legendre_order > 0:\n # Insert a column corresponding to the Legendre moments\n moments = ['P{}'.format(i) for i in range(self.legendre_order+1)]\n moments = np.tile(moments, df.shape[0] / len(moments))\n df['moment'] = moments\n\n # Place the moment column before the mean column\n mean_index = df.columns.get_loc('mean')\n columns = df.columns.tolist()\n df = df[columns[:mean_index] + ['moment'] + columns[mean_index:-1]]\n\n # Select rows corresponding to requested scattering moment\n if moment != 'all':\n cv.check_type('moment', moment, Integral)\n cv.check_greater_than('moment', moment, 0, equality=True)\n cv.check_less_than(\n 'moment', moment, self.legendre_order, equality=True)\n df = df[df['moment'] == 'P{}'.format(moment)]\n\n return df\n\n def print_xs(self, subdomains='all', nuclides='all',\n xs_type='macro', moment=0):\n \"\"\"Prints a string representation for the multi-group cross section.\n\n Parameters\n ----------\n subdomains : Iterable of Integral or 'all'\n The subdomain IDs of the cross sections to include in the report.\n Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the report. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will report the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will report\n the cross sections summed over all nuclides. Defaults to 'all'.\n xs_type: {'macro', 'micro'}\n Return the macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n moment : int\n The scattering moment to print (default is 0)\n\n \"\"\"\n\n # Construct a collection of the subdomains to report\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral)\n elif self.domain_type == 'distribcell':\n subdomains = np.arange(self.num_subdomains, dtype=np.int)\n else:\n subdomains = [self.domain.id]\n\n # Construct a collection of the nuclides to report\n if self.by_nuclide:\n if nuclides == 'all':\n nuclides = self.get_all_nuclides()\n if nuclides == 'sum':\n nuclides = ['sum']\n else:\n cv.check_iterable_type('nuclides', nuclides, basestring)\n else:\n nuclides = ['sum']\n\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n if self.correction != 'P0':\n rxn_type = '{0} (P{1})'.format(self.rxn_type, moment)\n else:\n rxn_type = self.rxn_type\n\n # Build header for string with type and domain info\n string = 'Multi-Group XS\\n'\n string += '{0: <16}=\\t{1}\\n'.format('\\tReaction Type', rxn_type)\n string += '{0: <16}=\\t{1}\\n'.format('\\tDomain Type', self.domain_type)\n string += '{0: <16}=\\t{1}\\n'.format('\\tDomain ID', self.domain.id)\n\n # If cross section data has not been computed, only print string header\n if self.tallies is None:\n print(string)\n return\n\n string += '{0: <16}\\n'.format('\\tEnergy Groups:')\n template = '{0: <12}Group {1} [{2: <10} - {3: <10}MeV]\\n'\n\n # Loop over energy groups ranges\n for group in range(1, self.num_groups + 1):\n bounds = self.energy_groups.get_group_bounds(group)\n string += template.format('', group, bounds[0], bounds[1])\n\n # Loop over all subdomains\n for subdomain in subdomains:\n\n if self.domain_type == 'distribcell':\n string += \\\n '{0: <16}=\\t{1}\\n'.format('\\tSubdomain', subdomain)\n\n # Loop over all Nuclides\n for nuclide in nuclides:\n\n # Build header for nuclide type\n if xs_type != 'sum':\n string += '{0: <16}=\\t{1}\\n'.format('\\tNuclide', nuclide)\n\n # Build header for cross section type\n if xs_type == 'macro':\n string += '{0: <16}\\n'.format('\\tCross Sections [cm^-1]:')\n else:\n string += '{0: <16}\\n'.format('\\tCross Sections [barns]:')\n\n template = '{0: <12}Group {1} -> Group {2}:\\t\\t'\n\n # Loop over incoming/outgoing energy groups ranges\n for in_group in range(1, self.num_groups + 1):\n for out_group in range(1, self.num_groups + 1):\n string += template.format('', in_group, out_group)\n average = \\\n self.get_xs([in_group], [out_group],\n [subdomain], [nuclide], moment=moment,\n xs_type=xs_type, value='mean')\n rel_err = \\\n self.get_xs([in_group], [out_group],\n [subdomain], [nuclide], moment=moment,\n xs_type=xs_type, value='rel_err')\n average = average.flatten()[0]\n rel_err = rel_err.flatten()[0] * 100.\n string += '{:1.2e} +/- {:1.2e}%'.format(average,\n rel_err)\n string += '\\n'\n string += '\\n'\n string += '\\n'\n string += '\\n'\n\n print(string)\n\n\nclass NuScatterMatrixXS(ScatterMatrixXS):\n \"\"\"A scattering production matrix multi-group cross section for one or\n more Legendre moments.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`NuScatterMatrixXS.energy_groups` and\n :attr:`NuScatterMatrixXS.domain` properties. Tallies for the flux and\n appropriate reaction rates over the specified domain are generated\n automatically via the :attr:`NuScatterMatrixXS.tallies` property, which can\n then be appended to a :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`NuScatterMatrixXS.xs_tally` property.\n\n The calculation of the scattering-production matrix is the same as that for\n :class:`ScatterMatrixXS` except that the scattering multiplicity is\n accounted for.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n correction : 'P0' or None\n Apply the P0 correction to scattering matrices if set to 'P0'\n legendre_order : int\n The highest legendre moment in the scattering matrix (default is 0)\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`NuScatterMatrixXS.tally_keys` property\n and values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(NuScatterMatrixXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'nu-scatter'\n self._hdf5_key = 'nu-scatter matrix'\n\n\nclass MultiplicityMatrixXS(MatrixMGXS):\n r\"\"\"The scattering multiplicity matrix.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`MultiplicityMatrixXS.energy_groups` and\n :attr:`MultiplicityMatrixXS.domain` properties. Tallies for the flux and\n appropriate reaction rates over the specified domain are generated\n automatically via the :attr:`MultiplicityMatrixXS.tallies` property, which\n can then be appended to a :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`MultiplicityMatrixXS.xs_tally`\n property.\n\n For a spatial domain :math:`V`, incoming energy group\n :math:`[E_{g'},E_{g'-1}]`, and outgoing energy group :math:`[E_g,E_{g-1}]`,\n the multiplicity is calculated as:\n\n .. math::\n\n \\langle \\upsilon \\sigma_{s,g'\\rightarrow g} \\phi \\rangle &= \\int_{r \\in\n D} dr \\int_{4\\pi} d\\Omega' \\int_{E_{g'}}^{E_{g'-1}} dE' \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\sum_i \\upsilon_i \\sigma_i (r, E' \\rightarrow\n E, \\Omega' \\cdot \\Omega) \\psi(r, E', \\Omega') \\\\\n \\langle \\sigma_{s,g'\\rightarrow g} \\phi \\rangle &= \\int_{r \\in\n D} dr \\int_{4\\pi} d\\Omega' \\int_{E_{g'}}^{E_{g'-1}} dE' \\int_{4\\pi}\n d\\Omega \\int_{E_g}^{E_{g-1}} dE \\; \\sum_i \\upsilon_i \\sigma_i (r, E' \\rightarrow\n E, \\Omega' \\cdot \\Omega) \\psi(r, E', \\Omega') \\\\\n \\upsilon_{g'\\rightarrow g} &= \\frac{\\langle \\upsilon\n \\sigma_{s,g'\\rightarrow g} \\rangle}{\\langle \\sigma_{s,g'\\rightarrow g}\n \\rangle}\n\n where :math:`\\upsilon_i` is the multiplicity for the :math:`i`-th reaction.\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`MultiplicityMatrixXS.tally_keys`\n property and values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(MultiplicityMatrixXS, self).__init__(domain, domain_type, groups,\n by_nuclide, name)\n self._rxn_type = 'multiplicity matrix'\n\n @property\n def scores(self):\n scores = ['nu-scatter', 'scatter']\n return scores\n\n @property\n def filters(self):\n # Create the non-domain specific Filters for the Tallies\n group_edges = self.energy_groups.group_edges\n energy = openmc.Filter('energy', group_edges)\n energyout = openmc.Filter('energyout', group_edges)\n\n return [[energy, energyout], [energy, energyout]]\n\n @property\n def rxn_rate_tally(self):\n if self._rxn_rate_tally is None:\n self._rxn_rate_tally = self.tallies['nu-scatter']\n self._rxn_rate_tally.sparse = self.sparse\n return self._rxn_rate_tally\n\n @property\n def xs_tally(self):\n\n if self._xs_tally is None:\n scatter = self.tallies['scatter']\n\n # Compute the multiplicity\n self._xs_tally = self.rxn_rate_tally / scatter\n super(MultiplicityMatrixXS, self)._compute_xs()\n\n return self._xs_tally\n\n\nclass NuFissionMatrixXS(MatrixMGXS):\n r\"\"\"A fission production matrix multi-group cross section.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`NuFissionMatrixXS.energy_groups` and\n :attr:`NuFissionMatrixXS.domain` properties. Tallies for the flux and\n appropriate reaction rates over the specified domain are generated\n automatically via the :attr:`NuFissionMatrixXS.tallies` property, which can\n then be appended to a :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`NuFissionMatrixXS.xs_tally` property.\n\n For a spatial domain :math:`V`, incoming energy group\n :math:`[E_{g'},E_{g'-1}]`, and outgoing energy group :math:`[E_g,E_{g-1}]`,\n the fission production is calculated as:\n\n .. math::\n\n \\langle \\nu\\sigma_{f,g'\\rightarrow g} \\phi \\rangle &= \\int_{r \\in V} dr\n \\int_{4\\pi} d\\Omega' \\int_{E_{g'}}^{E_{g'-1}} dE' \\int_{E_g}^{E_{g-1}} dE\n \\; \\chi(E) \\nu\\sigma_f (r, E') \\psi(r, E', \\Omega')\\\\\n \\langle \\phi \\rangle &= \\int_{r \\in V} dr \\int_{4\\pi} d\\Omega\n \\int_{E_g}^{E_{g-1}} dE \\; \\psi (r, E, \\Omega) \\\\\n \\nu\\sigma_{f,g'\\rightarrow g} &= \\frac{\\langle \\nu\\sigma_{f,g'\\rightarrow\n g} \\phi \\rangle}{\\langle \\phi \\rangle}\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`NuFissionMatrixXS.tally_keys`\n property and values are instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(NuFissionMatrixXS, self).__init__(domain, domain_type,\n groups, by_nuclide, name)\n self._rxn_type = 'nu-fission'\n self._hdf5_key = 'nu-fission matrix'\n\n\nclass Chi(MGXS):\n r\"\"\"The fission spectrum.\n\n This class can be used for both OpenMC input generation and tally data\n post-processing to compute spatially-homogenized and energy-integrated\n multi-group cross sections for multi-group neutronics calculations. At a\n minimum, one needs to set the :attr:`Chi.energy_groups` and\n :attr:`Chi.domain` properties. Tallies for the flux and appropriate reaction\n rates over the specified domain are generated automatically via the\n :attr:`Chi.tallies` property, which can then be appended to a\n :class:`openmc.Tallies` instance.\n\n For post-processing, the :meth:`MGXS.load_from_statepoint` will pull in the\n necessary data to compute multi-group cross sections from a\n :class:`openmc.StatePoint` instance. The derived multi-group cross section\n can then be obtained from the :attr:`Chi.xs_tally` property.\n\n For a spatial domain :math:`V` and energy group :math:`[E_g,E_{g-1}]`, the\n fission spectrum is calculated as:\n\n .. math::\n\n \\langle \\nu\\sigma_{f,\\rightarrow g} \\phi \\rangle &= \\int_{r \\in V} dr\n \\int_{4\\pi} d\\Omega' \\int_0^\\infty dE' \\int_{E_g}^{E_{g-1}} dE \\; \\chi(E)\n \\nu\\sigma_f (r, E') \\psi(r, E', \\Omega')\\\\\n \\langle \\nu\\sigma_f \\phi \\rangle &= \\int_{r \\in V} dr \\int_{4\\pi}\n d\\Omega' \\int_0^\\infty dE' \\int_0^\\infty dE \\; \\chi(E) \\nu\\sigma_f (r,\n E') \\psi(r, E', \\Omega') \\\\\n \\chi_g &= \\frac{\\langle \\nu\\sigma_{f,\\rightarrow g} \\phi \\rangle}{\\langle\n \\nu\\sigma_f \\phi \\rangle}\n\n Parameters\n ----------\n domain : openmc.Material or openmc.Cell or openmc.Universe\n The domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n The domain type for spatial homogenization\n groups : openmc.mgxs.EnergyGroups\n The energy group structure for energy condensation\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n name : str, optional\n Name of the multi-group cross section. Used as a label to identify\n tallies in OpenMC 'tallies.xml' file.\n\n Attributes\n ----------\n name : str, optional\n Name of the multi-group cross section\n rxn_type : str\n Reaction type (e.g., 'total', 'nu-fission', etc.)\n by_nuclide : bool\n If true, computes cross sections for each nuclide in domain\n domain : Material or Cell or Universe\n Domain for spatial homogenization\n domain_type : {'material', 'cell', 'distribcell', 'universe'}\n Domain type for spatial homogenization\n energy_groups : openmc.mgxs.EnergyGroups\n Energy group structure for energy condensation\n tally_trigger : openmc.Trigger\n An (optional) tally precision trigger given to each tally used to\n compute the cross section\n scores : list of str\n The scores in each tally used to compute the multi-group cross section\n filters : list of openmc.Filter\n The filters in each tally used to compute the multi-group cross section\n tally_keys : list of str\n The keys into the tallies dictionary for each tally used to compute\n the multi-group cross section\n estimator : {'tracklength', 'analog'}\n The tally estimator used to compute the multi-group cross section\n tallies : collections.OrderedDict\n OpenMC tallies needed to compute the multi-group cross section. The keys\n are strings listed in the :attr:`Chi.tally_keys` property and values are\n instances of :class:`openmc.Tally`.\n rxn_rate_tally : openmc.Tally\n Derived tally for the reaction rate tally used in the numerator to\n compute the multi-group cross section. This attribute is None\n unless the multi-group cross section has been computed.\n xs_tally : openmc.Tally\n Derived tally for the multi-group cross section. This attribute\n is None unless the multi-group cross section has been computed.\n num_subdomains : int\n The number of subdomains is unity for 'material', 'cell' and 'universe'\n domain types. When the This is equal to the number of cell instances\n for 'distribcell' domain types (it is equal to unity prior to loading\n tally data from a statepoint file).\n num_nuclides : int\n The number of nuclides for which the multi-group cross section is\n being tracked. This is unity if the by_nuclide attribute is False.\n nuclides : Iterable of str or 'sum'\n The optional user-specified nuclides for which to compute cross\n sections (e.g., 'U-238', 'O-16'). If by_nuclide is True but nuclides\n are not specified by the user, all nuclides in the spatial domain\n are included. This attribute is 'sum' if by_nuclide is false.\n sparse : bool\n Whether or not the MGXS' tallies use SciPy's LIL sparse matrix format\n for compressed data storage\n loaded_sp : bool\n Whether or not a statepoint file has been loaded with tally data\n derived : bool\n Whether or not the MGXS is merged from one or more other MGXS\n hdf5_key : str\n The key used to index multi-group cross sections in an HDF5 data store\n\n \"\"\"\n\n def __init__(self, domain=None, domain_type=None,\n groups=None, by_nuclide=False, name=''):\n super(Chi, self).__init__(domain, domain_type, groups, by_nuclide, name)\n self._rxn_type = 'chi'\n\n @property\n def scores(self):\n return ['nu-fission', 'nu-fission']\n\n @property\n def filters(self):\n # Create the non-domain specific Filters for the Tallies\n group_edges = self.energy_groups.group_edges\n energyout = openmc.Filter('energyout', group_edges)\n energyin = openmc.Filter('energy', [group_edges[0], group_edges[-1]])\n return [[energyin], [energyout]]\n\n @property\n def tally_keys(self):\n return ['nu-fission-in', 'nu-fission-out']\n\n @property\n def estimator(self):\n return 'analog'\n\n @property\n def rxn_rate_tally(self):\n if self._rxn_rate_tally is None:\n self._rxn_rate_tally = self.tallies['nu-fission-out']\n self._rxn_rate_tally.sparse = self.sparse\n return self._rxn_rate_tally\n\n @property\n def xs_tally(self):\n\n if self._xs_tally is None:\n nu_fission_in = self.tallies['nu-fission-in']\n\n # Remove coarse energy filter to keep it out of tally arithmetic\n energy_filter = nu_fission_in.find_filter('energy')\n nu_fission_in.remove_filter(energy_filter)\n\n # Compute chi\n self._xs_tally = self.rxn_rate_tally / nu_fission_in\n super(Chi, self)._compute_xs()\n\n # Add the coarse energy filter back to the nu-fission tally\n nu_fission_in.filters.append(energy_filter)\n\n return self._xs_tally\n\n def get_slice(self, nuclides=[], groups=[]):\n \"\"\"Build a sliced Chi for the specified nuclides and energy groups.\n\n This method constructs a new MGXS to encapsulate a subset of the data\n represented by this MGXS. The subset of data to include in the tally\n slice is determined by the nuclides and energy groups specified in\n the input parameters.\n\n Parameters\n ----------\n nuclides : list of str\n A list of nuclide name strings\n (e.g., ['U-235', 'U-238']; default is [])\n groups : list of Integral\n A list of energy group indices starting at 1 for the high energies\n (e.g., [1, 2, 3]; default is [])\n\n Returns\n -------\n openmc.mgxs.MGXS\n A new MGXS which encapsulates the subset of data requested\n for the nuclide(s) and/or energy group(s) requested in the\n parameters.\n\n \"\"\"\n\n # Temporarily remove energy filter from nu-fission-in since its\n # group structure will work in super MGXS.get_slice(...) method\n nu_fission_in = self.tallies['nu-fission-in']\n energy_filter = nu_fission_in.find_filter('energy')\n nu_fission_in.remove_filter(energy_filter)\n\n # Call super class method and null out derived tallies\n slice_xs = super(Chi, self).get_slice(nuclides, groups)\n slice_xs._rxn_rate_tally = None\n slice_xs._xs_tally = None\n\n # Slice energy groups if needed\n if len(groups) != 0:\n filter_bins = []\n for group in groups:\n group_bounds = self.energy_groups.get_group_bounds(group)\n filter_bins.append(group_bounds)\n filter_bins = [tuple(filter_bins)]\n\n # Slice nu-fission-out tally along energyout filter\n nu_fission_out = slice_xs.tallies['nu-fission-out']\n tally_slice = nu_fission_out.get_slice(filters=['energyout'],\n filter_bins=filter_bins)\n slice_xs._tallies['nu-fission-out'] = tally_slice\n\n # Add energy filter back to nu-fission-in tallies\n self.tallies['nu-fission-in'].add_filter(energy_filter)\n slice_xs._tallies['nu-fission-in'].add_filter(energy_filter)\n\n slice_xs.sparse = self.sparse\n return slice_xs\n\n def merge(self, other):\n \"\"\"Merge another Chi with this one\n\n If results have been loaded from a statepoint, then Chi are only\n mergeable along one and only one of energy groups or nuclides.\n\n Parameters\n ----------\n other : openmc.mgxs.MGXS\n MGXS to merge with this one\n\n Returns\n -------\n merged_mgxs : openmc.mgxs.MGXS\n Merged MGXS\n \"\"\"\n\n if not self.can_merge(other):\n raise ValueError('Unable to merge Chi')\n\n # Create deep copy of tally to return as merged tally\n merged_mgxs = copy.deepcopy(self)\n merged_mgxs._derived = True\n merged_mgxs._rxn_rate_tally = None\n merged_mgxs._xs_tally = None\n\n # Merge energy groups\n if self.energy_groups != other.energy_groups:\n merged_groups = self.energy_groups.merge(other.energy_groups)\n merged_mgxs.energy_groups = merged_groups\n\n # Merge nuclides\n if self.nuclides != other.nuclides:\n\n # The nuclides must be mutually exclusive\n for nuclide in self.nuclides:\n if nuclide in other.nuclides:\n msg = 'Unable to merge Chi with shared nuclides'\n raise ValueError(msg)\n\n # Concatenate lists of nuclides for the merged MGXS\n merged_mgxs.nuclides = self.nuclides + other.nuclides\n\n # Merge tallies\n for tally_key in self.tallies:\n merged_tally = self.tallies[tally_key].merge(other.tallies[tally_key])\n merged_mgxs.tallies[tally_key] = merged_tally\n\n return merged_mgxs\n\n def get_xs(self, groups='all', subdomains='all', nuclides='all',\n xs_type='macro', order_groups='increasing',\n value='mean', **kwargs):\n \"\"\"Returns an array of the fission spectrum.\n\n This method constructs a 2D NumPy array for the requested multi-group\n cross section data data for one or more energy groups and subdomains.\n\n Parameters\n ----------\n groups : Iterable of Integral or 'all'\n Energy groups of interest. Defaults to 'all'.\n subdomains : Iterable of Integral or 'all'\n Subdomain IDs of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n A list of nuclide name strings (e.g., ['U-235', 'U-238']). The\n special string 'all' will return the cross sections for all nuclides\n in the spatial domain. The special string 'sum' will return the\n cross section summed over all nuclides. Defaults to 'all'.\n xs_type: {'macro', 'micro'}\n This parameter is not relevant for chi but is included here to\n mirror the parent MGXS.get_xs(...) class method\n order_groups: {'increasing', 'decreasing'}\n Return the cross section indexed according to increasing or\n decreasing energy groups (decreasing or increasing energies).\n Defaults to 'increasing'.\n value : {'mean', 'std_dev', 'rel_err'}\n A string for the type of value to return. Defaults to 'mean'.\n\n Returns\n -------\n numpy.ndarray\n A NumPy array of the multi-group cross section indexed in the order\n each group, subdomain and nuclide is listed in the parameters.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n cv.check_value('value', value, ['mean', 'std_dev', 'rel_err'])\n cv.check_value('xs_type', xs_type, ['macro', 'micro'])\n\n filters = []\n filter_bins = []\n\n # Construct a collection of the domain filter bins\n if not isinstance(subdomains, basestring):\n cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=2)\n for subdomain in subdomains:\n filters.append(self.domain_type)\n filter_bins.append((subdomain,))\n\n # Construct list of energy group bounds tuples for all requested groups\n if not isinstance(groups, basestring):\n cv.check_iterable_type('groups', groups, Integral)\n for group in groups:\n filters.append('energyout')\n filter_bins.append((self.energy_groups.get_group_bounds(group),))\n\n # If chi was computed for each nuclide in the domain\n if self.by_nuclide:\n\n # Get the sum as the fission source weighted average chi for all\n # nuclides in the domain\n if nuclides == 'sum' or nuclides == ['sum']:\n\n # Retrieve the fission production tallies\n nu_fission_in = self.tallies['nu-fission-in']\n nu_fission_out = self.tallies['nu-fission-out']\n\n # Sum out all nuclides\n nuclides = self.get_all_nuclides()\n nu_fission_in = nu_fission_in.summation(nuclides=nuclides)\n nu_fission_out = nu_fission_out.summation(nuclides=nuclides)\n\n # Remove coarse energy filter to keep it out of tally arithmetic\n energy_filter = nu_fission_in.find_filter('energy')\n nu_fission_in.remove_filter(energy_filter)\n\n # Compute chi and store it as the xs_tally attribute so we can\n # use the generic get_xs(...) method\n xs_tally = nu_fission_out / nu_fission_in\n\n # Add the coarse energy filter back to the nu-fission tally\n nu_fission_in.filters.append(energy_filter)\n\n xs = xs_tally.get_values(filters=filters,\n filter_bins=filter_bins, value=value)\n\n # Get chi for all nuclides in the domain\n elif nuclides == 'all':\n nuclides = self.get_all_nuclides()\n xs = self.xs_tally.get_values(filters=filters,\n filter_bins=filter_bins,\n nuclides=nuclides, value=value)\n\n # Get chi for user-specified nuclides in the domain\n else:\n cv.check_iterable_type('nuclides', nuclides, basestring)\n xs = self.xs_tally.get_values(filters=filters,\n filter_bins=filter_bins,\n nuclides=nuclides, value=value)\n\n # If chi was computed as an average of nuclides in the domain\n else:\n xs = self.xs_tally.get_values(filters=filters,\n filter_bins=filter_bins, value=value)\n\n # Reverse data if user requested increasing energy groups since\n # tally data is stored in order of increasing energies\n if order_groups == 'increasing':\n\n # Reshape tally data array with separate axes for domain and energy\n if groups == 'all':\n num_groups = self.num_groups\n else:\n num_groups = len(groups)\n num_subdomains = int(xs.shape[0] / num_groups)\n new_shape = (num_subdomains, num_groups) + xs.shape[1:]\n xs = np.reshape(xs, new_shape)\n\n # Reverse energies to align with increasing energy groups\n xs = xs[:, ::-1, :]\n\n # Eliminate trivial dimensions\n xs = np.squeeze(xs)\n xs = np.atleast_1d(xs)\n\n xs = np.nan_to_num(xs)\n return xs\n\n def get_pandas_dataframe(self, groups='all', nuclides='all',\n xs_type='macro', distribcell_paths=False):\n \"\"\"Build a Pandas DataFrame for the MGXS data.\n\n This method leverages :meth:`openmc.Tally.get_pandas_dataframe`, but\n renames the columns with terminology appropriate for cross section data.\n\n Parameters\n ----------\n groups : Iterable of Integral or 'all'\n Energy groups of interest. Defaults to 'all'.\n nuclides : Iterable of str or 'all' or 'sum'\n The nuclides of the cross-sections to include in the dataframe. This\n may be a list of nuclide name strings (e.g., ['U-235', 'U-238']).\n The special string 'all' will include the cross sections for all\n nuclides in the spatial domain. The special string 'sum' will\n include the cross sections summed over all nuclides. Defaults to\n 'all'.\n xs_type: {'macro', 'micro'}\n Return macro or micro cross section in units of cm^-1 or barns.\n Defaults to 'macro'.\n distribcell_paths : bool, optional\n Construct columns for distribcell tally filters (default is True).\n The geometric information in the Summary object is embedded into\n a Multi-index column with a geometric \"path\" to each distribcell\n instance.\n\n Returns\n -------\n pandas.DataFrame\n A Pandas DataFrame for the cross section data.\n\n Raises\n ------\n ValueError\n When this method is called before the multi-group cross section is\n computed from tally data.\n\n \"\"\"\n\n # Build the dataframe using the parent class method\n df = super(Chi, self).get_pandas_dataframe(\n groups, nuclides, xs_type, distribcell_paths=distribcell_paths)\n\n # If user requested micro cross sections, multiply by the atom\n # densities to cancel out division made by the parent class method\n if xs_type == 'micro':\n if self.by_nuclide:\n densities = self.get_nuclide_densities(nuclides)\n else:\n densities = self.get_nuclide_densities('sum')\n tile_factor = df.shape[0] / len(densities)\n df['mean'] *= np.tile(densities, tile_factor)\n df['std. dev.'] *= np.tile(densities, tile_factor)\n\n return df\n" ]
[ [ "numpy.add.reduceat", "numpy.swapaxes", "numpy.allclose", "numpy.sqrt", "numpy.unique", "numpy.reshape", "numpy.arange", "numpy.squeeze", "numpy.nan_to_num", "numpy.tile", "numpy.atleast_1d", "numpy.atleast_2d", "numpy.repeat", "numpy.zeros", "numpy.where" ] ]
Kyumin-Park/CRAFT-pytorch
[ "d62ad78f94f98a52cb0828bd57fb9291964d221f" ]
[ "imgproc.py" ]
[ "\"\"\" \nCopyright (c) 2019-present NAVER Corp.\nMIT License\n\"\"\"\n\n# -*- coding: utf-8 -*-\nimport numpy as np\n# from skimage import io\nimport cv2\n\n\ndef loadImage(img_file):\n # img = io.imread(img_file) # RGB order\n img = cv2.imread(img_file)\n if img.shape[0] == 2:\n img = img[0]\n if len(img.shape) == 2:\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n else:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if img.shape[2] == 4:\n img = img[:, :, :3]\n img = np.array(img)\n assert len(img.shape) == 3 and img.shape[2] == 3\n return img\n\n\ndef normalizeMeanVariance(in_img, mean=(0.485, 0.456, 0.406), variance=(0.229, 0.224, 0.225)):\n # should be RGB order\n img = in_img.copy().astype(np.float32)\n\n img -= np.array([mean[0] * 255.0, mean[1] * 255.0, mean[2] * 255.0], dtype=np.float32)\n img /= np.array([variance[0] * 255.0, variance[1] * 255.0, variance[2] * 255.0], dtype=np.float32)\n return img\n\n\ndef denormalizeMeanVariance(in_img, mean=(0.485, 0.456, 0.406), variance=(0.229, 0.224, 0.225)):\n # should be RGB order\n img = in_img.copy()\n img *= variance\n img += mean\n img *= 255.0\n img = np.clip(img, 0, 255).astype(np.uint8)\n return img\n\n\ndef resize_aspect_ratio(img, square_size, interpolation, mag_ratio=1):\n height, width, channel = img.shape\n\n # magnify image size\n target_size = mag_ratio * max(height, width)\n\n # set original image size\n if target_size > square_size:\n target_size = square_size\n \n ratio = target_size / max(height, width) \n\n target_h, target_w = int(height * ratio), int(width * ratio)\n proc = cv2.resize(img, (target_w, target_h), interpolation=interpolation)\n\n # make canvas and paste image\n target_h32, target_w32 = target_h, target_w\n if target_h % 32 != 0:\n target_h32 = target_h + (32 - target_h % 32)\n if target_w % 32 != 0:\n target_w32 = target_w + (32 - target_w % 32)\n resized = np.zeros((target_h32, target_w32, channel), dtype=np.float32)\n resized[0:target_h, 0:target_w, :] = proc\n target_h, target_w = target_h32, target_w32\n\n size_heatmap = (int(target_w/2), int(target_h/2))\n\n return resized, ratio, size_heatmap\n\ndef fill_canvas(img, canvas_size):\n h, w, c = img.shape\n canvas = np.zeros((canvas_size, canvas_size, 3), dtype=img.dtype)\n canvas[:h, :w] = img\n\n return canvas\n\ndef cvt2HeatmapImg(img):\n img = (np.clip(img, 0, 1) * 255).astype(np.uint8)\n img = cv2.applyColorMap(img, cv2.COLORMAP_JET)\n return img\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.clip" ] ]
qzhao2018/samantha
[ "da422556d7dbf8de456c0078fc1950d686e4b559" ]
[ "tools/tensorflow/src/models/metrics_test.py" ]
[ "\nimport unittest\nimport random\nimport numpy as np\nimport tensorflow as tf\n\nfrom src.models.metrics import *\n\n\nclass MetricsTest(unittest.TestCase):\n\n def test_compute_map_metrics(self):\n graph = tf.Graph()\n with graph.as_default():\n session = tf.Session(graph=graph)\n with session.as_default():\n with tf.variable_scope('test1'):\n labels = tf.constant([2], dtype=tf.int64)\n preds = tf.constant([[0.01, 0.4, 0.1]])\n values, updates = compute_map_metrics(labels, preds, 'MAP@1,2')\n session.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n session.run(updates)\n maps = session.run(values)\n self.assertEqual(maps[0], 0.0)\n self.assertEqual(maps[1], 0.5)\n with tf.variable_scope('test2'):\n labels = tf.SparseTensor(\n tf.constant([[0, 2], [0, 5], [1, 0], [1, 2], [1, 4]], dtype=tf.int64),\n tf.constant([2, 3, 0, 7, 1], dtype=tf.int64),\n tf.constant([2, 6], dtype=tf.int64))\n preds = tf.constant([\n [0.3, 0.1, 0.9, 0.10, 0.2, 0.01, 0.003, 0.14],\n [0.01, 0.9, 0.1, 0.2, 0.38, 0.2, 0.48, 0.04]])\n values, updates = compute_map_metrics(labels, preds, 'MAP@1,7,8')\n session.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n session.run(updates)\n maps = session.run(values)\n self.assertAlmostEqual(maps[0], 1.000, delta=0.001)\n self.assertAlmostEqual(maps[1], 0.547, delta=0.001)\n self.assertAlmostEqual(maps[2], 0.610, delta=0.001)\n\n" ]
[ [ "tensorflow.Graph", "tensorflow.constant", "tensorflow.local_variables_initializer", "tensorflow.global_variables_initializer", "tensorflow.Session", "tensorflow.variable_scope" ] ]
lightsilver/asdae
[ "c751e4124e97082aa2aee2abd8bdf6528b910da1", "c751e4124e97082aa2aee2abd8bdf6528b910da1" ]
[ "tfrecords_train.py", "MLPrec.py" ]
[ "# -*- coding: utf8 -*-\nimport tensorflow as tf\nimport sys\nimport ast\nimport os\n\nfrom utils import *\nfrom MLPclassify import *\nfrom tfrecords_SDAE import *\nfrom readData import *\nimport kmeans\n\n# SDAE网络参数\nsdae_args = {\n \"noise\" : .1, # 噪声水平0-1.0\n \"n_nodes\" : (512, 256, 128), # 各DAE层节点数\n \"learning_rate\": (.0001, 0.001, 0.001), # 各层学习率\n \"n_epochs\" : (200, 150, 150), # 各层迭代次数\n \"rho\" :(0.05, 0.02, 0.02), # 各层稀疏水平\n \"data_dir\": './data/', # 数据存储和读取的路径\n \"batch_size\": 50, # batch_size\n \"reg_lambda\":0.0, # 正则化系数\n \"sparse_lambda\":1.0 # 稀疏项系数\n}\n\n# 用于检验无监督学习特征的分类网络,MLP\nmlp_args = {\n \"n_nodes\" : (80,),\n \"learning_rate\": .001,\n \"n_epochs\" : 100,\n \"batch_size\": 50,\n}\n\n\ndef main():\n # ------------------ 读参数、数据 ---------------------\n if len(sys.argv) < 2:\n print(\"Using defaults:\\n\".format(sys.argv[0]))\n for arg in sys.argv[1:]: # argv[0]代表代码本身文件路径,因此要从第二个开始取参数。\n k, v = arg.split('=', 1)\n sdae_args[k] = ast.literal_eval(v)\n for k in ('learning_rate', 'n_epochs', 'n_nodes', 'noise', 'rho'):\n sdae_args[k] = solo_to_tuple(sdae_args[k], n=3)\n print(\"Stacked DAE arguments: \")\n for k in sorted(sdae_args.keys()):\n print(\"\\t{:15}: {}\".format(k, sdae_args[k]))\n if not os.path.isdir(sdae_args[\"data_dir\"]):\n os.makedirs(sdae_args[\"data_dir\"])\n\n # 获取一下数据信息:有多少条训练数据和验证集数据\n trainX, valX,trainIdx,valIdx,trainY,valY = load_goods_data(train_ratio=0.8,use_cat=False)\n # trainX, valX = load_users_data(train_ratio=0.8)\n # ----------------------------------------------------\n # ----------------- 模型初始化、训练 ------------------------\n with tf.Session() as sess:\n print(\"Initializing...\")\n sdae = SDAE(sess, trainX.shape, valX.shape, is_training=True, **sdae_args)\n print(\"training...\")\n features,val_features = sdae.train()\n\n\nif __name__ == '__main__':\n main()", "import os\nimport tensorflow as tf\nfrom utils import *\n\nclass MLPrec(object):\n def __init__(self, sess, input_size, noise=0, n_nodes=(225, 10), learning_rate=1,\n n_epochs=100,is_training = True, input_dim = 1,data_dir = None,batch_size = 20):\n\n self.sess = sess\n self.is_training = is_training\n self.n_nodes = n_nodes # 各层节点数\n if type(self.n_nodes)==int:\n self.n_layers = 1\n else:\n self.n_layers = len(self.n_nodes) # 层数\n\n self.n_epochs = n_epochs\n self.batch_size = batch_size\n self.input_size = input_size # 输入特征数\n self.input_dim = input_dim # 输入是几通道,rgb是3\n\n self.lr = learning_rate\n self.stddev = 0.02 # 初始化参数用的\n self.noise = noise # dropout水平,是tuple\n\n self.checkpoint_dir = 'checkpoint'\n self.result_dir = 'results'\n self.log_dir = 'logs'\n self.n_show = 100\n\n if not os.path.isdir(self.checkpoint_dir):\n os.makedirs(self.checkpoint_dir)\n if not os.path.isdir(self.result_dir):\n os.makedirs(self.result_dir)\n if not os.path.isdir(self.log_dir):\n os.makedirs(self.log_dir)\n\n # ------------------------- 编码层 -------------------------------------\n def encoder(self,input,output_filter,noise,name = \"default\"):\n with tf.variable_scope(name):\n # dropout+fc+lrelu\n corrupt = tf.layers.dropout(input,rate= noise,training=self.is_training)\n fc = tf.layers.dense(corrupt,output_filter,\n kernel_initializer=tf.random_normal_initializer(stddev=self.stddev),\n bias_initializer=tf.constant_initializer(0.0))\n act = lrelu(fc) #leaky relu\n return act\n\n # ------------------------- 解码层 -------------------------------------\n def decoder(self,input,output_filter,name=\"default\"):\n with tf.variable_scope(name):\n # fc+lrelu\n fc = tf.layers.dense(input, output_filter,\n kernel_initializer=tf.random_normal_initializer(stddev=self.stddev),\n bias_initializer=tf.constant_initializer(0.0))\n act = lrelu(fc)\n return act\n\n def build(self,is_training=True):\n self.x = tf.placeholder(tf.float32,[self.batch_size,self.input_size],\n name=\"input\")\n self.features=[]\n # --------------------------- 建立编码层 -----------------------------------------\n self.enc_layers = []\n input = self.x\n for i in range(self.n_layers):\n out = self.encoder(input,self.n_nodes[i],noise = self.noise[i],\n name = \"encode_layer\" + str(i))\n self.enc_layers.append(out)\n input = out\n self.features.append(out)\n self.enc_out = out\n # -------------------------------------------------------------------------------\n #----------------------------建立解码层-------------------------------------------\n self.dec_layers = []\n input = self.enc_out\n dec_nodes = list(self.n_nodes[:self.n_layers-1]) # 解码器各层节点数,与编码器对应\n dec_nodes.reverse()\n dec_nodes.append(self.input_size)\n for i in range(self.n_layers):\n out = self.decoder(input,dec_nodes[i],\n name = \"decode_layer\" + str(i))\n self.dec_layers.append(out)\n input = out\n self.rec = out # 重建图\n # ------------------------------------------------------------------------------\n # ------------------------ 定义loss --------------------------------------------\n self.loss2 = mse(self.rec,self.x)\n self.loss = self.loss2\n # ------------------------------------------------------------------------------\n # ------------------------ 提取各层可训练参数 -----------------------------------\n self.train_vals = tf.trainable_variables()\n self.train_vals_layer =[]\n for i in range(self.n_layers):\n self.train_vals_layer.append ( [var for var in self.train_vals if str(i) in var.name.split(\"/\")[0]])\n # ------------------------------------------------------------------------------\n\n def train(self,x):\n self.optimizer = tf.train.GradientDescentOptimizer(self.lr[0]).minimize(self.loss,var_list=self.train_vals)\n tf.global_variables_initializer().run()\n\n n_batch = x.shape[0] // self.batch_size\n print(\"num_batch\", n_batch)\n\n for epoch in range(self.n_epochs[0]):\n print(\"epoch: \", epoch)\n for batch in range(n_batch):\n batch_x = x[batch*self.batch_size:(batch+1)*self.batch_size]\n\n _, loss = self.sess.run([self.optimizer,self.loss],feed_dict={self.x:batch_x})\n # 每个epoch输出一下信息,loss用的是该epoch最后一个batch的loss,还有个准确率\n print (\"train loss: \",loss)\n # 训练结束后,输出特征图\n features = [[]]\n for batch in range(self.n_show//self.batch_size):\n batch_x = x[batch * self.batch_size:(batch + 1) * self.batch_size]\n feature = self.sess.run([self.features], feed_dict={self.x: batch_x})\n for l in range(self.n_layers):\n if l>0:\n features.append([])\n features[l].append(feature[0][l])\n for l in range(self.n_layers):\n features[l] = np.concatenate(tuple(features[l]))\n save_image(features[l],self.result_dir+'/feature'+str(l)+'.png',n_show=self.n_show)\n" ]
[ [ "tensorflow.Session" ], [ "tensorflow.layers.dropout", "tensorflow.placeholder", "tensorflow.constant_initializer", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.variable_scope", "tensorflow.trainable_variables", "tensorflow.random_normal_initializer" ] ]
PHYST480/homeworks-elphiesk8s
[ "1d48dda80a69897bed296d52ba2dae9b7b700614" ]
[ "code/sklearn_ex1.py" ]
[ "# G. Richards 2016, based on sgd_separator.py by Jake Vanderplas\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.datasets.samples_generator import make_blobs\n\n# we create 50 separable points\nX, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)\n\n# fit the model\nclf = SGDClassifier(loss=\"hinge\", alpha=0.01, n_iter=200, fit_intercept=True)\nclf.fit(X, Y)\n\n# plot the line, the points, and the nearest vectors to the plane\nxx = np.linspace(-1, 5, 10)\nyy = np.linspace(-1, 5, 10)\n\nX1, X2 = np.meshgrid(xx, yy)\nZ = np.empty(X1.shape)\nfor (i, j), val in np.ndenumerate(X1):\n x1 = val\n x2 = X2[i, j]\n #p = clf.decision_function([x1, x2])\n p = clf.decision_function(np.array([x1,x2]).reshape(1,-1))\n Z[i, j] = p[0]\nlevels = [-1.0, 0.0, 1.0]\nlinestyles = ['dashed', 'solid', 'dashed']\ncolors = 'k'\n\n#ax = plt.axes()\nplt.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)\nplt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)\nplt.axis('tight')\nplt.show()\n" ]
[ [ "numpy.array", "numpy.linspace", "matplotlib.pyplot.scatter", "sklearn.linear_model.SGDClassifier", "matplotlib.pyplot.show", "matplotlib.pyplot.contour", "matplotlib.pyplot.axis", "numpy.ndenumerate", "sklearn.datasets.samples_generator.make_blobs", "numpy.meshgrid", "numpy.empty" ] ]
an-dhyun/DeepLearningStudy
[ "bf4d6d72cdf443bb66c4a408f51c2d744dc52f65" ]
[ "ch08/deep_convnet.py" ]
[ "# coding: utf-8\nimport sys, os\nsys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정\nimport pickle\nimport numpy as np\nfrom collections import OrderedDict\nfrom common.layers import *\n\n\nclass DeepConvNet:\n \"\"\"정확도 99% 이상의 고정밀 합성곱 신경망\n\n 네트워크 구성은 아래와 같음\n conv - relu - conv- relu - pool -\n conv - relu - conv- relu - pool -\n conv - relu - conv- relu - pool -\n affine - relu - dropout - affine - dropout - softmax\n \"\"\"\n def __init__(self, input_dim=(1, 28, 28),\n conv_param_1 = {'filter_num':16, 'filter_size':3, 'pad':1, 'stride':1},\n conv_param_2 = {'filter_num':16, 'filter_size':3, 'pad':1, 'stride':1},\n conv_param_3 = {'filter_num':32, 'filter_size':3, 'pad':1, 'stride':1},\n conv_param_4 = {'filter_num':32, 'filter_size':3, 'pad':2, 'stride':1},\n conv_param_5 = {'filter_num':64, 'filter_size':3, 'pad':1, 'stride':1},\n conv_param_6 = {'filter_num':64, 'filter_size':3, 'pad':1, 'stride':1},\n hidden_size=50, output_size=10):\n # 가중치 초기화===========\n # 각 층의 뉴런 하나당 앞 층의 몇 개 뉴런과 연결되는가(TODO: 자동 계산되게 바꿀 것)\n pre_node_nums = np.array([1*3*3, 16*3*3, 16*3*3, 32*3*3, 32*3*3, 64*3*3, 64*4*4, hidden_size])\n wight_init_scales = np.sqrt(2.0 / pre_node_nums) # ReLU를 사용할 때의 권장 초깃값\n \n self.params = {}\n pre_channel_num = input_dim[0]\n for idx, conv_param in enumerate([conv_param_1, conv_param_2, conv_param_3, conv_param_4, conv_param_5, conv_param_6]):\n self.params['W' + str(idx+1)] = wight_init_scales[idx] * np.random.randn(conv_param['filter_num'], pre_channel_num, conv_param['filter_size'], conv_param['filter_size'])\n self.params['b' + str(idx+1)] = np.zeros(conv_param['filter_num'])\n pre_channel_num = conv_param['filter_num']\n self.params['W7'] = wight_init_scales[6] * np.random.randn(64*4*4, hidden_size)\n self.params['b7'] = np.zeros(hidden_size)\n self.params['W8'] = wight_init_scales[7] * np.random.randn(hidden_size, output_size)\n self.params['b8'] = np.zeros(output_size)\n\n # 계층 생성===========\n self.layers = []\n self.layers.append(Convolution(self.params['W1'], self.params['b1'], \n conv_param_1['stride'], conv_param_1['pad']))\n self.layers.append(Relu())\n self.layers.append(Convolution(self.params['W2'], self.params['b2'], \n conv_param_2['stride'], conv_param_2['pad']))\n self.layers.append(Relu())\n self.layers.append(Pooling(pool_h=2, pool_w=2, stride=2))\n self.layers.append(Convolution(self.params['W3'], self.params['b3'], \n conv_param_3['stride'], conv_param_3['pad']))\n self.layers.append(Relu())\n self.layers.append(Convolution(self.params['W4'], self.params['b4'],\n conv_param_4['stride'], conv_param_4['pad']))\n self.layers.append(Relu())\n self.layers.append(Pooling(pool_h=2, pool_w=2, stride=2))\n self.layers.append(Convolution(self.params['W5'], self.params['b5'],\n conv_param_5['stride'], conv_param_5['pad']))\n self.layers.append(Relu())\n self.layers.append(Convolution(self.params['W6'], self.params['b6'],\n conv_param_6['stride'], conv_param_6['pad']))\n self.layers.append(Relu())\n self.layers.append(Pooling(pool_h=2, pool_w=2, stride=2))\n self.layers.append(Affine(self.params['W7'], self.params['b7']))\n self.layers.append(Relu())\n self.layers.append(Dropout(0.5))\n self.layers.append(Affine(self.params['W8'], self.params['b8']))\n self.layers.append(Dropout(0.5))\n \n self.last_layer = SoftmaxWithLoss()\n\n def predict(self, x, train_flg=False):\n for layer in self.layers:\n if isinstance(layer, Dropout):\n x = layer.forward(x, train_flg)\n else:\n x = layer.forward(x)\n return x\n\n def loss(self, x, t):\n y = self.predict(x, train_flg=True)\n return self.last_layer.forward(y, t)\n\n def accuracy(self, x, t, batch_size=100):\n if t.ndim != 1 : t = np.argmax(t, axis=1)\n\n acc = 0.0\n\n for i in range(int(x.shape[0] / batch_size)):\n tx = x[i*batch_size:(i+1)*batch_size]\n tt = t[i*batch_size:(i+1)*batch_size]\n y = self.predict(tx, train_flg=False)\n y = np.argmax(y, axis=1)\n acc += np.sum(y == tt)\n\n return acc / x.shape[0]\n\n def gradient(self, x, t):\n # forward\n self.loss(x, t)\n\n # backward\n dout = 1\n dout = self.last_layer.backward(dout)\n\n tmp_layers = self.layers.copy()\n tmp_layers.reverse()\n for layer in tmp_layers:\n dout = layer.backward(dout)\n\n # 결과 저장\n grads = {}\n for i, layer_idx in enumerate((0, 2, 5, 7, 10, 12, 15, 18)):\n grads['W' + str(i+1)] = self.layers[layer_idx].dW\n grads['b' + str(i+1)] = self.layers[layer_idx].db\n\n return grads\n\n def save_params(self, file_name=\"params.pkl\"):\n params = {}\n for key, val in self.params.items():\n params[key] = val\n with open(file_name, 'wb') as f:\n pickle.dump(params, f)\n\n def load_params(self, file_name=\"params.pkl\"):\n with open(file_name, 'rb') as f:\n params = pickle.load(f)\n for key, val in params.items():\n self.params[key] = val\n\n for i, layer_idx in enumerate((0, 2, 5, 7, 10, 12, 15, 18)):\n self.layers[layer_idx].W = self.params['W' + str(i+1)]\n self.layers[layer_idx].b = self.params['b' + str(i+1)]\n" ]
[ [ "numpy.sqrt", "numpy.argmax", "numpy.random.randn", "numpy.array", "numpy.zeros", "numpy.sum" ] ]