code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#%% import numpy as np from utils import * #%% def lstm_cell_forward(xt, a_prev, c_prev, parameters): """ Implement a single forward step of the LSTM-cell Arguments: xt -- your input data at timestep "t", numpy array of shape (n_x, m) a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m) c_prev -- Memory state at timestep "t-1", numpy array of shape (n_a, m) parameters -- python dictionary containing: Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x) bf -- Bias of the forget gate, numpy array of shape (n_a, 1) Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x) bi -- Bias of the update gate, numpy array of shape (n_a, 1) Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x) bc -- Bias of the first "tanh", numpy array of shape (n_a, 1) Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x) bo -- Bias of the output gate, numpy array of shape (n_a, 1) Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a) by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1) Returns: a_next -- next hidden state, of shape (n_a, m) c_next -- next memory state, of shape (n_a, m) yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m) cache -- tuple of values needed for the backward pass, contains (a_next, c_next, a_prev, c_prev, xt, parameters) Note: ft/it/ot stand for the forget/update/output gates, cct stands for the candidate value (c tilde), c stands for the cell state (memory) """ # Retrieve parameters from "parameters" Wf = parameters["Wf"] # forget gate weight bf = parameters["bf"] Wi = parameters["Wi"] # update gate weight (notice the variable name) bi = parameters["bi"] # (notice the variable name) Wc = parameters["Wc"] # candidate value weight bc = parameters["bc"] Wo = parameters["Wo"] # output gate weight bo = parameters["bo"] Wy = parameters["Wy"] # prediction weight by = parameters["by"] # Concatenate a_prev and xt concat = np.concatenate((a_prev, xt), axis=0) # Compute values for ft (forget gate), it (update gate), # cct (candidate value), c_next (cell state), # ot (output gate), a_next (hidden state) (≈6 lines) ft = sigmoid(np.dot(Wf, concat) + bf) # forget gate it = sigmoid(np.dot(Wi, concat) + bi) # update gate cct = np.tanh(np.dot(Wc, concat) + bc) # candidate value c_next = np.multiply(ft, c_prev) + np.multiply(it, cct) # cell state ot = sigmoid(np.dot(Wo, concat) + bo) # output gate a_next = np.multiply(ot, np.tanh(c_next)) # hidden state # Compute prediction of the LSTM cell yt_pred = softmax(np.dot(Wy, a_next) + by) # store values needed for backward propagation in cache cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) return a_next, c_next, yt_pred, cache #%% def lstm_forward(x, a0, parameters): """ Implement the forward propagation of the recurrent neural network using an LSTM-cell Arguments: x -- Input data for every time-step, of shape (n_x, m, T_x). a0 -- Initial hidden state, of shape (n_a, m) parameters -- python dictionary containing: Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x) bf -- Bias of the forget gate, numpy array of shape (n_a, 1) Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x) bi -- Bias of the update gate, numpy array of shape (n_a, 1) Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x) bc -- Bias of the first "tanh", numpy array of shape (n_a, 1) Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x) bo -- Bias of the output gate, numpy array of shape (n_a, 1) Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a) by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1) Returns: a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x) y -- Predictions for every time-step, numpy array of shape (n_y, m, T_x) c -- The value of the cell state, numpy array of shape (n_a, m, T_x) caches -- tuple of values needed for the backward pass, contains (list of all the caches, x) """ # Initialize "caches", which will track the list of all the caches caches = [] # Retrieve dimensions from shapes of x and parameters['Wy'] n_x, m, T_x = x.shape n_y, n_a = parameters['Wy'].shape # initialize "a", "c" and "y" with zeros a = np.zeros((n_a, m, T_x)) c = np.zeros((n_a, m, T_x)) y = np.zeros((n_y, m, T_x)) # Initialize a_next and c_next a_next = a0 c_next = np.zeros((n_a, m)) # loop over all time-steps for t in range(T_x): # Get the 2D slice 'xt' from the 3D input 'x' at time step 't' xt = x[:, :, t] # Update next hidden state, next memory state, compute the prediction, get the cache a_next, c_next, yt, cache = lstm_cell_forward(xt, a_next, c_next, parameters) # Save the value of the new "next" hidden state in a a[:, :, t] = a_next # Save the value of the next cell state c[:, :, t] = c_next # Save the value of the prediction in y y[:, :, t] = yt # Append the cache into caches caches.append(cache) # store values needed for backward propagation in cache caches = (caches, x) return a, y, c, caches #%% def lstm_cell_backward(da_next, dc_next, cache): """ Implement the backward pass for the LSTM-cell (single time-step) Arguments: da_next -- Gradients of next hidden state, of shape (n_a, m) dc_next -- Gradients of next cell state, of shape (n_a, m) cache -- cache storing information from the forward pass Returns: gradients -- python dictionary containing: dxt -- Gradient of input data at time-step t, of shape (n_x, m) da_prev -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m) dc_prev -- Gradient w.r.t. the previous memory state, of shape (n_a, m, T_x) dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x) dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1) dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x) dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1) dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x) dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1) dWo -- Gradient w.r.t. the weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x) dbo -- Gradient w.r.t. biases of the output gate, of shape (n_a, 1) """ # Retrieve information from "cache" (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache # Retrieve dimensions from xt's and a_next's shape n_x, m = xt.shape n_a, m = a_next.shape # Compute gates related derivatives dot = da_next * np.tanh(c_next) * ot * (1 - ot) dcct = (dc_next * it + ot * (1 - np.tanh(c_next) ** 2) * it * da_next) * (1 - cct ** 2) dit = (dc_next * cct + ot * (1 - np.tanh(c_next) ** 2) * cct * da_next) * it * (1 - it) dft = (dc_next * c_prev + ot * (1 - np.tanh(c_next) ** 2) * c_prev * da_next) * ft * (1 - ft) # Compute parameters related derivatives dWf = np.dot(dft, np.concatenate((a_prev, xt), axis=0).T) dbf = np.sum(dft, axis=1, keepdims=True) dWi = np.dot(dit, np.concatenate((a_prev, xt), axis=0).T) dbi = np.sum(dit, axis=1, keepdims=True) dWc = np.dot(dcct, np.concatenate((a_prev, xt), axis=0).T) dbc = np.sum(dcct, axis=1, keepdims=True) dWo = np.dot(dot, np.concatenate((a_prev, xt), axis=0).T) dbo = np.sum(dot, axis=1, keepdims=True) # Compute derivatives w.r.t previous hidden state, previous memory state and input da_prev = np.dot(parameters['Wf'][:, :n_a].T, dft) + np.dot(parameters['Wi'][:, :n_a].T, dit) \ + np.dot(parameters['Wc'][:, :n_a].T, dcct) + np.dot(parameters['Wo'][:, :n_a].T, dot) dc_prev = dc_next * ft + ot * (1 - np.tanh(c_next) ** 2) * ft * da_next dxt = np.dot(parameters['Wf'][:, n_a:].T, dft) + np.dot(parameters['Wi'][:, n_a:].T, dit) \ + np.dot(parameters['Wc'][:, n_a:].T, dcct) + np.dot(parameters['Wo'][:, n_a:].T, dot) # Save gradients in dictionary gradients = {"dxt": dxt, "da_prev": da_prev, "dc_prev": dc_prev, "dWf": dWf, "dbf": dbf, "dWi": dWi, "dbi": dbi, "dWc": dWc, "dbc": dbc, "dWo": dWo, "dbo": dbo} return gradients #%% def lstm_backward(da, caches): """ Implement the backward pass for the RNN with LSTM-cell (over a whole sequence) Arguments: da -- Gradients w.r.t the hidden states, numpy-array of shape (n_a, m, T_x) From each time t, y_predt is calculated and its gradient can be calculated da is stacked from the gradient from each time t caches -- cache storing information from the forward pass (lSTM_forward) Returns: gradients -- python dictionary containing: dx -- Gradient of inputs, of shape (n_x, m, T_x) da0 -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m) dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x) dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x) dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x) dWo -- Gradient w.r.t. the weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x) dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1) dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1) dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1) dbo -- Gradient w.r.t. biases of the save gate, of shape (n_a, 1) """ # Retrieve values from the first cache (t=1) of caches. (caches, x) = caches (a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0] # Retrieve dimensions from da's and x1's shapes n_a, m, T_x = da.shape n_x, m = x1.shape # initialize the gradients with the right sizes dx = np.zeros((n_x, m, T_x)) da0 = np.zeros((n_a, m)) da_prevt = np.zeros((n_a, m)) dc_prevt = np.zeros((n_a, m)) dWf = np.zeros((n_a, n_a + n_x)) dWi = np.zeros((n_a, n_a + n_x)) dWc = np.zeros((n_a, n_a + n_x)) dWo = np.zeros((n_a, n_a + n_x)) dbf = np.zeros((n_a, 1)) dbi = np.zeros((n_a, 1)) dbc = np.zeros((n_a, 1)) dbo = np.zeros((n_a, 1)) # loop back over the whole sequence for t in reversed(range(T_x)): # Compute all gradients using lstm_cell_backward gradients = lstm_cell_backward(da[:, :, t] + da_prevt, dc_prevt, caches[t]) # Store or add the gradient to the parameters' previous step's gradient dx[:, :, t] = gradients['dxt'] da_prevt = gradients['da_prev'] dc_prevt = gradients['dc_prev'] dWf = gradients['dWf'] dWi = gradients['dWi'] dWc = gradients['dWc'] dWo = gradients['dWo'] dbf = gradients['dbf'] dbi = gradients['dbi'] dbc = gradients['dbc'] dbo = gradients['dbo'] # Set the first activation's gradient to the backpropagated gradient da_prev. da0 += da_prevt # Store the gradients in a python dictionary gradients = {"dx": dx, "da0": da0, "dWf": dWf, "dbf": dbf, "dWi": dWi, "dbi": dbi, "dWc": dWc, "dbc": dbc, "dWo": dWo, "dbo": dbo} return gradients
[ "numpy.multiply", "numpy.tanh", "numpy.sum", "numpy.zeros", "numpy.dot", "numpy.concatenate" ]
[((2419, 2455), 'numpy.concatenate', 'np.concatenate', (['(a_prev, xt)'], {'axis': '(0)'}), '((a_prev, xt), axis=0)\n', (2433, 2455), True, 'import numpy as np\n'), ((5177, 5200), 'numpy.zeros', 'np.zeros', (['(n_a, m, T_x)'], {}), '((n_a, m, T_x))\n', (5185, 5200), True, 'import numpy as np\n'), ((5209, 5232), 'numpy.zeros', 'np.zeros', (['(n_a, m, T_x)'], {}), '((n_a, m, T_x))\n', (5217, 5232), True, 'import numpy as np\n'), ((5241, 5264), 'numpy.zeros', 'np.zeros', (['(n_y, m, T_x)'], {}), '((n_y, m, T_x))\n', (5249, 5264), True, 'import numpy as np\n'), ((5330, 5348), 'numpy.zeros', 'np.zeros', (['(n_a, m)'], {}), '((n_a, m))\n', (5338, 5348), True, 'import numpy as np\n'), ((8378, 8412), 'numpy.sum', 'np.sum', (['dft'], {'axis': '(1)', 'keepdims': '(True)'}), '(dft, axis=1, keepdims=True)\n', (8384, 8412), True, 'import numpy as np\n'), ((8485, 8519), 'numpy.sum', 'np.sum', (['dit'], {'axis': '(1)', 'keepdims': '(True)'}), '(dit, axis=1, keepdims=True)\n', (8491, 8519), True, 'import numpy as np\n'), ((8593, 8628), 'numpy.sum', 'np.sum', (['dcct'], {'axis': '(1)', 'keepdims': '(True)'}), '(dcct, axis=1, keepdims=True)\n', (8599, 8628), True, 'import numpy as np\n'), ((8701, 8735), 'numpy.sum', 'np.sum', (['dot'], {'axis': '(1)', 'keepdims': '(True)'}), '(dot, axis=1, keepdims=True)\n', (8707, 8735), True, 'import numpy as np\n'), ((11397, 11420), 'numpy.zeros', 'np.zeros', (['(n_x, m, T_x)'], {}), '((n_x, m, T_x))\n', (11405, 11420), True, 'import numpy as np\n'), ((11431, 11449), 'numpy.zeros', 'np.zeros', (['(n_a, m)'], {}), '((n_a, m))\n', (11439, 11449), True, 'import numpy as np\n'), ((11465, 11483), 'numpy.zeros', 'np.zeros', (['(n_a, m)'], {}), '((n_a, m))\n', (11473, 11483), True, 'import numpy as np\n'), ((11499, 11517), 'numpy.zeros', 'np.zeros', (['(n_a, m)'], {}), '((n_a, m))\n', (11507, 11517), True, 'import numpy as np\n'), ((11528, 11554), 'numpy.zeros', 'np.zeros', (['(n_a, n_a + n_x)'], {}), '((n_a, n_a + n_x))\n', (11536, 11554), True, 'import numpy as np\n'), ((11565, 11591), 'numpy.zeros', 'np.zeros', (['(n_a, n_a + n_x)'], {}), '((n_a, n_a + n_x))\n', (11573, 11591), True, 'import numpy as np\n'), ((11602, 11628), 'numpy.zeros', 'np.zeros', (['(n_a, n_a + n_x)'], {}), '((n_a, n_a + n_x))\n', (11610, 11628), True, 'import numpy as np\n'), ((11639, 11665), 'numpy.zeros', 'np.zeros', (['(n_a, n_a + n_x)'], {}), '((n_a, n_a + n_x))\n', (11647, 11665), True, 'import numpy as np\n'), ((11676, 11694), 'numpy.zeros', 'np.zeros', (['(n_a, 1)'], {}), '((n_a, 1))\n', (11684, 11694), True, 'import numpy as np\n'), ((11705, 11723), 'numpy.zeros', 'np.zeros', (['(n_a, 1)'], {}), '((n_a, 1))\n', (11713, 11723), True, 'import numpy as np\n'), ((11734, 11752), 'numpy.zeros', 'np.zeros', (['(n_a, 1)'], {}), '((n_a, 1))\n', (11742, 11752), True, 'import numpy as np\n'), ((11763, 11781), 'numpy.zeros', 'np.zeros', (['(n_a, 1)'], {}), '((n_a, 1))\n', (11771, 11781), True, 'import numpy as np\n'), ((2814, 2837), 'numpy.multiply', 'np.multiply', (['ft', 'c_prev'], {}), '(ft, c_prev)\n', (2825, 2837), True, 'import numpy as np\n'), ((2840, 2860), 'numpy.multiply', 'np.multiply', (['it', 'cct'], {}), '(it, cct)\n', (2851, 2860), True, 'import numpy as np\n'), ((2961, 2976), 'numpy.tanh', 'np.tanh', (['c_next'], {}), '(c_next)\n', (2968, 2976), True, 'import numpy as np\n'), ((8984, 9024), 'numpy.dot', 'np.dot', (["parameters['Wo'][:, :n_a].T", 'dot'], {}), "(parameters['Wo'][:, :n_a].T, dot)\n", (8990, 9024), True, 'import numpy as np\n'), ((9253, 9293), 'numpy.dot', 'np.dot', (["parameters['Wo'][:, n_a:].T", 'dot'], {}), "(parameters['Wo'][:, n_a:].T, dot)\n", (9259, 9293), True, 'import numpy as np\n'), ((2642, 2660), 'numpy.dot', 'np.dot', (['Wf', 'concat'], {}), '(Wf, concat)\n', (2648, 2660), True, 'import numpy as np\n'), ((2699, 2717), 'numpy.dot', 'np.dot', (['Wi', 'concat'], {}), '(Wi, concat)\n', (2705, 2717), True, 'import numpy as np\n'), ((2757, 2775), 'numpy.dot', 'np.dot', (['Wc', 'concat'], {}), '(Wc, concat)\n', (2763, 2775), True, 'import numpy as np\n'), ((2892, 2910), 'numpy.dot', 'np.dot', (['Wo', 'concat'], {}), '(Wo, concat)\n', (2898, 2910), True, 'import numpy as np\n'), ((3059, 3077), 'numpy.dot', 'np.dot', (['Wy', 'a_next'], {}), '(Wy, a_next)\n', (3065, 3077), True, 'import numpy as np\n'), ((8328, 8364), 'numpy.concatenate', 'np.concatenate', (['(a_prev, xt)'], {'axis': '(0)'}), '((a_prev, xt), axis=0)\n', (8342, 8364), True, 'import numpy as np\n'), ((8435, 8471), 'numpy.concatenate', 'np.concatenate', (['(a_prev, xt)'], {'axis': '(0)'}), '((a_prev, xt), axis=0)\n', (8449, 8471), True, 'import numpy as np\n'), ((8543, 8579), 'numpy.concatenate', 'np.concatenate', (['(a_prev, xt)'], {'axis': '(0)'}), '((a_prev, xt), axis=0)\n', (8557, 8579), True, 'import numpy as np\n'), ((8651, 8687), 'numpy.concatenate', 'np.concatenate', (['(a_prev, xt)'], {'axis': '(0)'}), '((a_prev, xt), axis=0)\n', (8665, 8687), True, 'import numpy as np\n'), ((8940, 8981), 'numpy.dot', 'np.dot', (["parameters['Wc'][:, :n_a].T", 'dcct'], {}), "(parameters['Wc'][:, :n_a].T, dcct)\n", (8946, 8981), True, 'import numpy as np\n'), ((9209, 9250), 'numpy.dot', 'np.dot', (["parameters['Wc'][:, n_a:].T", 'dcct'], {}), "(parameters['Wc'][:, n_a:].T, dcct)\n", (9215, 9250), True, 'import numpy as np\n'), ((7946, 7961), 'numpy.tanh', 'np.tanh', (['c_next'], {}), '(c_next)\n', (7953, 7961), True, 'import numpy as np\n'), ((8838, 8878), 'numpy.dot', 'np.dot', (["parameters['Wf'][:, :n_a].T", 'dft'], {}), "(parameters['Wf'][:, :n_a].T, dft)\n", (8844, 8878), True, 'import numpy as np\n'), ((8881, 8921), 'numpy.dot', 'np.dot', (["parameters['Wi'][:, :n_a].T", 'dit'], {}), "(parameters['Wi'][:, :n_a].T, dit)\n", (8887, 8921), True, 'import numpy as np\n'), ((9111, 9151), 'numpy.dot', 'np.dot', (["parameters['Wf'][:, n_a:].T", 'dft'], {}), "(parameters['Wf'][:, n_a:].T, dft)\n", (9117, 9151), True, 'import numpy as np\n'), ((9154, 9194), 'numpy.dot', 'np.dot', (["parameters['Wi'][:, n_a:].T", 'dit'], {}), "(parameters['Wi'][:, n_a:].T, dit)\n", (9160, 9194), True, 'import numpy as np\n'), ((9064, 9079), 'numpy.tanh', 'np.tanh', (['c_next'], {}), '(c_next)\n', (9071, 9079), True, 'import numpy as np\n'), ((8015, 8030), 'numpy.tanh', 'np.tanh', (['c_next'], {}), '(c_next)\n', (8022, 8030), True, 'import numpy as np\n'), ((8107, 8122), 'numpy.tanh', 'np.tanh', (['c_next'], {}), '(c_next)\n', (8114, 8122), True, 'import numpy as np\n'), ((8202, 8217), 'numpy.tanh', 'np.tanh', (['c_next'], {}), '(c_next)\n', (8209, 8217), True, 'import numpy as np\n')]
import numpy as np import pytest from sklearn.datasets import make_regression from cartesian import Symbolic from cartesian.sklearn_api import _ensure_1d class TestSymbolic: @pytest.mark.parametrize("n_out", [1, 2]) def test_fit(self, n_out): x, y = make_regression(n_features=2, n_informative=1, n_targets=n_out) est = Symbolic(maxfev=1, lambda_=1).fit(x, y) yhat = est.predict(x) assert yhat.shape == y.shape def test_joblib(self): x, y = make_regression(n_features=2, n_informative=1, n_targets=1) yhat = Symbolic(n_jobs=-1, maxfev=1, lambda_=1).fit(x, y).predict(x) assert yhat.shape == y.shape def test__ensure_1d(): assert _ensure_1d(1, 1) == np.ones(1) assert _ensure_1d(np.ones(1), 1) == np.ones(1)
[ "cartesian.Symbolic", "cartesian.sklearn_api._ensure_1d", "sklearn.datasets.make_regression", "numpy.ones", "pytest.mark.parametrize" ]
[((182, 222), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n_out"""', '[1, 2]'], {}), "('n_out', [1, 2])\n", (205, 222), False, 'import pytest\n'), ((269, 332), 'sklearn.datasets.make_regression', 'make_regression', ([], {'n_features': '(2)', 'n_informative': '(1)', 'n_targets': 'n_out'}), '(n_features=2, n_informative=1, n_targets=n_out)\n', (284, 332), False, 'from sklearn.datasets import make_regression\n'), ((497, 556), 'sklearn.datasets.make_regression', 'make_regression', ([], {'n_features': '(2)', 'n_informative': '(1)', 'n_targets': '(1)'}), '(n_features=2, n_informative=1, n_targets=1)\n', (512, 556), False, 'from sklearn.datasets import make_regression\n'), ((707, 723), 'cartesian.sklearn_api._ensure_1d', '_ensure_1d', (['(1)', '(1)'], {}), '(1, 1)\n', (717, 723), False, 'from cartesian.sklearn_api import _ensure_1d\n'), ((727, 737), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (734, 737), True, 'import numpy as np\n'), ((778, 788), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (785, 788), True, 'import numpy as np\n'), ((760, 770), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (767, 770), True, 'import numpy as np\n'), ((347, 376), 'cartesian.Symbolic', 'Symbolic', ([], {'maxfev': '(1)', 'lambda_': '(1)'}), '(maxfev=1, lambda_=1)\n', (355, 376), False, 'from cartesian import Symbolic\n'), ((572, 612), 'cartesian.Symbolic', 'Symbolic', ([], {'n_jobs': '(-1)', 'maxfev': '(1)', 'lambda_': '(1)'}), '(n_jobs=-1, maxfev=1, lambda_=1)\n', (580, 612), False, 'from cartesian import Symbolic\n')]
import sys # import matplotlib.pyplot as plt import numpy as np from PIL import Image from sr_convnet import SRConvNet if len(sys.argv) != 4: print('Usage: python3 {} in.pkl in.xxx(image) ' 'out.xxx(image)'.format(sys.argv[0])) sys.exit(1) fnp = sys.argv[1] fni = sys.argv[2] fno = sys.argv[3] num_ch = 1 patch_size = 33 scale = 3 im = Image.open(fni) im = im.resize((im.width*scale, im.height*scale), resample=Image.BICUBIC) im = im.convert('YCbCr') height = im.height width = im.width im.show() im_bi = np.array(im).transpose(2, 0, 1)/255 im_in = np.empty((1, num_ch, height, width)) im_in[0] = im_bi[0, :, :] network = SRConvNet(input_dim=(num_ch, patch_size, patch_size), conv_param_1={'filter_num': 64, 'filter_size': 9, 'pad': 4, 'stride': 1}, conv_param_2={'filter_num': 32, 'filter_size': 1, 'pad': 0, 'stride': 1}, conv_param_3={'filter_num': 1, 'filter_size': 5, 'pad': 2, 'stride': 1}) network.load_params(fnp) im_out = network.predict(im_in) im_mux = np.empty((height, width, 3)) im_mux[:, :, 0] = np.clip(im_out[0, 0], 0, 1) im_mux[:, :, 1:] = im_bi[1:].transpose(1, 2, 0) im_mux = (im_mux*255).astype(np.uint8) im_sr = Image.fromarray(im_mux, 'YCbCr') im_sr.show() # plt.imshow(np.array(im_mux), interpolation='nearest') # plt.show() im_sr.convert('RGB').save(fno)
[ "sr_convnet.SRConvNet", "numpy.empty", "numpy.clip", "PIL.Image.open", "numpy.array", "PIL.Image.fromarray", "sys.exit" ]
[((359, 374), 'PIL.Image.open', 'Image.open', (['fni'], {}), '(fni)\n', (369, 374), False, 'from PIL import Image\n'), ((573, 609), 'numpy.empty', 'np.empty', (['(1, num_ch, height, width)'], {}), '((1, num_ch, height, width))\n', (581, 609), True, 'import numpy as np\n'), ((647, 935), 'sr_convnet.SRConvNet', 'SRConvNet', ([], {'input_dim': '(num_ch, patch_size, patch_size)', 'conv_param_1': "{'filter_num': 64, 'filter_size': 9, 'pad': 4, 'stride': 1}", 'conv_param_2': "{'filter_num': 32, 'filter_size': 1, 'pad': 0, 'stride': 1}", 'conv_param_3': "{'filter_num': 1, 'filter_size': 5, 'pad': 2, 'stride': 1}"}), "(input_dim=(num_ch, patch_size, patch_size), conv_param_1={\n 'filter_num': 64, 'filter_size': 9, 'pad': 4, 'stride': 1},\n conv_param_2={'filter_num': 32, 'filter_size': 1, 'pad': 0, 'stride': 1\n }, conv_param_3={'filter_num': 1, 'filter_size': 5, 'pad': 2, 'stride': 1})\n", (656, 935), False, 'from sr_convnet import SRConvNet\n'), ((1151, 1179), 'numpy.empty', 'np.empty', (['(height, width, 3)'], {}), '((height, width, 3))\n', (1159, 1179), True, 'import numpy as np\n'), ((1198, 1225), 'numpy.clip', 'np.clip', (['im_out[0, 0]', '(0)', '(1)'], {}), '(im_out[0, 0], 0, 1)\n', (1205, 1225), True, 'import numpy as np\n'), ((1321, 1353), 'PIL.Image.fromarray', 'Image.fromarray', (['im_mux', '"""YCbCr"""'], {}), "(im_mux, 'YCbCr')\n", (1336, 1353), False, 'from PIL import Image\n'), ((248, 259), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (256, 259), False, 'import sys\n'), ((529, 541), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (537, 541), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 27 12:40:48 2018 @author: BallBlueMeercat """ import numpy as np import os import time from results import load import matplotlib.pyplot as plt import matplotlib as mpl mpl.style.use('default') # has to be switched on to set figure size mpl.style.use('fivethirtyeight') plt.rcParams['axes.facecolor'] = 'white' plt.rcParams['figure.facecolor'] = 'white' plt.rcParams['grid.color'] = 'white' plt.rcParams.update({'figure.autolayout': True}) def stat_emcee(hue, var, var_true, var_name, slnprob, zpicks, mag, sigma, nsteps, nwalkers, save_path, firstderivs_key): initial = var_name.lower()[:1] name_true = var_name[:1] + '_true' hue_name = hue hue = 'xkcd:'+hue # Marginalised distribution histogram. plt.figure() # plt.xlabel(r'$\{}$'.format(name_l)) plt.xlabel(var_name) # plt.title('model: '+firstderivs_key+'\n Marginalised distribution of ' # +var_name+' \n nsteps: '+str(nsteps)+', noise: '+str(sigma) # +', npoints: '+str(len(zpicks))+' '+firstderivs_key) plt.hist(var, 50, facecolor=hue) plt.locator_params(axis='x', nbins=5) stamp = str(int(time.time())) filename = str(stamp)+'_'+initial+'_mhist__nsteps_'+str(nsteps) \ +'_nwalkers_'+str(nwalkers)+'_noise_'+str(sigma) \ +'_numpoints_'+str(len(zpicks))+'.png' filename = os.path.join(save_path, filename) plt.savefig(filename) # Walker steps. plt.figure() plt.xlabel(var_name) # plt.title('model: '+firstderivs_key+'\n lnprobability of '+var_name # +' \n nsteps: '+str(nsteps)+', noise: '+str(sigma) # +', npoints: '+str(len(zpicks))) plt.plot(var, slnprob, '.', color=hue) plt.locator_params(axis='x', nbins=5) stamp = str(int(time.time())) filename = str(stamp)+'_'+initial+'_steps__nsteps_'+str(nsteps) \ +'_nwalkers_'+str(nwalkers)+'_noise_'+str(sigma) \ +'_numpoints_'+str(len(zpicks))+'.png' filename = os.path.join(save_path, filename) plt.savefig(filename) # Chains. plt.figure() plt.xlabel('step number') # plt.ylabel(r'$\{}$'.format(name_l)) plt.ylabel(var_name) # plt.title('model: '+firstderivs_key+'\n flatchains, '+name_true+ # ' in '+hue_name+' \n nsteps: '+str(nsteps)+', noise: ' # +str(sigma)+', npoints: '+str(len(zpicks))) plt.plot(var.T, '-', color='k', alpha=0.3, lw=2, label='chain') plt.axhline(var_true, color=hue, lw=2, label='input value') plt.locator_params(axis='x', nbins=5) plt.legend() stamp = str(int(time.time())) filename = str(stamp)+'_'+initial+'_chain__nsteps_'+str(nsteps) \ +'_nwalkers_'+str(nwalkers)+'_noise_'+str(sigma) \ +'_numpoints_'+str(len(zpicks))+'.png' filename = os.path.join(save_path, filename) plt.savefig(filename) plt.show(block=False) return def stat_DNest(hue, var, var_true, var_name, slnprob, zpicks, mag, sigma, nsteps, nwalkers, save_path, firstderivs_key): initial = var_name.lower()[:1] name_true = var_name[:1] + '_true' hue_name = hue hue = 'xkcd:'+hue # Marginalised distribution histogram. plt.figure() # plt.xlabel(r'$\{}$'.format(name_l)) plt.xlabel(var_name) plt.title('model: '+firstderivs_key+'\n Marginalised distribution of ' +var_name+' \n nsteps: '+str(nsteps)+', noise: '+str(sigma) +', npoints: '+str(len(zpicks))+' '+firstderivs_key) plt.hist(var, 50, facecolor=hue) stamp = str(int(time.time())) filename = str(stamp)+'_'+initial+'_mhist__nsteps_'+str(nsteps) \ +'_nwalkers_'+str(nwalkers)+'_noise_'+str(sigma) \ +'_numpoints_'+str(len(zpicks))+'.png' filename = os.path.join(save_path, filename) plt.savefig(filename) # Walker steps. plt.figure() plt.xlabel(var_name) plt.title('model: '+firstderivs_key+'\n lnprobability of '+var_name +' \n nsteps: '+str(nsteps)+', noise: '+str(sigma) +', npoints: '+str(len(zpicks))) plt.plot(var, slnprob, '.', color=hue) stamp = str(int(time.time())) filename = str(stamp)+'_'+initial+'_steps__nsteps_'+str(nsteps) \ +'_nwalkers_'+str(nwalkers)+'_noise_'+str(sigma) \ +'_numpoints_'+str(len(zpicks))+'.png' filename = os.path.join(save_path, filename) plt.savefig(filename) # Chains. plt.figure() plt.xlabel('step number') # plt.ylabel(r'$\{}$'.format(name_l)) plt.ylabel(var_name) plt.title('model: '+firstderivs_key+'\n flatchains, '+name_true+ ' in '+hue_name+' \n nsteps: '+str(nsteps)+', noise: ' +str(sigma)+', npoints: '+str(len(zpicks))) plt.plot(var.T, '-', color='k', alpha=0.3) plt.axhline(var_true, color=hue) stamp = str(int(time.time())) filename = str(stamp)+'_'+initial+'_chain__nsteps_'+str(nsteps) \ +'_nwalkers_'+str(nwalkers)+'_noise_'+str(sigma) \ +'_numpoints_'+str(len(zpicks))+'.png' filename = os.path.join(save_path, filename) plt.savefig(filename) plt.show(block=False) return def precise_runs(firstderivs_key, names, values, p, x): ''' Takes in: firstderivs_key = string, model tested; params_dic = list of dicts, parameters used to generate 'LCDM' data; p = flot/int, cutoff precision in % for vc (params with mean !=0); x = flot/int, cutoff precision for s.d. ''' # Results folder to search through. directory = os.path.join('./results_error_vs_data_plots/'+firstderivs_key) # Lists to be populated with contents of results folders. sd_list = [] mean_list = [] vc_list = [] sigma_list = [] npoints_list = [] # Creating a list of folders for each run that the model was tested. folders = [] for d in os.walk(directory): folders.append(d[0]) folders.pop(0) # Colecting sd, mean, vc of marginalised distributions for all parameters, and # the dataset properties such as sigma of noise added and number of points used. for folder in folders: sd_list += load(folder, 'sd_list.p') mean_list += load(folder, 'mean_list.p') vc_list += load(folder, 'vc_list.p') sigma_list += load(folder, 'sigma_list.p') npoints_list += load(folder, 'npoints_list.p') n_param = len(values) # How many parameters were fitted. n_run = int(len(vc_list) / n_param) # How many runs were recorded. # For each parameter: for j in range(n_param): initial = vc_list[j][0][0] # First letter of the parameter fitted. sd = [] mean = [] vc = [] # Results recorded for each run: for i in range(n_run): index = i*n_param+j # index of current parameter's results, # given number of parameters fitted sd.append(sd_list[index][1]) mean.append(mean_list[index][1]) vc.append(vc_list[index][1]) i+=1 # Onto the next run. # Converting to np.ndarrays to find & remove rows with repeating npoints. sd = np.array(sd) vc = np.asarray(vc) sigma = np.asarray(sigma_list) npoints = np.asarray(npoints_list) # Since input m and M are !=0, fitted m and M are unlikely to have mean=0, # so precision can be based on the variance coefficient vc=sd/mean*100. if initial == 'm' or initial == 'M': # Indicies of rows with vc > p%. vc_above_p_index = np.where(abs(vc) > p) # Eliminating parameters found with precision > p%. p_stack = np.stack((npoints, sigma, vc), axis=1) p_stack = np.delete(p_stack, vc_above_p_index, 0) # Removing all but the noisiest run for each dataset size. for l in range(len(p_stack)-1): k = l+1 # next line npoints_l = p_stack[l][0] # Size of dataset on run l. npints_k = p_stack[k][0] # Size of dataset on run k. if npoints_l == npints_k: # If dataset sizes are the same, then sigma_l = p_stack[l][1] # compare sd of noise added to data. sigma_k = p_stack[k][1] # and leave the noisier run results. if sigma_l > sigma_k: p_stack = np.delete(p_stack, k, 0) elif sigma_l < sigma_k: p_stack = np.delete(p_stack, l, 0) l+=1 # Splitting npoints, sigma added to data and variance # coefficient into one dimentional np.arrays. p_npoints, p_sigma, p_vc= np.hsplit(p_stack, 3) p_npoints = p_npoints.flatten() p_sigma = p_sigma.flatten() p_vc = p_vc.flatten() # Plotting dataset size vs noise added to data for all runs, and runs # where parameters were found withing precision p, with vc annotated. fig, ax = plt.subplots() ax.scatter(npoints, sigma, c='c', label=('all runs')) ax.scatter(p_npoints, p_sigma, c='m', label=('vc < %s%%'%(p))) # Annotating vc. for i, txt in enumerate(p_vc): txt = str(round(txt,2)) ax.annotate(txt, (p_npoints[i], p_sigma[i])) plt.xlabel('Dataset size') plt.ylabel('Sigma of noise added to data') plt.title('Runs where '+initial+' was recovered within '+ str(p)+' percent. \n Variance coefficients annotated.') plt.legend() # Since input interaction terms are 0, recovered terms often have mean=0, # hence precision is based on stadard deviation to avoid division by 0 # when calculating a variance coefficient. else: # Indicies of rows with sd > x. sd_above_x_index = np.where(abs(sd) > x) # Eliminating parameters found outside of sd < x. x_stack = np.stack((npoints, sigma, sd), axis=1) x_stack = np.delete(x_stack, sd_above_x_index, 0) # Removing all but the noisiest run for each dataset size. for l in range(len(x_stack)-1): k = l+1 # next line npoints_l = x_stack[l][0] # Size of dataset on run l. npints_k = x_stack[k][0] # Size of dataset on run k. if npoints_l == npints_k: # If dataset sizes are the same, then sigma_l = x_stack[l][1] # compare sd of noise added to data. sigma_k = x_stack[k][1] # and leave the noisier run results. if sigma_l > sigma_k: x_stack = np.delete(x_stack, k, 0) elif sigma_l < sigma_k: x_stack = np.delete(x_stack, l, 0) l+=1 # Splitting npoints, sigma added to data and standard # deviation into one dimentional np.arrays. x_npoints, x_sigma, x_sd= np.hsplit(x_stack, 3) x_npoints = x_npoints.flatten() x_sigma = x_sigma.flatten() x_sd = x_sd.flatten() # Plotting dataset size vs noise added to data for all runs, and runs # where parameters were found with s.d. < x, with s.d. annotated. fig, ax = plt.subplots() ax.scatter(npoints, sigma, c='c', label=('all runs')) ax.scatter(x_npoints, x_sigma, c='m', label=('s.d. < %s'%(x))) # Annotating vc. for i, txt in enumerate(x_sd): txt = str(round(txt,2)) ax.annotate(txt, (x_npoints[i], x_sigma[i])) plt.xlabel('Dataset size') plt.ylabel('Sigma of noise added to data') plt.title('Runs where '+initial+' was recovered with s.d. < '+ str(x)+'. \n Standard deviations annotated.') plt.legend() j+=1 # Onto the next parameter. plt.show() return def modelcheck(mag, input_zpicks, plot_var, firstderivs_key): print(f'len of input zpicks = {len(input_zpicks)}') zpicks = plot_var.get('z') t = plot_var.get('t') dl = plot_var.get('dl') a = plot_var.get('a') Hz = plot_var.get('Hz') fluid_names = plot_var.get('fluid_names') fluid_arr = plot_var.get('fluid_arr') int_terms = plot_var.get('int_terms') da = plot_var.get('da') dV = plot_var.get('dV') t = -t if np.isnan(Hz).any(): print('plots.modelcheck got NaN value for H') # Fluid evolution. plt.figure() plt.xlabel('$z$') plt.ylabel(r'$\bar \Omega $') plt.grid(True) for i in range(len(fluid_arr)): plt.plot(zpicks, fluid_arr[i], label=fluid_names[i]) plt.legend() plt.title(r'$\bar \Omega_{X}$ evolution' f'\n Model: {firstderivs_key}, int_terms = {int_terms}') # Evolution of the angular diameter distance. plt.figure() plt.title('Angular diameter distance evolution' f'\n Model: {firstderivs_key}, int_terms = {int_terms}') plt.xlabel('z') plt.ylabel(r'$ d_A (H_0 / c)$') plt.grid(True) da_index = np.argmin(da) if da[da_index] < 0: plt.plot(zpicks[:,da_index], da[:, da_index]) plt.plot(zpicks[da_index, :], da[da_index, :]) else: plt.plot(zpicks, da) # Evolution of dV. plt.figure() plt.title(r'$d_V$ evolution' f'\n Model: {firstderivs_key}, int_terms = {int_terms}') plt.xlabel('z') plt.ylabel(r'$ d_V (z)$ [Mpc]') plt.grid(True) plt.plot(zpicks, dV) # Luminosity distance vs redshift. plt.figure() plt.xlabel('$z$') plt.ylabel('$d_L$*($H_0$/c)') plt.grid(True) plt.plot(zpicks, dl) plt.title('$d_L$ evolution'+'\n Model: %s, int_terms = %s' %(firstderivs_key, int_terms)) # H vs redshift. plt.figure() plt.xlabel('$z$') plt.ylabel('H') plt.grid(True) plt.plot(zpicks, Hz) plt.title(r'$H(z)$ evolution'+'\n Model: %s, int_terms = %s' %(firstderivs_key, int_terms)) # Scale factor vs redshift. plt.figure() plt.xlabel('$z$') plt.ylabel('a') plt.grid(True) plt.plot(zpicks, a) plt.title('Scale factor evolution with redshift ' +'\n Model: %s, int_terms = %s' %(firstderivs_key, int_terms)) # Scale factor vs age. plt.figure() plt.xlabel('Age') plt.ylabel('a') plt.grid(True) plt.plot(t, a) plt.title('Scale factor evolution with time'+'\n Model: %s, int_terms = %s' %(firstderivs_key, int_terms)) # Redshift vs age. plt.figure() plt.xlabel('Age') plt.ylabel('$z$') plt.grid(True) plt.plot(t, zpicks) plt.title('Redshift evolution'+'\n Model: %s, int_terms = %s' %(firstderivs_key, int_terms)) # Magnitude vs redshift. plt.figure() plt.xlabel('$z$') plt.ylabel('Magnitude') plt.title('Magnitude evolution'+'\n Model: %s, int_terms = %s' %(firstderivs_key, int_terms)) plt.scatter(input_zpicks, mag, marker='.') plt.show() return def multi_modelcheck(data, keys, plot_var_list): ''' For 1 interaction term models. ''' print('multi_modelcheck') zpicks = data['zpicks'] data_mag = data['mag'] model_names = '' for model_name in keys: model_names += model_name+', ' model_names = model_names[:-2] mag = [] t = [] dl = [] a = [] Hz = [] da = [] dV = [] fluid_names = [] fluid_arr = [] int_terms = [] for plot_var in plot_var_list: mag.append(plot_var.get('mag')) t.append(plot_var.get('t')) dl.append(plot_var.get('dl')) a.append(plot_var.get('a')) Hz.append(plot_var.get('Hz')) da.append(plot_var.get('da')) dV.append(plot_var.get('dV')) fluid_names.append(plot_var.get('fluid_names')) fluid_arr.append(plot_var.get('fluid_arr')) int_terms.append(plot_var.get('int_terms')) # # Changing time t into age # age=[] # for item in t: # item = -item # age.append(item) # # # log x axis fluid evolution vs redshift. # fig = plt.figure() # plt.xlabel('$z$') # plt.ylabel(r'$\bar \Omega $') # for i in range(len(fluid_arr)): # for j in range(len(fluid_arr[i])): # if j % 2 == 0: # linestyle=(0, ()) # # making float int terms display w/o full stop in legend # legend_n = str(int_terms[i])[1:-1] # if legend_n[-1] == '.': # legend_n = legend_n[0:-1] # plt.semilogx(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle, label=f'$\gamma$ = {legend_n}') # else: # linestyle=(0, (3, 1, 1, 1)) # plt.semilogx(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle) ## plt.title(r'$\bar \Omega_{X}$, models: %s.'%(model_names)) # plt.legend() # filename = 'a1_'+str(model_name)+'_evo_slog.png' # plt.savefig(filename, facecolor=fig.get_facecolor(), edgecolor='none') # # Fluid evolution. # fig = plt.figure() # plt.xlabel('$z$') # plt.ylabel(r'$\bar \Omega $') # for i in range(len(fluid_arr)): # for j in range(len(fluid_arr[i])): # if j % 2 == 0: # linestyle=(0, ()) # # making float int terms display w/o full stop in legend # legend_n = str(int_terms[i])[1:-1] # if legend_n[-1] == '.': # legend_n = legend_n[0:-1] # plt.plot(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle, label=f'$\gamma$ = {legend_n}') # else: # linestyle=(0, (3, 1, 1, 1)) # plt.plot(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle) ## plt.title(r'$\bar \Omega_{X}$, models: %s.'%(model_names)) # plt.legend() # filename = 'a1_'+str(model_name)+'_evo.png' # plt.savefig(filename, facecolor=fig.get_facecolor(), edgecolor='none') # Magnitude vs redshift. fig = plt.figure() plt.xlabel('$z$') plt.ylabel('Magnitude') for i in range(len(mag)): # making float int terms display w/o full stop in legend legend_n = str(int_terms[i])[1:-1] if legend_n[-1] == '.': legend_n = legend_n[0:-1] plt.plot(zpicks, mag[i], lw=2, label=f'$\gamma$ = {legend_n}') # plt.title('Magnitude evolution, models: %s.'%(model_names)) plt.scatter(data['data_zpicks'], data_mag, s=50, marker='o', c='darkslategrey', alpha=0.2, label='Pantheon') plt.legend() filename = 'a1_'+str(model_name)+'_mag.png' plt.savefig(filename, facecolor=fig.get_facecolor(), edgecolor='none') plt.show() return def multi_model_hubble_residuals(data, keys, plot_var_list): ''' Redshift vs magnitude residulas for 1 interaction term models. ''' zpicks = data['zpicks'] data_mag = data['mag'] model_names = [] for model_name in keys: model_names.append(model_name) mag = [] dlpc = [] t = [] dl = [] a = [] Hz = [] da = [] dV = [] fluid_names = [] fluid_arr = [] int_terms = [] for plot_var in plot_var_list: mag.append(plot_var.get('mag')) dlpc.append(plot_var.get('dlpc')) t.append(plot_var.get('t')) dl.append(plot_var.get('dl')) a.append(plot_var.get('a')) Hz.append(plot_var.get('Hz')) da.append(plot_var.get('da')) dV.append(plot_var.get('dV')) fluid_names.append(plot_var.get('fluid_names')) fluid_arr.append(plot_var.get('fluid_arr')) int_terms.append(plot_var.get('int_terms')) dlMpc = [] for i in range(len(dlpc)): dlMpc.append(dlpc[i] * 10e-6) # Magnitude vs redshift residuals. plt.figure() plt.xlabel('$z$') plt.ylabel('Magnitude') for i in range(1,len(mag)): plt.plot(zpicks, mag[0]-mag[i], lw=2, label=model_names[i]) # plt.scatter(data['data_zpicks'], mag[0]-data_mag, s=50, marker='o', c='darkslategrey', alpha=0.2, label='Pantheon') plt.legend() # Luminosity distance vs redshift. plt.figure() plt.xlabel('$d_L$(Mpc)') plt.ylabel('$z$') # plt.title('d_L vs redshift') for i in range(1,len(mag)): plt.plot(dlMpc[i], zpicks, lw=2, label=model_names[i]) plt.legend() # Luminocity distance vs redshift residuals. plt.figure() # plt.title('d_L residuals') plt.xlabel('$d_L$(Mpc)') plt.ylabel('$z$') for i in range(1,len(mag)): plt.plot(dlMpc[0]-dlMpc[i], zpicks, lw=2, label=model_names[i]) plt.legend() plt.show() return def multi_modelcheck_extra(data, keys, plot_var_list): ''' For models with multiple interaction terms. ''' print('multi_modelcheck_extra') zpicks = data['zpicks'] data_mag = data['mag'] model_names = '' for model_name in keys: model_names += model_name+', ' model_names = model_names[:-2] mag = [] t = [] dl = [] a = [] Hz = [] da = [] dV = [] fluid_names = [] fluid_arr = [] int_terms = [] for plot_var in plot_var_list: mag.append(plot_var.get('mag')) t.append(plot_var.get('t')) dl.append(plot_var.get('dl')) a.append(plot_var.get('a')) Hz.append(plot_var.get('Hz')) da.append(plot_var.get('da')) dV.append(plot_var.get('dV')) fluid_names.append(plot_var.get('fluid_names')) fluid_arr.append(plot_var.get('fluid_arr')) int_terms.append(plot_var.get('int_terms')) # Changing time t into age age=[] for item in t: item = -item age.append(item) # # semilog x axis fluid evolution vs redshift. # fig = plt.figure() # plt.xlabel('$z$') # plt.ylabel(r'$\bar \Omega $') # for i in range(len(fluid_arr)): # for j in range(len(fluid_arr[i])): # if j == 0: # legend_n = int_terms[i] # linestyle = 'solid' # plt.semilogx(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle, label=f'$v=w=x=${legend_n[0]}') # elif j == 1: # linestyle =(0, (1, 1)) # elif j == 2: # linestyle =(0, (5, 1)) # elif j == 3: # linestyle = (0, (3, 1, 1, 1)) # plt.semilogx(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle) # plt.legend() # filename = 'a1_'+str(model_name)+'_evo_slog.png' # plt.savefig(filename, facecolor=fig.get_facecolor(), edgecolor='none') # Fluid evolution. fig = plt.figure() plt.xlabel('$z$') plt.ylabel(r'$\bar \Omega $') for i in range(len(fluid_arr)): for j in range(len(fluid_arr[i])): if j == 0: legend_n = int_terms[i] linestyle= 'solid' plt.plot(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle, label=f'$p=...=z=${legend_n[0]}') elif j == 1: linestyle = (0, (5, 1)) elif j == range(len(fluid_arr[i]))[-1]: linestyle = (0, (1, 1)) else: continue plt.plot(zpicks, fluid_arr[i][j], lw=2, color="C{}".format(i), ls=linestyle) plt.legend() filename = 'a1_'+str(model_name)+'_evo.png' plt.savefig(filename, facecolor=fig.get_facecolor(), edgecolor='none') # Magnitude vs redshift. fig = plt.figure() plt.xlabel('$z$') plt.ylabel('Magnitude') for i in range(len(mag)): legend_n = int_terms[i] plt.plot(zpicks, mag[i], lw=2, label=f'$p=...=z=${legend_n[0]}') plt.scatter(data['data_zpicks'], data_mag, s=50, marker='o', c='darkslategrey', alpha=0.2, label='Pantheon') plt.legend() filename = 'a1_'+str(model_name)+'_mag.png' plt.savefig(filename, facecolor=fig.get_facecolor(), edgecolor='none') plt.show() return #linestyles = OrderedDict( # [('solid', (0, ())), # ('loosely dotted', (0, (1, 10))), # ('dotted', (0, (1, 5))), # ('densely dotted', (0, (1, 1))), # # ('loosely dashed', (0, (5, 10))), # ('dashed', (0, (5, 5))), # ('densely dashed', (0, (5, 1))), # # ('loosely dashdotted', (0, (3, 10, 1, 10))), # ('dashdotted', (0, (3, 5, 1, 5))), # ('densely dashdotted', (0, (3, 1, 1, 1))), # # ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), # ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), # ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])
[ "matplotlib.pyplot.title", "matplotlib.style.use", "os.walk", "numpy.argmin", "numpy.hsplit", "numpy.isnan", "matplotlib.pyplot.figure", "results.load", "os.path.join", "matplotlib.pyplot.locator_params", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.subplots", "matplotlib.pyplot.axhline", "numpy.stack", "matplotlib.pyplot.show", "matplotlib.pyplot.legend", "numpy.asarray", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.grid", "numpy.delete", "matplotlib.pyplot.hist", "matplotlib.pyplot.plot", "matplotlib.pyplot.scatter", "time.time", "numpy.array", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((243, 267), 'matplotlib.style.use', 'mpl.style.use', (['"""default"""'], {}), "('default')\n", (256, 267), True, 'import matplotlib as mpl\n'), ((311, 343), 'matplotlib.style.use', 'mpl.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (324, 343), True, 'import matplotlib as mpl\n'), ((465, 513), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (484, 513), True, 'import matplotlib.pyplot as plt\n'), ((809, 821), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (819, 821), True, 'import matplotlib.pyplot as plt\n'), ((867, 887), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name'], {}), '(var_name)\n', (877, 887), True, 'import matplotlib.pyplot as plt\n'), ((1111, 1143), 'matplotlib.pyplot.hist', 'plt.hist', (['var', '(50)'], {'facecolor': 'hue'}), '(var, 50, facecolor=hue)\n', (1119, 1143), True, 'import matplotlib.pyplot as plt\n'), ((1148, 1185), 'matplotlib.pyplot.locator_params', 'plt.locator_params', ([], {'axis': '"""x"""', 'nbins': '(5)'}), "(axis='x', nbins=5)\n", (1166, 1185), True, 'import matplotlib.pyplot as plt\n'), ((1403, 1436), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (1415, 1436), False, 'import os\n'), ((1441, 1462), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (1452, 1462), True, 'import matplotlib.pyplot as plt\n'), ((1488, 1500), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1498, 1500), True, 'import matplotlib.pyplot as plt\n'), ((1505, 1525), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name'], {}), '(var_name)\n', (1515, 1525), True, 'import matplotlib.pyplot as plt\n'), ((1717, 1755), 'matplotlib.pyplot.plot', 'plt.plot', (['var', 'slnprob', '"""."""'], {'color': 'hue'}), "(var, slnprob, '.', color=hue)\n", (1725, 1755), True, 'import matplotlib.pyplot as plt\n'), ((1760, 1797), 'matplotlib.pyplot.locator_params', 'plt.locator_params', ([], {'axis': '"""x"""', 'nbins': '(5)'}), "(axis='x', nbins=5)\n", (1778, 1797), True, 'import matplotlib.pyplot as plt\n'), ((2015, 2048), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (2027, 2048), False, 'import os\n'), ((2053, 2074), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (2064, 2074), True, 'import matplotlib.pyplot as plt\n'), ((2094, 2106), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2104, 2106), True, 'import matplotlib.pyplot as plt\n'), ((2111, 2136), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""step number"""'], {}), "('step number')\n", (2121, 2136), True, 'import matplotlib.pyplot as plt\n'), ((2182, 2202), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['var_name'], {}), '(var_name)\n', (2192, 2202), True, 'import matplotlib.pyplot as plt\n'), ((2406, 2469), 'matplotlib.pyplot.plot', 'plt.plot', (['var.T', '"""-"""'], {'color': '"""k"""', 'alpha': '(0.3)', 'lw': '(2)', 'label': '"""chain"""'}), "(var.T, '-', color='k', alpha=0.3, lw=2, label='chain')\n", (2414, 2469), True, 'import matplotlib.pyplot as plt\n'), ((2474, 2533), 'matplotlib.pyplot.axhline', 'plt.axhline', (['var_true'], {'color': 'hue', 'lw': '(2)', 'label': '"""input value"""'}), "(var_true, color=hue, lw=2, label='input value')\n", (2485, 2533), True, 'import matplotlib.pyplot as plt\n'), ((2538, 2575), 'matplotlib.pyplot.locator_params', 'plt.locator_params', ([], {'axis': '"""x"""', 'nbins': '(5)'}), "(axis='x', nbins=5)\n", (2556, 2575), True, 'import matplotlib.pyplot as plt\n'), ((2580, 2592), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2590, 2592), True, 'import matplotlib.pyplot as plt\n'), ((2810, 2843), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (2822, 2843), False, 'import os\n'), ((2848, 2869), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (2859, 2869), True, 'import matplotlib.pyplot as plt\n'), ((2875, 2896), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (2883, 2896), True, 'import matplotlib.pyplot as plt\n'), ((3204, 3216), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3214, 3216), True, 'import matplotlib.pyplot as plt\n'), ((3262, 3282), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name'], {}), '(var_name)\n', (3272, 3282), True, 'import matplotlib.pyplot as plt\n'), ((3503, 3535), 'matplotlib.pyplot.hist', 'plt.hist', (['var', '(50)'], {'facecolor': 'hue'}), '(var, 50, facecolor=hue)\n', (3511, 3535), True, 'import matplotlib.pyplot as plt\n'), ((3753, 3786), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (3765, 3786), False, 'import os\n'), ((3791, 3812), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (3802, 3812), True, 'import matplotlib.pyplot as plt\n'), ((3838, 3850), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3848, 3850), True, 'import matplotlib.pyplot as plt\n'), ((3855, 3875), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name'], {}), '(var_name)\n', (3865, 3875), True, 'import matplotlib.pyplot as plt\n'), ((4064, 4102), 'matplotlib.pyplot.plot', 'plt.plot', (['var', 'slnprob', '"""."""'], {'color': 'hue'}), "(var, slnprob, '.', color=hue)\n", (4072, 4102), True, 'import matplotlib.pyplot as plt\n'), ((4320, 4353), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (4332, 4353), False, 'import os\n'), ((4358, 4379), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (4369, 4379), True, 'import matplotlib.pyplot as plt\n'), ((4399, 4411), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4409, 4411), True, 'import matplotlib.pyplot as plt\n'), ((4416, 4441), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""step number"""'], {}), "('step number')\n", (4426, 4441), True, 'import matplotlib.pyplot as plt\n'), ((4487, 4507), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['var_name'], {}), '(var_name)\n', (4497, 4507), True, 'import matplotlib.pyplot as plt\n'), ((4708, 4750), 'matplotlib.pyplot.plot', 'plt.plot', (['var.T', '"""-"""'], {'color': '"""k"""', 'alpha': '(0.3)'}), "(var.T, '-', color='k', alpha=0.3)\n", (4716, 4750), True, 'import matplotlib.pyplot as plt\n'), ((4755, 4787), 'matplotlib.pyplot.axhline', 'plt.axhline', (['var_true'], {'color': 'hue'}), '(var_true, color=hue)\n', (4766, 4787), True, 'import matplotlib.pyplot as plt\n'), ((5005, 5038), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (5017, 5038), False, 'import os\n'), ((5043, 5064), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (5054, 5064), True, 'import matplotlib.pyplot as plt\n'), ((5070, 5091), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (5078, 5091), True, 'import matplotlib.pyplot as plt\n'), ((5496, 5560), 'os.path.join', 'os.path.join', (["('./results_error_vs_data_plots/' + firstderivs_key)"], {}), "('./results_error_vs_data_plots/' + firstderivs_key)\n", (5508, 5560), False, 'import os\n'), ((5821, 5839), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (5828, 5839), False, 'import os\n'), ((11993, 12003), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12001, 12003), True, 'import matplotlib.pyplot as plt\n'), ((12583, 12595), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (12593, 12595), True, 'import matplotlib.pyplot as plt\n'), ((12600, 12617), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (12610, 12617), True, 'import matplotlib.pyplot as plt\n'), ((12622, 12652), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\bar \\\\Omega $"""'], {}), "('$\\\\bar \\\\Omega $')\n", (12632, 12652), True, 'import matplotlib.pyplot as plt\n'), ((12656, 12670), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (12664, 12670), True, 'import matplotlib.pyplot as plt\n'), ((12772, 12784), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (12782, 12784), True, 'import matplotlib.pyplot as plt\n'), ((12789, 12899), 'matplotlib.pyplot.title', 'plt.title', (['f"""$\\\\bar \\\\Omega_{{X}}$ evolution\n Model: {firstderivs_key}, int_terms = {int_terms}"""'], {}), '(\n f"""$\\\\bar \\\\Omega_{{X}}$ evolution\n Model: {firstderivs_key}, int_terms = {int_terms}"""\n )\n', (12798, 12899), True, 'import matplotlib.pyplot as plt\n'), ((12956, 12968), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (12966, 12968), True, 'import matplotlib.pyplot as plt\n'), ((12973, 13087), 'matplotlib.pyplot.title', 'plt.title', (['f"""Angular diameter distance evolution\n Model: {firstderivs_key}, int_terms = {int_terms}"""'], {}), '(\n f"""Angular diameter distance evolution\n Model: {firstderivs_key}, int_terms = {int_terms}"""\n )\n', (12982, 13087), True, 'import matplotlib.pyplot as plt\n'), ((13096, 13111), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""z"""'], {}), "('z')\n", (13106, 13111), True, 'import matplotlib.pyplot as plt\n'), ((13116, 13146), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$ d_A (H_0 / c)$"""'], {}), "('$ d_A (H_0 / c)$')\n", (13126, 13146), True, 'import matplotlib.pyplot as plt\n'), ((13152, 13166), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (13160, 13166), True, 'import matplotlib.pyplot as plt\n'), ((13182, 13195), 'numpy.argmin', 'np.argmin', (['da'], {}), '(da)\n', (13191, 13195), True, 'import numpy as np\n'), ((13397, 13409), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13407, 13409), True, 'import matplotlib.pyplot as plt\n'), ((13414, 13503), 'matplotlib.pyplot.title', 'plt.title', (['f"""$d_V$ evolution\n Model: {firstderivs_key}, int_terms = {int_terms}"""'], {}), '(\n f"""$d_V$ evolution\n Model: {firstderivs_key}, int_terms = {int_terms}""")\n', (13423, 13503), True, 'import matplotlib.pyplot as plt\n'), ((13518, 13533), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""z"""'], {}), "('z')\n", (13528, 13533), True, 'import matplotlib.pyplot as plt\n'), ((13538, 13568), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$ d_V (z)$ [Mpc]"""'], {}), "('$ d_V (z)$ [Mpc]')\n", (13548, 13568), True, 'import matplotlib.pyplot as plt\n'), ((13574, 13588), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (13582, 13588), True, 'import matplotlib.pyplot as plt\n'), ((13593, 13613), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'dV'], {}), '(zpicks, dV)\n', (13601, 13613), True, 'import matplotlib.pyplot as plt\n'), ((13658, 13670), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13668, 13670), True, 'import matplotlib.pyplot as plt\n'), ((13675, 13692), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (13685, 13692), True, 'import matplotlib.pyplot as plt\n'), ((13697, 13726), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$d_L$*($H_0$/c)"""'], {}), "('$d_L$*($H_0$/c)')\n", (13707, 13726), True, 'import matplotlib.pyplot as plt\n'), ((13731, 13745), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (13739, 13745), True, 'import matplotlib.pyplot as plt\n'), ((13750, 13770), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'dl'], {}), '(zpicks, dl)\n', (13758, 13770), True, 'import matplotlib.pyplot as plt\n'), ((13775, 13875), 'matplotlib.pyplot.title', 'plt.title', (['(\'$d_L$ evolution\' + """\n Model: %s, int_terms = %s""" % (firstderivs_key,\n int_terms))'], {}), '(\'$d_L$ evolution\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))\n', (13784, 13875), True, 'import matplotlib.pyplot as plt\n'), ((13905, 13917), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13915, 13917), True, 'import matplotlib.pyplot as plt\n'), ((13922, 13939), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (13932, 13939), True, 'import matplotlib.pyplot as plt\n'), ((13944, 13959), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""H"""'], {}), "('H')\n", (13954, 13959), True, 'import matplotlib.pyplot as plt\n'), ((13964, 13978), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (13972, 13978), True, 'import matplotlib.pyplot as plt\n'), ((13983, 14003), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'Hz'], {}), '(zpicks, Hz)\n', (13991, 14003), True, 'import matplotlib.pyplot as plt\n'), ((14008, 14109), 'matplotlib.pyplot.title', 'plt.title', (['(\'$H(z)$ evolution\' + """\n Model: %s, int_terms = %s""" % (firstderivs_key,\n int_terms))'], {}), '(\'$H(z)$ evolution\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))\n', (14017, 14109), True, 'import matplotlib.pyplot as plt\n'), ((14151, 14163), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14161, 14163), True, 'import matplotlib.pyplot as plt\n'), ((14168, 14185), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (14178, 14185), True, 'import matplotlib.pyplot as plt\n'), ((14190, 14205), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""a"""'], {}), "('a')\n", (14200, 14205), True, 'import matplotlib.pyplot as plt\n'), ((14210, 14224), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (14218, 14224), True, 'import matplotlib.pyplot as plt\n'), ((14229, 14248), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'a'], {}), '(zpicks, a)\n', (14237, 14248), True, 'import matplotlib.pyplot as plt\n'), ((14253, 14375), 'matplotlib.pyplot.title', 'plt.title', (['(\'Scale factor evolution with redshift \' + \n """\n Model: %s, int_terms = %s""" % (firstderivs_key, int_terms))'], {}), '(\'Scale factor evolution with redshift \' + \n """\n Model: %s, int_terms = %s""" % (firstderivs_key, int_terms))\n', (14262, 14375), True, 'import matplotlib.pyplot as plt\n'), ((14426, 14438), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14436, 14438), True, 'import matplotlib.pyplot as plt\n'), ((14443, 14460), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (14453, 14460), True, 'import matplotlib.pyplot as plt\n'), ((14465, 14480), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""a"""'], {}), "('a')\n", (14475, 14480), True, 'import matplotlib.pyplot as plt\n'), ((14485, 14499), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (14493, 14499), True, 'import matplotlib.pyplot as plt\n'), ((14504, 14518), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'a'], {}), '(t, a)\n', (14512, 14518), True, 'import matplotlib.pyplot as plt\n'), ((14523, 14640), 'matplotlib.pyplot.title', 'plt.title', (['(\'Scale factor evolution with time\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))'], {}), '(\'Scale factor evolution with time\' + \n """\n Model: %s, int_terms = %s""" % (firstderivs_key, int_terms))\n', (14532, 14640), True, 'import matplotlib.pyplot as plt\n'), ((14668, 14680), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14678, 14680), True, 'import matplotlib.pyplot as plt\n'), ((14685, 14702), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (14695, 14702), True, 'import matplotlib.pyplot as plt\n'), ((14707, 14724), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$z$"""'], {}), "('$z$')\n", (14717, 14724), True, 'import matplotlib.pyplot as plt\n'), ((14729, 14743), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (14737, 14743), True, 'import matplotlib.pyplot as plt\n'), ((14748, 14767), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'zpicks'], {}), '(t, zpicks)\n', (14756, 14767), True, 'import matplotlib.pyplot as plt\n'), ((14772, 14875), 'matplotlib.pyplot.title', 'plt.title', (['(\'Redshift evolution\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))'], {}), '(\'Redshift evolution\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))\n', (14781, 14875), True, 'import matplotlib.pyplot as plt\n'), ((14909, 14921), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14919, 14921), True, 'import matplotlib.pyplot as plt\n'), ((14926, 14943), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (14936, 14943), True, 'import matplotlib.pyplot as plt\n'), ((14948, 14971), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (14958, 14971), True, 'import matplotlib.pyplot as plt\n'), ((14976, 15080), 'matplotlib.pyplot.title', 'plt.title', (['(\'Magnitude evolution\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))'], {}), '(\'Magnitude evolution\' + """\n Model: %s, int_terms = %s""" % (\n firstderivs_key, int_terms))\n', (14985, 15080), True, 'import matplotlib.pyplot as plt\n'), ((15084, 15126), 'matplotlib.pyplot.scatter', 'plt.scatter', (['input_zpicks', 'mag'], {'marker': '"""."""'}), "(input_zpicks, mag, marker='.')\n", (15095, 15126), True, 'import matplotlib.pyplot as plt\n'), ((15132, 15142), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15140, 15142), True, 'import matplotlib.pyplot as plt\n'), ((18175, 18187), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (18185, 18187), True, 'import matplotlib.pyplot as plt\n'), ((18192, 18209), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (18202, 18209), True, 'import matplotlib.pyplot as plt\n'), ((18214, 18237), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (18224, 18237), True, 'import matplotlib.pyplot as plt\n'), ((18586, 18699), 'matplotlib.pyplot.scatter', 'plt.scatter', (["data['data_zpicks']", 'data_mag'], {'s': '(50)', 'marker': '"""o"""', 'c': '"""darkslategrey"""', 'alpha': '(0.2)', 'label': '"""Pantheon"""'}), "(data['data_zpicks'], data_mag, s=50, marker='o', c=\n 'darkslategrey', alpha=0.2, label='Pantheon')\n", (18597, 18699), True, 'import matplotlib.pyplot as plt\n'), ((18699, 18711), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (18709, 18711), True, 'import matplotlib.pyplot as plt\n'), ((18840, 18850), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18848, 18850), True, 'import matplotlib.pyplot as plt\n'), ((19942, 19954), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (19952, 19954), True, 'import matplotlib.pyplot as plt\n'), ((19959, 19976), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (19969, 19976), True, 'import matplotlib.pyplot as plt\n'), ((19981, 20004), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (19991, 20004), True, 'import matplotlib.pyplot as plt\n'), ((20230, 20242), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20240, 20242), True, 'import matplotlib.pyplot as plt\n'), ((20287, 20299), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20297, 20299), True, 'import matplotlib.pyplot as plt\n'), ((20304, 20328), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$d_L$(Mpc)"""'], {}), "('$d_L$(Mpc)')\n", (20314, 20328), True, 'import matplotlib.pyplot as plt\n'), ((20333, 20350), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$z$"""'], {}), "('$z$')\n", (20343, 20350), True, 'import matplotlib.pyplot as plt\n'), ((20484, 20496), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20494, 20496), True, 'import matplotlib.pyplot as plt\n'), ((20551, 20563), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20561, 20563), True, 'import matplotlib.pyplot as plt\n'), ((20600, 20624), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$d_L$(Mpc)"""'], {}), "('$d_L$(Mpc)')\n", (20610, 20624), True, 'import matplotlib.pyplot as plt\n'), ((20629, 20646), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$z$"""'], {}), "('$z$')\n", (20639, 20646), True, 'import matplotlib.pyplot as plt\n'), ((20755, 20767), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20765, 20767), True, 'import matplotlib.pyplot as plt\n'), ((20773, 20783), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20781, 20783), True, 'import matplotlib.pyplot as plt\n'), ((22773, 22785), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (22783, 22785), True, 'import matplotlib.pyplot as plt\n'), ((22790, 22807), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (22800, 22807), True, 'import matplotlib.pyplot as plt\n'), ((22812, 22842), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\bar \\\\Omega $"""'], {}), "('$\\\\bar \\\\Omega $')\n", (22822, 22842), True, 'import matplotlib.pyplot as plt\n'), ((23439, 23451), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (23449, 23451), True, 'import matplotlib.pyplot as plt\n'), ((23615, 23627), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (23625, 23627), True, 'import matplotlib.pyplot as plt\n'), ((23632, 23649), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$z$"""'], {}), "('$z$')\n", (23642, 23649), True, 'import matplotlib.pyplot as plt\n'), ((23654, 23677), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (23664, 23677), True, 'import matplotlib.pyplot as plt\n'), ((23817, 23930), 'matplotlib.pyplot.scatter', 'plt.scatter', (["data['data_zpicks']", 'data_mag'], {'s': '(50)', 'marker': '"""o"""', 'c': '"""darkslategrey"""', 'alpha': '(0.2)', 'label': '"""Pantheon"""'}), "(data['data_zpicks'], data_mag, s=50, marker='o', c=\n 'darkslategrey', alpha=0.2, label='Pantheon')\n", (23828, 23930), True, 'import matplotlib.pyplot as plt\n'), ((23930, 23942), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (23940, 23942), True, 'import matplotlib.pyplot as plt\n'), ((24071, 24081), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (24079, 24081), True, 'import matplotlib.pyplot as plt\n'), ((6104, 6129), 'results.load', 'load', (['folder', '"""sd_list.p"""'], {}), "(folder, 'sd_list.p')\n", (6108, 6129), False, 'from results import load\n'), ((6151, 6178), 'results.load', 'load', (['folder', '"""mean_list.p"""'], {}), "(folder, 'mean_list.p')\n", (6155, 6178), False, 'from results import load\n'), ((6198, 6223), 'results.load', 'load', (['folder', '"""vc_list.p"""'], {}), "(folder, 'vc_list.p')\n", (6202, 6223), False, 'from results import load\n'), ((6246, 6274), 'results.load', 'load', (['folder', '"""sigma_list.p"""'], {}), "(folder, 'sigma_list.p')\n", (6250, 6274), False, 'from results import load\n'), ((6299, 6329), 'results.load', 'load', (['folder', '"""npoints_list.p"""'], {}), "(folder, 'npoints_list.p')\n", (6303, 6329), False, 'from results import load\n'), ((7124, 7136), 'numpy.array', 'np.array', (['sd'], {}), '(sd)\n', (7132, 7136), True, 'import numpy as np\n'), ((7150, 7164), 'numpy.asarray', 'np.asarray', (['vc'], {}), '(vc)\n', (7160, 7164), True, 'import numpy as np\n'), ((7181, 7203), 'numpy.asarray', 'np.asarray', (['sigma_list'], {}), '(sigma_list)\n', (7191, 7203), True, 'import numpy as np\n'), ((7222, 7246), 'numpy.asarray', 'np.asarray', (['npoints_list'], {}), '(npoints_list)\n', (7232, 7246), True, 'import numpy as np\n'), ((12715, 12767), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'fluid_arr[i]'], {'label': 'fluid_names[i]'}), '(zpicks, fluid_arr[i], label=fluid_names[i])\n', (12723, 12767), True, 'import matplotlib.pyplot as plt\n'), ((13229, 13275), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks[:, da_index]', 'da[:, da_index]'], {}), '(zpicks[:, da_index], da[:, da_index])\n', (13237, 13275), True, 'import matplotlib.pyplot as plt\n'), ((13283, 13329), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks[da_index, :]', 'da[da_index, :]'], {}), '(zpicks[da_index, :], da[da_index, :])\n', (13291, 13329), True, 'import matplotlib.pyplot as plt\n'), ((13348, 13368), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'da'], {}), '(zpicks, da)\n', (13356, 13368), True, 'import matplotlib.pyplot as plt\n'), ((18454, 18517), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'mag[i]'], {'lw': '(2)', 'label': 'f"""$\\\\gamma$ = {legend_n}"""'}), "(zpicks, mag[i], lw=2, label=f'$\\\\gamma$ = {legend_n}')\n", (18462, 18517), True, 'import matplotlib.pyplot as plt\n'), ((20045, 20106), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', '(mag[0] - mag[i])'], {'lw': '(2)', 'label': 'model_names[i]'}), '(zpicks, mag[0] - mag[i], lw=2, label=model_names[i])\n', (20053, 20106), True, 'import matplotlib.pyplot as plt\n'), ((20425, 20479), 'matplotlib.pyplot.plot', 'plt.plot', (['dlMpc[i]', 'zpicks'], {'lw': '(2)', 'label': 'model_names[i]'}), '(dlMpc[i], zpicks, lw=2, label=model_names[i])\n', (20433, 20479), True, 'import matplotlib.pyplot as plt\n'), ((20687, 20752), 'matplotlib.pyplot.plot', 'plt.plot', (['(dlMpc[0] - dlMpc[i])', 'zpicks'], {'lw': '(2)', 'label': 'model_names[i]'}), '(dlMpc[0] - dlMpc[i], zpicks, lw=2, label=model_names[i])\n', (20695, 20752), True, 'import matplotlib.pyplot as plt\n'), ((23748, 23812), 'matplotlib.pyplot.plot', 'plt.plot', (['zpicks', 'mag[i]'], {'lw': '(2)', 'label': 'f"""$p=...=z=${legend_n[0]}"""'}), "(zpicks, mag[i], lw=2, label=f'$p=...=z=${legend_n[0]}')\n", (23756, 23812), True, 'import matplotlib.pyplot as plt\n'), ((1206, 1217), 'time.time', 'time.time', ([], {}), '()\n', (1215, 1217), False, 'import time\n'), ((1818, 1829), 'time.time', 'time.time', ([], {}), '()\n', (1827, 1829), False, 'import time\n'), ((2613, 2624), 'time.time', 'time.time', ([], {}), '()\n', (2622, 2624), False, 'import time\n'), ((3556, 3567), 'time.time', 'time.time', ([], {}), '()\n', (3565, 3567), False, 'import time\n'), ((4123, 4134), 'time.time', 'time.time', ([], {}), '()\n', (4132, 4134), False, 'import time\n'), ((4808, 4819), 'time.time', 'time.time', ([], {}), '()\n', (4817, 4819), False, 'import time\n'), ((7640, 7678), 'numpy.stack', 'np.stack', (['(npoints, sigma, vc)'], {'axis': '(1)'}), '((npoints, sigma, vc), axis=1)\n', (7648, 7678), True, 'import numpy as np\n'), ((7701, 7740), 'numpy.delete', 'np.delete', (['p_stack', 'vc_above_p_index', '(0)'], {}), '(p_stack, vc_above_p_index, 0)\n', (7710, 7740), True, 'import numpy as np\n'), ((8669, 8690), 'numpy.hsplit', 'np.hsplit', (['p_stack', '(3)'], {}), '(p_stack, 3)\n', (8678, 8690), True, 'import numpy as np\n'), ((8996, 9010), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9008, 9010), True, 'import matplotlib.pyplot as plt\n'), ((9338, 9364), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Dataset size"""'], {}), "('Dataset size')\n", (9348, 9364), True, 'import matplotlib.pyplot as plt\n'), ((9377, 9419), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Sigma of noise added to data"""'], {}), "('Sigma of noise added to data')\n", (9387, 9419), True, 'import matplotlib.pyplot as plt\n'), ((9580, 9592), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (9590, 9592), True, 'import matplotlib.pyplot as plt\n'), ((10002, 10040), 'numpy.stack', 'np.stack', (['(npoints, sigma, sd)'], {'axis': '(1)'}), '((npoints, sigma, sd), axis=1)\n', (10010, 10040), True, 'import numpy as np\n'), ((10063, 10102), 'numpy.delete', 'np.delete', (['x_stack', 'sd_above_x_index', '(0)'], {}), '(x_stack, sd_above_x_index, 0)\n', (10072, 10102), True, 'import numpy as np\n'), ((11029, 11050), 'numpy.hsplit', 'np.hsplit', (['x_stack', '(3)'], {}), '(x_stack, 3)\n', (11038, 11050), True, 'import numpy as np\n'), ((11352, 11366), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11364, 11366), True, 'import matplotlib.pyplot as plt\n'), ((11694, 11720), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Dataset size"""'], {}), "('Dataset size')\n", (11704, 11720), True, 'import matplotlib.pyplot as plt\n'), ((11733, 11775), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Sigma of noise added to data"""'], {}), "('Sigma of noise added to data')\n", (11743, 11775), True, 'import matplotlib.pyplot as plt\n'), ((11931, 11943), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (11941, 11943), True, 'import matplotlib.pyplot as plt\n'), ((12481, 12493), 'numpy.isnan', 'np.isnan', (['Hz'], {}), '(Hz)\n', (12489, 12493), True, 'import numpy as np\n'), ((8357, 8381), 'numpy.delete', 'np.delete', (['p_stack', 'k', '(0)'], {}), '(p_stack, k, 0)\n', (8366, 8381), True, 'import numpy as np\n'), ((10719, 10743), 'numpy.delete', 'np.delete', (['x_stack', 'k', '(0)'], {}), '(x_stack, k, 0)\n', (10728, 10743), True, 'import numpy as np\n'), ((8460, 8484), 'numpy.delete', 'np.delete', (['p_stack', 'l', '(0)'], {}), '(p_stack, l, 0)\n', (8469, 8484), True, 'import numpy as np\n'), ((10822, 10846), 'numpy.delete', 'np.delete', (['x_stack', 'l', '(0)'], {}), '(x_stack, l, 0)\n', (10831, 10846), True, 'import numpy as np\n')]
import json import random import numpy as np import pytest_caprng def test_random_state_serialization(): orig_state = random.getstate() json_transduced = json.loads(json.dumps(orig_state)) bak_state = pytest_caprng.to_random_state(json_transduced) random.random() # Mutate the state. assert orig_state != random.getstate() random.setstate(bak_state) assert orig_state == random.getstate() def test_np_random_state_serialization(): orig_state = np.random.get_state() bak_state = pytest_caprng.to_json_serializable_np_random_state(orig_state) # ========================================================================= # mutate the state and take a sample. mt has a very long period. the # probability of two equal floating point samples is very, very low. # since i'm not sure if the state structure will change and testing for # array equality requires array comparisons not the == operator, this # is a cleaner test. # ========================================================================= orig_sample = np.random.random() np.random.set_state(bak_state) restored_sample = np.random.random() assert orig_sample == restored_sample
[ "pytest_caprng.to_random_state", "numpy.random.get_state", "pytest_caprng.to_json_serializable_np_random_state", "json.dumps", "numpy.random.set_state", "random.random", "numpy.random.random", "random.setstate", "random.getstate" ]
[((124, 141), 'random.getstate', 'random.getstate', ([], {}), '()\n', (139, 141), False, 'import random\n'), ((215, 261), 'pytest_caprng.to_random_state', 'pytest_caprng.to_random_state', (['json_transduced'], {}), '(json_transduced)\n', (244, 261), False, 'import pytest_caprng\n'), ((267, 282), 'random.random', 'random.random', ([], {}), '()\n', (280, 282), False, 'import random\n'), ((352, 378), 'random.setstate', 'random.setstate', (['bak_state'], {}), '(bak_state)\n', (367, 378), False, 'import random\n'), ((483, 504), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (502, 504), True, 'import numpy as np\n'), ((521, 583), 'pytest_caprng.to_json_serializable_np_random_state', 'pytest_caprng.to_json_serializable_np_random_state', (['orig_state'], {}), '(orig_state)\n', (571, 583), False, 'import pytest_caprng\n'), ((1084, 1102), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1100, 1102), True, 'import numpy as np\n'), ((1108, 1138), 'numpy.random.set_state', 'np.random.set_state', (['bak_state'], {}), '(bak_state)\n', (1127, 1138), True, 'import numpy as np\n'), ((1161, 1179), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1177, 1179), True, 'import numpy as np\n'), ((175, 197), 'json.dumps', 'json.dumps', (['orig_state'], {}), '(orig_state)\n', (185, 197), False, 'import json\n'), ((329, 346), 'random.getstate', 'random.getstate', ([], {}), '()\n', (344, 346), False, 'import random\n'), ((404, 421), 'random.getstate', 'random.getstate', ([], {}), '()\n', (419, 421), False, 'import random\n')]
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np from typing import List from .detect import BoundingBox def cast_pn_to_xyz(p_dst, normal, cam_v): """ Cast plane-distance + normal inputs into camera xyz coordinate space Args: p_dst: a float list with shape [..., 1], recording the plane-distance from camera position normal: a float list with shape [..., 3], recording the normal direction related to camera space cam_v: a float list with shape [..., 3], recording the eye direction of each elements Returns: a float list with shape [..., 3], the camera space coordinate """ normal_norm = normal / np.linalg.norm(normal, axis=-1, keepdims=True) cam_v_norm = cam_v / np.linalg.norm(cam_v, axis=-1, keepdims=True) cosine = np.sum(normal_norm * cam_v_norm, axis=-1, keepdims=True) cosine = np.where(cosine == 0., 0.000001, cosine) fov_xyz = p_dst / cosine * cam_v_norm return fov_xyz def cast_d_to_xyz(d_dst: np.ndarray, cam_v): # cam_v_norm = cam_v / cam_v[..., :1] if d_dst.ndim == 2: d_dst = np.expand_dims(d_dst, axis=-1) fov_xyz = d_dst * cam_v return fov_xyz def mask_vox_by_bbox(vox_size: List, bbox: BoundingBox): dim_index = [np.arange(a, dtype=np.int32) for a in vox_size] dim_index = np.stack(np.meshgrid(*dim_index, indexing='ij'), axis=-1) pos_mask = np.ones(vox_size, dtype=np.uint8) neg_mask = np.zeros(vox_size, dtype=np.uint8) dim_mask_lower = np.where(np.all(dim_index >= bbox.min, axis=-1), pos_mask, neg_mask) dim_mask_upper = np.where(np.all(dim_index <= bbox.max, axis=-1), pos_mask, neg_mask) dim_mask = np.where(np.logical_and(dim_mask_upper, dim_mask_lower), pos_mask, neg_mask).astype(np.int32) return dim_mask def map_vox_into_coord(vox_size, vox_stride=1): dim_index = [np.arange(a, dtype=np.int32) for a in vox_size] dim_index = np.stack(np.meshgrid(*dim_index, indexing='ij'), axis=-1).astype(np.float32) dim_index = dim_index * vox_stride + vox_stride / 2 return dim_index
[ "numpy.meshgrid", "numpy.sum", "numpy.logical_and", "numpy.zeros", "numpy.ones", "numpy.expand_dims", "numpy.where", "numpy.linalg.norm", "numpy.arange", "numpy.all" ]
[((834, 890), 'numpy.sum', 'np.sum', (['(normal_norm * cam_v_norm)'], {'axis': '(-1)', 'keepdims': '(True)'}), '(normal_norm * cam_v_norm, axis=-1, keepdims=True)\n', (840, 890), True, 'import numpy as np\n'), ((904, 942), 'numpy.where', 'np.where', (['(cosine == 0.0)', '(1e-06)', 'cosine'], {}), '(cosine == 0.0, 1e-06, cosine)\n', (912, 942), True, 'import numpy as np\n'), ((1426, 1459), 'numpy.ones', 'np.ones', (['vox_size'], {'dtype': 'np.uint8'}), '(vox_size, dtype=np.uint8)\n', (1433, 1459), True, 'import numpy as np\n'), ((1475, 1509), 'numpy.zeros', 'np.zeros', (['vox_size'], {'dtype': 'np.uint8'}), '(vox_size, dtype=np.uint8)\n', (1483, 1509), True, 'import numpy as np\n'), ((703, 749), 'numpy.linalg.norm', 'np.linalg.norm', (['normal'], {'axis': '(-1)', 'keepdims': '(True)'}), '(normal, axis=-1, keepdims=True)\n', (717, 749), True, 'import numpy as np\n'), ((775, 820), 'numpy.linalg.norm', 'np.linalg.norm', (['cam_v'], {'axis': '(-1)', 'keepdims': '(True)'}), '(cam_v, axis=-1, keepdims=True)\n', (789, 820), True, 'import numpy as np\n'), ((1135, 1165), 'numpy.expand_dims', 'np.expand_dims', (['d_dst'], {'axis': '(-1)'}), '(d_dst, axis=-1)\n', (1149, 1165), True, 'import numpy as np\n'), ((1289, 1317), 'numpy.arange', 'np.arange', (['a'], {'dtype': 'np.int32'}), '(a, dtype=np.int32)\n', (1298, 1317), True, 'import numpy as np\n'), ((1362, 1400), 'numpy.meshgrid', 'np.meshgrid', (['*dim_index'], {'indexing': '"""ij"""'}), "(*dim_index, indexing='ij')\n", (1373, 1400), True, 'import numpy as np\n'), ((1540, 1578), 'numpy.all', 'np.all', (['(dim_index >= bbox.min)'], {'axis': '(-1)'}), '(dim_index >= bbox.min, axis=-1)\n', (1546, 1578), True, 'import numpy as np\n'), ((1630, 1668), 'numpy.all', 'np.all', (['(dim_index <= bbox.max)'], {'axis': '(-1)'}), '(dim_index <= bbox.max, axis=-1)\n', (1636, 1668), True, 'import numpy as np\n'), ((1886, 1914), 'numpy.arange', 'np.arange', (['a'], {'dtype': 'np.int32'}), '(a, dtype=np.int32)\n', (1895, 1914), True, 'import numpy as np\n'), ((1714, 1760), 'numpy.logical_and', 'np.logical_and', (['dim_mask_upper', 'dim_mask_lower'], {}), '(dim_mask_upper, dim_mask_lower)\n', (1728, 1760), True, 'import numpy as np\n'), ((1959, 1997), 'numpy.meshgrid', 'np.meshgrid', (['*dim_index'], {'indexing': '"""ij"""'}), "(*dim_index, indexing='ij')\n", (1970, 1997), True, 'import numpy as np\n')]
import os.path as osp import numpy as np import scipy.sparse as sp import networkx as nx import pandas as pd import os import time import torch from scipy.linalg import fractional_matrix_power, inv import torch_geometric.transforms as T from torch_geometric.data import Data from torch_geometric.utils import to_undirected, is_undirected, to_networkx from networkx.algorithms.components import is_weakly_connected from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops, to_dense_adj from torch_scatter import scatter_add import scipy from cal_fast_pagerank import * # import fast_pagerank def get_undirected_adj(edge_index, num_nodes, dtype): edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype, device=edge_index.device) fill_value = 1 edge_index, edge_weight = add_self_loops( edge_index, edge_weight, fill_value, num_nodes) row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv_sqrt = deg.pow(-0.5) deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0 return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col] def cal_fast_appr(alpha, edge_index, num_nodes, dtype, edge_weight=None): if edge_weight == None: edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype, device=edge_index.device) fill_value = 1 # print(alpha) edge_index, edge_weight = add_self_loops( edge_index, edge_weight, fill_value, num_nodes) row, col = edge_index # from tensor to csr matrix sparse_adj = sp.csr_matrix( (edge_weight.cpu().numpy(), (row.cpu().numpy(), col.cpu().numpy())), shape=(num_nodes, num_nodes)) tol = 1e-6 L, _ = fast_appr_power( sparse_adj, alpha=alpha, tol=tol) L = L.tocoo() values = L.data indices = np.vstack((L.row, L.col)) L_indices = torch.LongTensor(indices).to(edge_index.device) L_values = torch.FloatTensor(values).to(edge_index.device) edge_index = L_indices edge_weight = L_values # sys normalization row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv_sqrt = deg.pow(-0.5) deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0 return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col] def get_pr_directed_adj(alpha, edge_index, num_nodes, dtype): edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype, device=edge_index.device) fill_value = 1 edge_index, edge_weight = add_self_loops( edge_index, edge_weight, fill_value, num_nodes) row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv = deg.pow(-1) deg_inv[deg_inv == float('inf')] = 0 p = deg_inv[row] * edge_weight p_dense = torch.sparse.FloatTensor( edge_index, p, torch.Size([num_nodes, num_nodes])).to_dense() # pagerank p p_pr = (1.0-alpha) * p_dense + alpha / num_nodes * \ torch.ones((num_nodes, num_nodes), dtype=dtype, device=p.device) eig_value, left_vector = scipy.linalg.eig( p_pr.numpy(), left=True, right=False) eig_value = torch.from_numpy(eig_value.real) left_vector = torch.from_numpy(left_vector.real) val, ind = eig_value.sort(descending=True) # assert val[0] == 1.0 pi = left_vector[:, ind[0]] # choose the largest eig vector pi = pi/pi.sum() # norm pi # Note that by scaling the vectors, even the sign can change. That's why positive and negative elements might get flipped. assert len(pi[pi < 0]) == 0 pi_inv_sqrt = pi.pow(-0.5) pi_inv_sqrt[pi_inv_sqrt == float('inf')] = 0 pi_inv_sqrt = pi_inv_sqrt.diag() pi_sqrt = pi.pow(0.5) pi_sqrt[pi_sqrt == float('inf')] = 0 pi_sqrt = pi_sqrt.diag() # L_pr L = (torch.mm(torch.mm(pi_sqrt, p_pr), pi_inv_sqrt) + torch.mm(torch.mm(pi_inv_sqrt, p_pr.t()), pi_sqrt)) / 2.0 # make nan to 0 L[torch.isnan(L)] = 0 # # let little possbility connection to 0, make L sparse # L[ L < (1/num_nodes)] = 0 # L[ L < 5e-4] = 0 # transfer dense L to sparse L_indices = torch.nonzero(L, as_tuple=False).t() L_values = L[L_indices[0], L_indices[1]] edge_index = L_indices edge_weight = L_values # row normalization row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv_sqrt = deg.pow(-0.5) deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0 return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col] def get_appr_directed_adj(alpha, edge_index, num_nodes, dtype, edge_weight=None): if edge_weight == None: edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype, device=edge_index.device) fill_value = 1 # print(alpha) edge_index, edge_weight = add_self_loops( edge_index, edge_weight, fill_value, num_nodes) row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv = deg.pow(-1) deg_inv[deg_inv == float('inf')] = 0 p = deg_inv[row] * edge_weight # personalized pagerank p p_dense = torch.sparse.FloatTensor( edge_index, p, torch.Size([num_nodes, num_nodes])).to_dense() p_v = torch.zeros(torch.Size([num_nodes+1, num_nodes+1])) p_v[0:num_nodes, 0:num_nodes] = (1-alpha) * p_dense p_v[num_nodes, 0:num_nodes] = 1.0 / num_nodes p_v[0:num_nodes, num_nodes] = alpha p_v[num_nodes, num_nodes] = 0.0 p_ppr = p_v eig_value, left_vector = scipy.linalg.eig( p_ppr.numpy(), left=True, right=False) eig_value = torch.from_numpy(eig_value.real) left_vector = torch.from_numpy(left_vector.real) val, ind = eig_value.sort(descending=True) pi = left_vector[:, ind[0]] # choose the largest eig vector pi = pi[0:num_nodes] p_ppr = p_dense pi = pi/pi.sum() # norm pi # print(pi) # Note that by scaling the vectors, even the sign can change. That's why positive and negative elements might get flipped. assert len(pi[pi < 0]) == 0 pi_inv_sqrt = pi.pow(-0.5) pi_inv_sqrt[pi_inv_sqrt == float('inf')] = 0 pi_inv_sqrt = pi_inv_sqrt.diag() pi_sqrt = pi.pow(0.5) pi_sqrt[pi_sqrt == float('inf')] = 0 pi_sqrt = pi_sqrt.diag() # L_appr # print(pi_sqrt.device) # print(p_ppr.device) # print(pi_inv_sqrt.device) # exit() # print(p_ppr.numpy()) pi_sqrt = pi_sqrt.to(p_ppr.device) pi_inv_sqrt = pi_inv_sqrt.to(p_ppr.device) L = (torch.mm(torch.mm(pi_sqrt, p_ppr), pi_inv_sqrt) + torch.mm(torch.mm(pi_inv_sqrt, p_ppr.t()), pi_sqrt)) / 2.0 # print(L[7, 1198].numpy()) # make nan to 0 L[torch.isnan(L)] = 0 # transfer dense L to sparse L_indices = torch.nonzero(L, as_tuple=False).t() # L_indices = torch.nonzero(L, as_tuple=False) L_values = L[L_indices[0], L_indices[1]] edge_index = L_indices edge_weight = L_values # print(L_indices[:, 0:20]) # print(L_indices.shape) # print(L_values[0:20]) # row normalization row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv_sqrt = deg.pow(-0.5) deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0 return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]
[ "torch.ones", "torch.LongTensor", "torch.FloatTensor", "torch.nonzero", "torch.mm", "torch_geometric.utils.add_self_loops", "torch.Size", "torch_scatter.scatter_add", "torch.isnan", "numpy.vstack", "torch.from_numpy" ]
[((855, 917), 'torch_geometric.utils.add_self_loops', 'add_self_loops', (['edge_index', 'edge_weight', 'fill_value', 'num_nodes'], {}), '(edge_index, edge_weight, fill_value, num_nodes)\n', (869, 917), False, 'from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops, to_dense_adj\n'), ((964, 1020), 'torch_scatter.scatter_add', 'scatter_add', (['edge_weight', 'row'], {'dim': '(0)', 'dim_size': 'num_nodes'}), '(edge_weight, row, dim=0, dim_size=num_nodes)\n', (975, 1020), False, 'from torch_scatter import scatter_add\n'), ((1482, 1544), 'torch_geometric.utils.add_self_loops', 'add_self_loops', (['edge_index', 'edge_weight', 'fill_value', 'num_nodes'], {}), '(edge_index, edge_weight, fill_value, num_nodes)\n', (1496, 1544), False, 'from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops, to_dense_adj\n'), ((1891, 1916), 'numpy.vstack', 'np.vstack', (['(L.row, L.col)'], {}), '((L.row, L.col))\n', (1900, 1916), True, 'import numpy as np\n'), ((2161, 2217), 'torch_scatter.scatter_add', 'scatter_add', (['edge_weight', 'row'], {'dim': '(0)', 'dim_size': 'num_nodes'}), '(edge_weight, row, dim=0, dim_size=num_nodes)\n', (2172, 2217), False, 'from torch_scatter import scatter_add\n'), ((2612, 2674), 'torch_geometric.utils.add_self_loops', 'add_self_loops', (['edge_index', 'edge_weight', 'fill_value', 'num_nodes'], {}), '(edge_index, edge_weight, fill_value, num_nodes)\n', (2626, 2674), False, 'from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops, to_dense_adj\n'), ((2720, 2776), 'torch_scatter.scatter_add', 'scatter_add', (['edge_weight', 'row'], {'dim': '(0)', 'dim_size': 'num_nodes'}), '(edge_weight, row, dim=0, dim_size=num_nodes)\n', (2731, 2776), False, 'from torch_scatter import scatter_add\n'), ((3247, 3279), 'torch.from_numpy', 'torch.from_numpy', (['eig_value.real'], {}), '(eig_value.real)\n', (3263, 3279), False, 'import torch\n'), ((3298, 3332), 'torch.from_numpy', 'torch.from_numpy', (['left_vector.real'], {}), '(left_vector.real)\n', (3314, 3332), False, 'import torch\n'), ((4428, 4484), 'torch_scatter.scatter_add', 'scatter_add', (['edge_weight', 'row'], {'dim': '(0)', 'dim_size': 'num_nodes'}), '(edge_weight, row, dim=0, dim_size=num_nodes)\n', (4439, 4484), False, 'from torch_scatter import scatter_add\n'), ((4954, 5016), 'torch_geometric.utils.add_self_loops', 'add_self_loops', (['edge_index', 'edge_weight', 'fill_value', 'num_nodes'], {}), '(edge_index, edge_weight, fill_value, num_nodes)\n', (4968, 5016), False, 'from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops, to_dense_adj\n'), ((5062, 5118), 'torch_scatter.scatter_add', 'scatter_add', (['edge_weight', 'row'], {'dim': '(0)', 'dim_size': 'num_nodes'}), '(edge_weight, row, dim=0, dim_size=num_nodes)\n', (5073, 5118), False, 'from torch_scatter import scatter_add\n'), ((5733, 5765), 'torch.from_numpy', 'torch.from_numpy', (['eig_value.real'], {}), '(eig_value.real)\n', (5749, 5765), False, 'import torch\n'), ((5784, 5818), 'torch.from_numpy', 'torch.from_numpy', (['left_vector.real'], {}), '(left_vector.real)\n', (5800, 5818), False, 'import torch\n'), ((7217, 7273), 'torch_scatter.scatter_add', 'scatter_add', (['edge_weight', 'row'], {'dim': '(0)', 'dim_size': 'num_nodes'}), '(edge_weight, row, dim=0, dim_size=num_nodes)\n', (7228, 7273), False, 'from torch_scatter import scatter_add\n'), ((4044, 4058), 'torch.isnan', 'torch.isnan', (['L'], {}), '(L)\n', (4055, 4058), False, 'import torch\n'), ((5384, 5426), 'torch.Size', 'torch.Size', (['[num_nodes + 1, num_nodes + 1]'], {}), '([num_nodes + 1, num_nodes + 1])\n', (5394, 5426), False, 'import torch\n'), ((6809, 6823), 'torch.isnan', 'torch.isnan', (['L'], {}), '(L)\n', (6820, 6823), False, 'import torch\n'), ((1934, 1959), 'torch.LongTensor', 'torch.LongTensor', (['indices'], {}), '(indices)\n', (1950, 1959), False, 'import torch\n'), ((1997, 2022), 'torch.FloatTensor', 'torch.FloatTensor', (['values'], {}), '(values)\n', (2014, 2022), False, 'import torch\n'), ((3072, 3136), 'torch.ones', 'torch.ones', (['(num_nodes, num_nodes)'], {'dtype': 'dtype', 'device': 'p.device'}), '((num_nodes, num_nodes), dtype=dtype, device=p.device)\n', (3082, 3136), False, 'import torch\n'), ((4231, 4263), 'torch.nonzero', 'torch.nonzero', (['L'], {'as_tuple': '(False)'}), '(L, as_tuple=False)\n', (4244, 4263), False, 'import torch\n'), ((6879, 6911), 'torch.nonzero', 'torch.nonzero', (['L'], {'as_tuple': '(False)'}), '(L, as_tuple=False)\n', (6892, 6911), False, 'import torch\n'), ((2942, 2976), 'torch.Size', 'torch.Size', (['[num_nodes, num_nodes]'], {}), '([num_nodes, num_nodes])\n', (2952, 2976), False, 'import torch\n'), ((3910, 3933), 'torch.mm', 'torch.mm', (['pi_sqrt', 'p_pr'], {}), '(pi_sqrt, p_pr)\n', (3918, 3933), False, 'import torch\n'), ((5315, 5349), 'torch.Size', 'torch.Size', (['[num_nodes, num_nodes]'], {}), '([num_nodes, num_nodes])\n', (5325, 5349), False, 'import torch\n'), ((6642, 6666), 'torch.mm', 'torch.mm', (['pi_sqrt', 'p_ppr'], {}), '(pi_sqrt, p_ppr)\n', (6650, 6666), False, 'import torch\n')]
import numpy as np import pandas as pd from tqdm import tqdm import datetime pd.plotting.register_matplotlib_converters() # addresses complaints about Timestamp instead of float for plotting x-values import matplotlib import matplotlib.pyplot as plt from matplotlib.lines import Line2D import joblib from scipy.stats import norm as sp_norm plt.style.use('seaborn-darkgrid') matplotlib.use('Agg') from time import time as get_time from os import path import os from enum import Enum from yattag import Doc class Region(Enum): US_states = 'US_states' countries = 'countries' US_counties = 'US_counties' provinces = 'provinces' def __str__(self): return str(self.value) class ApproxType(Enum): __order__ = 'BS LS MCMC SM PyMC3 Hess SM_acc SM_TS CF NDT_Hess NDT_Jac SP_min' BS = ('BS', 'bootstrap') LS = ('LS', 'likelihood_samples') MCMC = ('MCMC', 'random_walk') SM = ('SM', 'statsmodels') PyMC3 = ('PyMC3', 'PyMC3') Hess = ('Hess', 'hessian') SM_acc = ('SM_acc', 'statsmodels_acc') SM_TS = ('SM_TS', 'statsmodels_time_series') CF = ('CF', 'curve_fit_covariance') NDT_Hess = ('NDT_Hess', 'numdifftools_hessian') NDT_Jac = ('NDT_Jac', 'numdifftools_jacobian') SP_min = ('SP_min', 'scipy_minimize') def __str__(self): return str(self.value) class Stopwatch: def __init__(self): self.time0 = get_time() def elapsed_time(self): return get_time() - self.time0 def reset(self): self.time0 = get_time() def render_whisker_plot_simplified(state_report, plot_param_name='alpha_2', output_filename_format_str='test_boxplot_for_{}_{}.png', opt_log=False, boxwidth=0.7, approx_types=[('SM', 'statsmodels')]): ''' Plot all-state box/whiskers for given apram_name :param state_report: full state report as pandas dataframe :param param_name: param name as string :param output_filename_format_str: format string for the output filename, with two open slots :param opt_log: boolean for log-transform x-axis :return: None, it saves plots to files ''' tmp_ind = [i for i, x in state_report.iterrows() if x['param'] == plot_param_name] print('columns:') print(state_report.columns) tmp_ind = sorted(tmp_ind, key=lambda x: state_report.iloc[x][f'{approx_types[0].value[0]}_p50']) small_state_report = state_report.iloc[tmp_ind] small_state_report.to_csv('simplified_state_report_{}.csv'.format(plot_param_name)) for approx_type in approx_types: try: param_name_abbr, param_name = approx_type.value latex_str = small_state_report[ [f'{param_name_abbr}_p5', f'{param_name_abbr}_p50', f'{param_name_abbr}_p95']].to_latex(index=False, float_format="{:0.4f}".format) print(param_name) print(latex_str) except: pass map_approx_type_to_boxes = dict() for approx_type in approx_types: try: param_name_abbr, param_name = approx_type.value tmp_list = list() for i in range(len(small_state_report)): row = pd.DataFrame([small_state_report.iloc[i]]) new_box = \ { 'label': approx_type.value[1], 'whislo': row[f'{param_name_abbr}_p5'].values[0], # Bottom whisker position 'q1': row[f'{param_name_abbr}_p25'].values[0], # First quartile (25th percentile) 'med': row[f'{param_name_abbr}_p50'].values[0], # Median (50th percentile) 'q3': row[f'{param_name_abbr}_p75'].values[0], # Third quartile (75th percentile) 'whishi': row[f'{param_name_abbr}_p95'].values[0], # Top whisker position 'fliers': [] # Outliers } tmp_list.append(new_box) map_approx_type_to_boxes[param_name_abbr] = tmp_list except: pass plt.close() plt.clf() fig, ax = plt.subplots() fig.set_size_inches(8, 10.5) # add vertical line at zero plt.axvline(linestyle='--', x=0, color='black') n_groups = len(map_approx_type_to_boxes) # when just one group, there's extra space between each state we need to account for if n_groups == 1: boxwidth = 1.2 map_approx_type_to_ax = dict() for ind, approx_type in enumerate(sorted(map_approx_type_to_boxes)): try: map_approx_type_to_ax[approx_type] = ax.bxp(map_approx_type_to_boxes[approx_type], showfliers=False, positions=range(1 + ind, len(map_approx_type_to_boxes[approx_type]) * ( n_groups + 1), (n_groups + 1)), widths=boxwidth, patch_artist=True, vert=False) except: pass setup_boxes = map_approx_type_to_boxes[list(map_approx_type_to_boxes.keys())[0]] # plt.yticks([x + 0.5 for x in range(1, len(BS_boxes) * (n_groups + 1), (n_groups + 1))], small_state_report['state']) plt.yticks(range(1, len(setup_boxes) * (n_groups + 1), (n_groups + 1)), small_state_report['state']) # fill with colors colors = ['blue', 'red', 'green', 'purple', 'orange', 'brown', 'navy', 'teal', 'orchid', 'tan'] for approx_type, color in zip(sorted(map_approx_type_to_ax), colors): try: ax = map_approx_type_to_ax[approx_type] for item in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']: for patch in ax[item]: try: patch.set_facecolor(color) except: pass patch.set_color(color) except: pass # add legend if n_groups > 1: custom_lines = [ Line2D([0], [0], color=color, lw=4) for approx_type, color in zip(sorted(map_approx_type_to_ax), colors) ] plt.legend(custom_lines, sorted(map_approx_type_to_ax)) # increase left margin output_filename = output_filename_format_str.format(plot_param_name, '_'.join(approx_type.value[1] for approx_type in approx_types)) plt.subplots_adjust(left=0.2) if opt_log: plt.xscale('log') plt.savefig(output_filename, dpi=300) # plt.boxplot(small_state_report['state'], small_state_report[['BS_p5', 'BS_p95']]) def generate_state_prediction(map_state_name_to_model, override_max_date_str, prediction_filename=None, n_samples=1000): max_date = datetime.datetime.strptime(override_max_date_str, '%Y-%m-%d') all_predictions = list() for state_ind, state in enumerate(map_state_name_to_model): if state in map_state_name_to_model: state_model = map_state_name_to_model[state] else: print(f'Skipping {state}!') continue if state_model is not None: for approx_type in state_model.model_approx_types: if approx_type == ApproxType.SM or approx_type == ApproxType.SM_acc or approx_type == ApproxType.SM_TS: params, _, _, log_probs = state_model.get_weighted_samples_via_statsmodels() elif approx_type == ApproxType.PyMC3: params, _, _, log_probs = state_model.get_weighted_samples_via_PyMC3() print(approx_type) param_inds_to_plot = list(range(len(params))) param_inds_to_plot = np.random.choice(param_inds_to_plot, min(n_samples, len(param_inds_to_plot)), replace=False) sols_to_plot = [state_model.run_simulation(in_params=params[param_ind]) for param_ind in tqdm(param_inds_to_plot)] start_ind_sol = len(state_model.data_new_tested) + state_model.burn_in start_ind_data = start_ind_sol - 1 - state_model.burn_in sol_date_range = [ state_model.min_date - datetime.timedelta(days=state_model.burn_in) + datetime.timedelta( days=1) * i for i in range(len(sols_to_plot[0][0]))] sols_to_plot_new_tested = list() sols_to_plot_new_dead = list() sols_to_plot_tested = list() sols_to_plot_dead = list() for sol in sols_to_plot: tested = [max(sol[1][i] - state_model.log_offset, 0) for i in range(len(sol[1]))] tested_range = np.cumsum(tested[start_ind_sol:]) dead = [max(sol[1][i] - state_model.log_offset, 0) for i in range(len(sol[1]))] dead_range = np.cumsum(dead[start_ind_sol:]) sols_to_plot_new_tested.append(tested) sols_to_plot_new_dead.append(dead) data_tested_at_start = np.cumsum(state_model.data_new_tested)[start_ind_data] data_dead_at_start = np.cumsum(state_model.data_new_dead)[start_ind_data] tested = [0] * start_ind_sol + [data_tested_at_start + tested_val for tested_val in tested_range] dead = [0] * start_ind_sol + [data_dead_at_start + dead_val for dead_val in dead_range] sols_to_plot_tested.append(tested) sols_to_plot_dead.append(dead) output_list_of_dicts = list() for date_ind in range(start_ind_sol, len(sols_to_plot_tested[0])): distro_new_tested = [tested[date_ind] for tested in sols_to_plot_new_tested] distro_new_dead = [dead[date_ind] for dead in sols_to_plot_new_dead] distro_tested = [tested[date_ind] for tested in sols_to_plot_tested] distro_dead = [dead[date_ind] for dead in sols_to_plot_dead] tmp_dict = {'model_type': approx_type.value[1], 'date': sol_date_range[date_ind], 'total_positive_mean': np.average(distro_tested), 'total_positive_std': np.std(distro_tested), 'total_positive_p5': np.percentile(distro_tested, 5), 'total_positive_p25': np.percentile(distro_tested, 25), 'total_positive_p50': np.percentile(distro_tested, 50), 'total_positive_p75': np.percentile(distro_tested, 75), 'total_positive_p95': np.percentile(distro_tested, 95), 'total_deceased_mean': np.average(distro_dead), 'total_deceased_std': np.std(distro_dead), 'total_deceased_p5': np.percentile(distro_dead, 5), 'total_deceased_p25': np.percentile(distro_dead, 25), 'total_deceased_p50': np.percentile(distro_dead, 50), 'total_deceased_p75': np.percentile(distro_dead, 75), 'total_deceased_p95': np.percentile(distro_dead, 95), 'new_positive_mean': np.average(distro_new_tested), 'new_positive_std': np.std(distro_new_tested), 'new_positive_p5': np.percentile(distro_new_tested, 5), 'new_positive_p25': np.percentile(distro_new_tested, 25), 'new_positive_p50': np.percentile(distro_new_tested, 50), 'new_positive_p75': np.percentile(distro_new_tested, 75), 'new_positive_p95': np.percentile(distro_new_tested, 95), 'new_deceased_mean': np.average(distro_new_dead), 'new_deceased_std': np.std(distro_new_dead), 'new_deceased_p5': np.percentile(distro_new_dead, 5), 'new_deceased_p25': np.percentile(distro_new_dead, 25), 'new_deceased_p50': np.percentile(distro_new_dead, 50), 'new_deceased_p75': np.percentile(distro_new_dead, 75), 'new_deceased_p95': np.percentile(distro_new_dead, 95), } output_list_of_dicts.append(tmp_dict.copy()) tmp_dict.update({'state': state}) all_predictions.append(tmp_dict.copy()) all_predictions = pd.DataFrame(all_predictions) if all([x.startswith('US: ') for x in all_predictions['state']]): all_predictions['state'] = [x[3:] for x in all_predictions['state']] # filter to just the first two weeks and every 1st of the month projection_dates = [max_date + datetime.timedelta(days=x) for x in range(1, 14)] for date in set(all_predictions['date']): if date.strftime('%Y-%m-%d').endswith('-01'): projection_dates.append(date) use_date_iloc = [i for i, x in enumerate(all_predictions['date']) if x in projection_dates] print('Saving state prediction to {}...'.format(prediction_filename)) joblib.dump(all_predictions, prediction_filename) print('...done!') print('Saving state report to {}...'.format(prediction_filename.replace('joblib', 'csv'))) joblib.dump(all_predictions.iloc[use_date_iloc].to_csv(), prediction_filename.replace('joblib', 'csv')) print('...done!') def generate_state_report(map_state_name_to_model, state_report_filename=None, report_names=None): state_report_as_list_of_dicts = list() for state_ind, state in enumerate(map_state_name_to_model): if state in map_state_name_to_model: state_model = map_state_name_to_model[state] else: print(f'Skipping {state}!') continue if state_model is not None: if report_names is None: report_names = state_model.sorted_names + list(state_model.extra_params.keys()) try: LS_params, _, _, _ = state_model.get_weighted_samples_via_MVN() except: LS_params = [0] try: SM_params, _, _, _ = state_model.get_weighted_samples_via_statsmodels() except: SM_params = [0] try: SM_acc_params = state_model.map_param_to_acc except: SM_acc_params = [0] approx_type_params = dict() for approx_type in state_model.map_approx_type_to_model: if True: approx_type_params[approx_type], _, _, _ = state_model.get_weighted_samples_via_model(approx_type=approx_type) else: approx_type_params[approx_type] = [0] try: PyMC3_params, _, _, _ = state_model.get_weighted_samples_via_PyMC3() except: PyMC3_params = [0] for param_name in report_names: if param_name in state_model.sorted_names: try: BS_vals = [state_model.bootstrap_params[i][param_name] for i in range(len(state_model.bootstrap_params))] except: pass try: LS_vals = [LS_params[i][state_model.map_name_to_sorted_ind[param_name]] for i in range(len(LS_params))] except: pass approx_type_vals = dict() for approx_type in state_model.map_approx_type_to_model: try: approx_type_vals[approx_type] = [approx_type_params[approx_type][i][state_model.map_name_to_sorted_ind[param_name]] for i in range(len(approx_type_params[approx_type]))] except: pass try: SM_vals = [SM_params[i][state_model.map_name_to_sorted_ind[param_name]] for i in range(len(SM_params))] except: pass try: PyMC3_vals = [PyMC3_params[i][state_model.map_name_to_sorted_ind[param_name]] for i in range(len(PyMC3_params))] except: pass try: MCMC_vals = [ state_model.all_random_walk_samples_as_list[i][ state_model.map_name_to_sorted_ind[param_name]] for i in range(len(state_model.all_random_walk_samples_as_list))] except: pass else: try: BS_vals = [state_model.extra_params[param_name]( [state_model.bootstrap_params[i][key] for key in state_model.sorted_names]) for i in range(len(state_model.bootstrap_params))] except: pass try: LS_vals = [state_model.extra_params[param_name](LS_params[i]) for i in range(len(LS_params))] except: pass try: SM_vals = [state_model.extra_params[param_name](SM_params[i]) for i in range(len(SM_params))] except: pass approx_type_vals = dict() for approx_type in state_model.map_approx_type_to_model: try: approx_type_vals[approx_type] = [state_model.extra_params[param_name](approx_type_params[approx_type][i]) for i in range(len(approx_type_params[approx_type]))] except: pass try: PyMC3_vals = [ state_model.extra_params[param_name](state_model.extra_params[param_name](PyMC3_params[i])) for i in range(len(PyMC3_params))] except: pass try: MCMC_vals = [ state_model.extra_params[param_name](state_model.all_random_walk_samples_as_list[i]) for i in range(len(state_model.all_random_walk_samples_as_list))] except: pass dict_to_add = {'state': state, 'param': param_name } try: offset = SM_acc_params[param_name]['offset'] SM_acc_mean = SM_acc_params[param_name]['slope2'] - SM_acc_params[param_name]['slope1'] SM_acc_std_err = np.sqrt( SM_acc_params[param_name]['bse1'] ** 2 + SM_acc_params[param_name]['bse2'] ** 2) SM_acc_vals = sp_norm(loc=SM_acc_mean, scale=SM_acc_std_err).rvs(1000) dict_to_add.update({ 'statsmodels_acc_mean': np.average(SM_acc_vals), 'statsmodels_acc_std_err': np.std(SM_acc_vals), 'statsmodels_acc_fwhm': np.std(SM_acc_vals) * 2.355, 'statsmodels_acc_p50': np.percentile(SM_acc_vals, 50), 'statsmodels_acc_p5': np.percentile(SM_acc_vals, 5), 'statsmodels_acc_p95': np.percentile(SM_acc_vals, 95), 'statsmodels_acc_p25': np.percentile(SM_acc_vals, 25), 'statsmodels_acc_p75': np.percentile(SM_acc_vals, 75) }) dict_to_add.update({ f'statsmodels_mean_offset_{offset}_days': SM_acc_params[param_name]['slope1'], f'statsmodels_mean_std_err_offset_{offset}_days': SM_acc_params[param_name]['bse1'], # 'statsmodels_mean': SM_acc_params[param_name]['slope2'], # 'statsmodels_mean_std_err': SM_acc_params[param_name]['bse2'], 'statsmodels_acc_z_score': SM_acc_params[param_name]['z_score'], 'statsmodels_acc_p_value': SM_acc_params[param_name]['p_value'] }) except: pass try: dict_to_add.update({ 'bootstrap_mean': np.average(BS_vals), 'bootstrap_p50': np.percentile(BS_vals, 50), 'bootstrap_p25': np.percentile(BS_vals, 25), 'bootstrap_p75': np.percentile(BS_vals, 75), 'bootstrap_p5': np.percentile(BS_vals, 5), 'bootstrap_p95': np.percentile(BS_vals, 95) }) except: pass try: dict_to_add.update({ 'random_walk_mean': np.average(MCMC_vals), 'random_walk_p50': np.percentile(MCMC_vals, 50), 'random_walk_p5': np.percentile(MCMC_vals, 5), 'random_walk_p95': np.percentile(MCMC_vals, 95), 'random_walk_p25': np.percentile(MCMC_vals, 25), 'random_walk_p75': np.percentile(MCMC_vals, 75) }) except: pass try: dict_to_add.update({ 'likelihood_samples_mean': np.average(LS_vals), 'likelihood_samples_p50': np.percentile(LS_vals, 50), 'likelihood_samples_p5': np.percentile(LS_vals, 5), 'likelihood_samples_p95': np.percentile(LS_vals, 95), 'likelihood_samples_p25': np.percentile(LS_vals, 25), 'likelihood_samples_p75': np.percentile(LS_vals, 75) }) except: pass try: dict_to_add.update({ 'statsmodels_mean': np.average(SM_vals), 'statsmodels_std_err': np.std(SM_vals), 'statsmodels_fwhm': np.std(SM_vals) * 2.355, 'statsmodels_p50': np.percentile(SM_vals, 50), 'statsmodels_p5': np.percentile(SM_vals, 5), 'statsmodels_p95': np.percentile(SM_vals, 95), 'statsmodels_p25': np.percentile(SM_vals, 25), 'statsmodels_p75': np.percentile(SM_vals, 75) }) except: pass for approx_type in approx_type_vals: try: dict_to_add.update({ f'{approx_type.value[0]}_mean': np.average(approx_type_vals[approx_type]), f'{approx_type.value[0]}_std_err': np.std(approx_type_vals[approx_type]), f'{approx_type.value[0]}_p50': np.percentile(approx_type_vals[approx_type], 50), f'{approx_type.value[0]}_p5': np.percentile(approx_type_vals[approx_type], 5), f'{approx_type.value[0]}_p95': np.percentile(approx_type_vals[approx_type], 95), f'{approx_type.value[0]}_p25': np.percentile(approx_type_vals[approx_type], 25), f'{approx_type.value[0]}_p75': np.percentile(approx_type_vals[approx_type], 75) }) except: pass try: dict_to_add.update({ 'PyMC3_mean': np.average(PyMC3_vals), 'PyMC3_std_err': np.std(PyMC3_vals), 'PyMC3_p50': np.percentile(PyMC3_vals, 50), 'PyMC3_p5': np.percentile(PyMC3_vals, 5), 'PyMC3_p95': np.percentile(PyMC3_vals, 95), 'PyMC3_p25': np.percentile(PyMC3_vals, 25), 'PyMC3_p75': np.percentile(PyMC3_vals, 75) }) except: pass state_report_as_list_of_dicts.append(dict_to_add) state_report = pd.DataFrame(state_report_as_list_of_dicts) print('Saving state report to {}...'.format(state_report_filename)) joblib.dump(state_report, state_report_filename) print('...done!') print('Saving state report to {}...'.format(state_report_filename.replace('joblib', 'csv'))) joblib.dump(state_report.to_csv(), state_report_filename.replace('joblib', 'csv')) print('...done!') n_states = len(set(state_report['state'])) print(n_states) new_cols = list() for col in state_report.columns: for approx_type in ApproxType: col = col.replace(approx_type.value[1], approx_type.value[0]) new_col = col.replace('__', '_') new_cols.append(new_col) state_report.columns = new_cols if all([x.startswith('US: ') for x in state_report['state']]): state_report['state'] = [x[3:] for x in state_report['state']] return state_report def run_everything(run_states, model_class, load_data, override_max_date_str=None, sorted_init_condit_names=None, sorted_param_names=None, extra_params=None, logarithmic_params=list(), plot_param_names=None, opt_simplified=False, **kwargs): # setting intermediate variables to global allows us to inspect these objects via monkey-patching global map_state_name_to_model, state_report map_state_name_to_model = dict() for state_ind, state in enumerate(run_states): if state not in load_data.map_state_to_current_case_cnt: continue print( f'\n----\n----\nProcessing {state} ({state_ind} of {len(run_states)}, current cases {load_data.map_state_to_current_case_cnt[state]:,})...\n----\n----\n') if True: print('Building model with the following args...') for key in sorted(kwargs.keys()): print(f'{key}: {kwargs[key]}') state_model = model_class(state, sorted_init_condit_names=sorted_init_condit_names, sorted_param_names=sorted_param_names, extra_params=extra_params, logarithmic_params=logarithmic_params, plot_param_names=plot_param_names, opt_simplified=opt_simplified, override_max_date_str=override_max_date_str, **kwargs ) if opt_simplified: state_model.run_fits_simplified() else: state_model.run_fits() map_state_name_to_model[state] = state_model else: print("Error with state", state) continue plot_subfolder = state_model.plot_subfolder if opt_simplified: state_report_filename = path.join(plot_subfolder, f'simplified_state_report.joblib') state_prediction_filename = path.join(plot_subfolder, f'simplified_state_prediction.joblib') filename_format_str = path.join(plot_subfolder, f'simplified_boxplot_for_{{}}_{{}}.png') if state_ind in [0, 1, 4, 9, 100] or state_ind == len(run_states) - 1: print('Reporting now and at the end') state_report = generate_state_report(map_state_name_to_model, state_report_filename=state_report_filename, report_names=plot_param_names) _ = generate_state_prediction(map_state_name_to_model, override_max_date_str, prediction_filename=state_prediction_filename) for param_name in state_model.plot_param_names: render_whisker_plot_simplified(state_report, plot_param_name=param_name, output_filename_format_str=filename_format_str, opt_log=param_name in logarithmic_params, approx_types=state_model.model_approx_types) if ApproxType.SM in state_model.model_approx_types: render_whisker_plot_simplified(state_report, plot_param_name=param_name, output_filename_format_str=filename_format_str, opt_log=param_name in logarithmic_params, approx_types=[ApproxType.SM_acc]) else: pass else: state_report_filename = path.join(plot_subfolder, 'state_report.csv') filename_format_str = path.join(plot_subfolder, 'boxplot_for_{}_{}.png') if state_ind in [0, 1, 4, 9, 100] or state_ind == len(run_states) - 1: print('Reporting now and at the end') state_report = generate_state_report(map_state_name_to_model, state_report_filename=state_report_filename) for param_name in state_model.plot_param_names: render_whisker_plot_simplified(state_report, plot_param_name=param_name, output_filename_format_str=filename_format_str, opt_log=param_name in logarithmic_params, approx_types=state_model.model_approx_types) return plot_subfolder def generate_plot_browser(plot_browser_dir, base_url_dir, github_url, full_report_filename, list_of_figures, list_of_figures_full_report, regions_to_present): if not path.exists(plot_browser_dir): os.mkdir(plot_browser_dir) alphabetical_states = sorted(regions_to_present) # load_data.map_state_to_current_case_cnt.keys()) # alphabetical_states.remove('total') # alphabetical_states = ['total'] + alphabetical_states map_state_to_html = dict() for state in alphabetical_states: state_lc = state.lower().replace(' ', '_') doc, tag, text = Doc(defaults={'title': f'Plots for {state}'}).tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('head'): pass with tag('body'): with tag('div', id='photo-container'): with tag('ul'): with tag('li'): with tag('a', href='../index.html'): text('<-- Back') for figure_name in list_of_figures: tmp_url = base_url_dir + state_lc + '/' + figure_name with tag("a", href=tmp_url): doc.stag('img', src=tmp_url, klass="photo", height="300", width="400") with tag('li'): with doc.tag("a", href=tmp_url): doc.text(figure_name) with tag('hr'): pass result = doc.getvalue() map_state_to_html[state] = result for state in map_state_to_html: state_lc = state.lower().replace(' ', '_').replace(':','') if not path.exists(path.join(plot_browser_dir, state_lc)): os.mkdir(path.join(plot_browser_dir, state_lc)) with open(path.join(plot_browser_dir, path.join(state_lc, 'index.html')), 'w') as f: f.write(map_state_to_html[state]) ##### # Generate state-report page ##### with open(path.join(plot_browser_dir, full_report_filename), 'w') as f: doc, tag, text = Doc(defaults={'title': f'Plots for Full Report'}).tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('head'): pass with tag('body'): with tag('div', id='photo-container'): with tag('ul'): with tag('li'): with tag('a', href='index.html'): text('<-- Back') for figure_name in list_of_figures_full_report: tmp_url = base_url_dir + figure_name with tag("a", href=tmp_url): doc.stag('img', src=tmp_url, klass="photo", height="400", width="300") with tag('li'): with doc.tag("a", href=tmp_url): doc.text(figure_name) with tag('hr'): pass f.write(doc.getvalue()) ##### # Generate landing page ##### with open(path.join(plot_browser_dir, 'index.html'), 'w') as f: doc, tag, text = Doc(defaults={'title': f'Plots for {state}'}).tagtext() doc.asis('<!DOCTYPE html>') with tag('html'): with tag('head'): pass with tag('body'): with tag('ul'): with tag('li'): with tag("a", href=github_url): text('<-- Back to Repository') with tag('li'): with tag("a", href=full_report_filename): text(f'Full Report') for state in alphabetical_states: state_lc = state.lower().replace(' ', '_').replace(':', '') tmp_url = state_lc + '/index.html' if state.lower().startswith('us:_'): print_state = state[4:] else: print_state = state print_state = print_state.title().replace('_', ' ').replace(' Of', ' of') with tag('li'): with tag("a", href=tmp_url): text(print_state) f.write(doc.getvalue())
[ "os.mkdir", "matplotlib.pyplot.clf", "joblib.dump", "matplotlib.pyplot.style.use", "os.path.join", "pandas.DataFrame", "matplotlib.pyplot.axvline", "scipy.stats.norm", "matplotlib.lines.Line2D", "numpy.std", "matplotlib.pyplot.close", "os.path.exists", "numpy.cumsum", "datetime.timedelta", "matplotlib.pyplot.subplots", "tqdm.tqdm", "numpy.average", "yattag.Doc", "numpy.percentile", "datetime.datetime.strptime", "matplotlib.use", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.xscale", "pandas.plotting.register_matplotlib_converters", "time.time", "matplotlib.pyplot.savefig", "numpy.sqrt" ]
[((78, 122), 'pandas.plotting.register_matplotlib_converters', 'pd.plotting.register_matplotlib_converters', ([], {}), '()\n', (120, 122), True, 'import pandas as pd\n'), ((343, 376), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-darkgrid"""'], {}), "('seaborn-darkgrid')\n", (356, 376), True, 'import matplotlib.pyplot as plt\n'), ((377, 398), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (391, 398), False, 'import matplotlib\n'), ((4305, 4316), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4314, 4316), True, 'import matplotlib.pyplot as plt\n'), ((4321, 4330), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4328, 4330), True, 'import matplotlib.pyplot as plt\n'), ((4345, 4359), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (4357, 4359), True, 'import matplotlib.pyplot as plt\n'), ((4430, 4477), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'linestyle': '"""--"""', 'x': '(0)', 'color': '"""black"""'}), "(linestyle='--', x=0, color='black')\n", (4441, 4477), True, 'import matplotlib.pyplot as plt\n'), ((6726, 6755), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.2)'}), '(left=0.2)\n', (6745, 6755), True, 'import matplotlib.pyplot as plt\n'), ((6802, 6839), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_filename'], {'dpi': '(300)'}), '(output_filename, dpi=300)\n', (6813, 6839), True, 'import matplotlib.pyplot as plt\n'), ((7156, 7217), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['override_max_date_str', '"""%Y-%m-%d"""'], {}), "(override_max_date_str, '%Y-%m-%d')\n", (7182, 7217), False, 'import datetime\n'), ((13232, 13261), 'pandas.DataFrame', 'pd.DataFrame', (['all_predictions'], {}), '(all_predictions)\n', (13244, 13261), True, 'import pandas as pd\n'), ((13881, 13930), 'joblib.dump', 'joblib.dump', (['all_predictions', 'prediction_filename'], {}), '(all_predictions, prediction_filename)\n', (13892, 13930), False, 'import joblib\n'), ((26335, 26378), 'pandas.DataFrame', 'pd.DataFrame', (['state_report_as_list_of_dicts'], {}), '(state_report_as_list_of_dicts)\n', (26347, 26378), True, 'import pandas as pd\n'), ((26455, 26503), 'joblib.dump', 'joblib.dump', (['state_report', 'state_report_filename'], {}), '(state_report, state_report_filename)\n', (26466, 26503), False, 'import joblib\n'), ((1402, 1412), 'time.time', 'get_time', ([], {}), '()\n', (1410, 1412), True, 'from time import time as get_time\n'), ((1524, 1534), 'time.time', 'get_time', ([], {}), '()\n', (1532, 1534), True, 'from time import time as get_time\n'), ((6780, 6797), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (6790, 6797), True, 'import matplotlib.pyplot as plt\n'), ((32596, 32625), 'os.path.exists', 'path.exists', (['plot_browser_dir'], {}), '(plot_browser_dir)\n', (32607, 32625), False, 'from os import path\n'), ((32635, 32661), 'os.mkdir', 'os.mkdir', (['plot_browser_dir'], {}), '(plot_browser_dir)\n', (32643, 32661), False, 'import os\n'), ((1457, 1467), 'time.time', 'get_time', ([], {}), '()\n', (1465, 1467), True, 'from time import time as get_time\n'), ((6322, 6357), 'matplotlib.lines.Line2D', 'Line2D', (['[0]', '[0]'], {'color': 'color', 'lw': '(4)'}), '([0], [0], color=color, lw=4)\n', (6328, 6357), False, 'from matplotlib.lines import Line2D\n'), ((13514, 13540), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'x'}), '(days=x)\n', (13532, 13540), False, 'import datetime\n'), ((29420, 29480), 'os.path.join', 'path.join', (['plot_subfolder', 'f"""simplified_state_report.joblib"""'], {}), "(plot_subfolder, f'simplified_state_report.joblib')\n", (29429, 29480), False, 'from os import path\n'), ((29521, 29585), 'os.path.join', 'path.join', (['plot_subfolder', 'f"""simplified_state_prediction.joblib"""'], {}), "(plot_subfolder, f'simplified_state_prediction.joblib')\n", (29530, 29585), False, 'from os import path\n'), ((29620, 29686), 'os.path.join', 'path.join', (['plot_subfolder', 'f"""simplified_boxplot_for_{{}}_{{}}.png"""'], {}), "(plot_subfolder, f'simplified_boxplot_for_{{}}_{{}}.png')\n", (29629, 29686), False, 'from os import path\n'), ((31431, 31476), 'os.path.join', 'path.join', (['plot_subfolder', '"""state_report.csv"""'], {}), "(plot_subfolder, 'state_report.csv')\n", (31440, 31476), False, 'from os import path\n'), ((31511, 31561), 'os.path.join', 'path.join', (['plot_subfolder', '"""boxplot_for_{}_{}.png"""'], {}), "(plot_subfolder, 'boxplot_for_{}_{}.png')\n", (31520, 31561), False, 'from os import path\n'), ((34525, 34574), 'os.path.join', 'path.join', (['plot_browser_dir', 'full_report_filename'], {}), '(plot_browser_dir, full_report_filename)\n', (34534, 34574), False, 'from os import path\n'), ((35698, 35739), 'os.path.join', 'path.join', (['plot_browser_dir', '"""index.html"""'], {}), "(plot_browser_dir, 'index.html')\n", (35707, 35739), False, 'from os import path\n'), ((3420, 3462), 'pandas.DataFrame', 'pd.DataFrame', (['[small_state_report.iloc[i]]'], {}), '([small_state_report.iloc[i]])\n', (3432, 3462), True, 'import pandas as pd\n'), ((33016, 33061), 'yattag.Doc', 'Doc', ([], {'defaults': "{'title': f'Plots for {state}'}"}), "(defaults={'title': f'Plots for {state}'})\n", (33019, 33061), False, 'from yattag import Doc\n'), ((34217, 34254), 'os.path.join', 'path.join', (['plot_browser_dir', 'state_lc'], {}), '(plot_browser_dir, state_lc)\n', (34226, 34254), False, 'from os import path\n'), ((34278, 34315), 'os.path.join', 'path.join', (['plot_browser_dir', 'state_lc'], {}), '(plot_browser_dir, state_lc)\n', (34287, 34315), False, 'from os import path\n'), ((34612, 34661), 'yattag.Doc', 'Doc', ([], {'defaults': "{'title': f'Plots for Full Report'}"}), "(defaults={'title': f'Plots for Full Report'})\n", (34615, 34661), False, 'from yattag import Doc\n'), ((35777, 35822), 'yattag.Doc', 'Doc', ([], {'defaults': "{'title': f'Plots for {state}'}"}), "(defaults={'title': f'Plots for {state}'})\n", (35780, 35822), False, 'from yattag import Doc\n'), ((9144, 9177), 'numpy.cumsum', 'np.cumsum', (['tested[start_ind_sol:]'], {}), '(tested[start_ind_sol:])\n', (9153, 9177), True, 'import numpy as np\n'), ((9313, 9344), 'numpy.cumsum', 'np.cumsum', (['dead[start_ind_sol:]'], {}), '(dead[start_ind_sol:])\n', (9322, 9344), True, 'import numpy as np\n'), ((20067, 20160), 'numpy.sqrt', 'np.sqrt', (["(SM_acc_params[param_name]['bse1'] ** 2 + SM_acc_params[param_name]['bse2'] **\n 2)"], {}), "(SM_acc_params[param_name]['bse1'] ** 2 + SM_acc_params[param_name][\n 'bse2'] ** 2)\n", (20074, 20160), True, 'import numpy as np\n'), ((34363, 34396), 'os.path.join', 'path.join', (['state_lc', '"""index.html"""'], {}), "(state_lc, 'index.html')\n", (34372, 34396), False, 'from os import path\n'), ((8371, 8395), 'tqdm.tqdm', 'tqdm', (['param_inds_to_plot'], {}), '(param_inds_to_plot)\n', (8375, 8395), False, 'from tqdm import tqdm\n'), ((9504, 9542), 'numpy.cumsum', 'np.cumsum', (['state_model.data_new_tested'], {}), '(state_model.data_new_tested)\n', (9513, 9542), True, 'import numpy as np\n'), ((9600, 9636), 'numpy.cumsum', 'np.cumsum', (['state_model.data_new_dead'], {}), '(state_model.data_new_dead)\n', (9609, 9636), True, 'import numpy as np\n'), ((10662, 10687), 'numpy.average', 'np.average', (['distro_tested'], {}), '(distro_tested)\n', (10672, 10687), True, 'import numpy as np\n'), ((10743, 10764), 'numpy.std', 'np.std', (['distro_tested'], {}), '(distro_tested)\n', (10749, 10764), True, 'import numpy as np\n'), ((10819, 10850), 'numpy.percentile', 'np.percentile', (['distro_tested', '(5)'], {}), '(distro_tested, 5)\n', (10832, 10850), True, 'import numpy as np\n'), ((10906, 10938), 'numpy.percentile', 'np.percentile', (['distro_tested', '(25)'], {}), '(distro_tested, 25)\n', (10919, 10938), True, 'import numpy as np\n'), ((10994, 11026), 'numpy.percentile', 'np.percentile', (['distro_tested', '(50)'], {}), '(distro_tested, 50)\n', (11007, 11026), True, 'import numpy as np\n'), ((11082, 11114), 'numpy.percentile', 'np.percentile', (['distro_tested', '(75)'], {}), '(distro_tested, 75)\n', (11095, 11114), True, 'import numpy as np\n'), ((11170, 11202), 'numpy.percentile', 'np.percentile', (['distro_tested', '(95)'], {}), '(distro_tested, 95)\n', (11183, 11202), True, 'import numpy as np\n'), ((11259, 11282), 'numpy.average', 'np.average', (['distro_dead'], {}), '(distro_dead)\n', (11269, 11282), True, 'import numpy as np\n'), ((11338, 11357), 'numpy.std', 'np.std', (['distro_dead'], {}), '(distro_dead)\n', (11344, 11357), True, 'import numpy as np\n'), ((11412, 11441), 'numpy.percentile', 'np.percentile', (['distro_dead', '(5)'], {}), '(distro_dead, 5)\n', (11425, 11441), True, 'import numpy as np\n'), ((11497, 11527), 'numpy.percentile', 'np.percentile', (['distro_dead', '(25)'], {}), '(distro_dead, 25)\n', (11510, 11527), True, 'import numpy as np\n'), ((11583, 11613), 'numpy.percentile', 'np.percentile', (['distro_dead', '(50)'], {}), '(distro_dead, 50)\n', (11596, 11613), True, 'import numpy as np\n'), ((11669, 11699), 'numpy.percentile', 'np.percentile', (['distro_dead', '(75)'], {}), '(distro_dead, 75)\n', (11682, 11699), True, 'import numpy as np\n'), ((11755, 11785), 'numpy.percentile', 'np.percentile', (['distro_dead', '(95)'], {}), '(distro_dead, 95)\n', (11768, 11785), True, 'import numpy as np\n'), ((11840, 11869), 'numpy.average', 'np.average', (['distro_new_tested'], {}), '(distro_new_tested)\n', (11850, 11869), True, 'import numpy as np\n'), ((11923, 11948), 'numpy.std', 'np.std', (['distro_new_tested'], {}), '(distro_new_tested)\n', (11929, 11948), True, 'import numpy as np\n'), ((12001, 12036), 'numpy.percentile', 'np.percentile', (['distro_new_tested', '(5)'], {}), '(distro_new_tested, 5)\n', (12014, 12036), True, 'import numpy as np\n'), ((12090, 12126), 'numpy.percentile', 'np.percentile', (['distro_new_tested', '(25)'], {}), '(distro_new_tested, 25)\n', (12103, 12126), True, 'import numpy as np\n'), ((12180, 12216), 'numpy.percentile', 'np.percentile', (['distro_new_tested', '(50)'], {}), '(distro_new_tested, 50)\n', (12193, 12216), True, 'import numpy as np\n'), ((12270, 12306), 'numpy.percentile', 'np.percentile', (['distro_new_tested', '(75)'], {}), '(distro_new_tested, 75)\n', (12283, 12306), True, 'import numpy as np\n'), ((12360, 12396), 'numpy.percentile', 'np.percentile', (['distro_new_tested', '(95)'], {}), '(distro_new_tested, 95)\n', (12373, 12396), True, 'import numpy as np\n'), ((12451, 12478), 'numpy.average', 'np.average', (['distro_new_dead'], {}), '(distro_new_dead)\n', (12461, 12478), True, 'import numpy as np\n'), ((12532, 12555), 'numpy.std', 'np.std', (['distro_new_dead'], {}), '(distro_new_dead)\n', (12538, 12555), True, 'import numpy as np\n'), ((12608, 12641), 'numpy.percentile', 'np.percentile', (['distro_new_dead', '(5)'], {}), '(distro_new_dead, 5)\n', (12621, 12641), True, 'import numpy as np\n'), ((12695, 12729), 'numpy.percentile', 'np.percentile', (['distro_new_dead', '(25)'], {}), '(distro_new_dead, 25)\n', (12708, 12729), True, 'import numpy as np\n'), ((12783, 12817), 'numpy.percentile', 'np.percentile', (['distro_new_dead', '(50)'], {}), '(distro_new_dead, 50)\n', (12796, 12817), True, 'import numpy as np\n'), ((12871, 12905), 'numpy.percentile', 'np.percentile', (['distro_new_dead', '(75)'], {}), '(distro_new_dead, 75)\n', (12884, 12905), True, 'import numpy as np\n'), ((12959, 12993), 'numpy.percentile', 'np.percentile', (['distro_new_dead', '(95)'], {}), '(distro_new_dead, 95)\n', (12972, 12993), True, 'import numpy as np\n'), ((8636, 8680), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'state_model.burn_in'}), '(days=state_model.burn_in)\n', (8654, 8680), False, 'import datetime\n'), ((8683, 8709), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (8701, 8709), False, 'import datetime\n'), ((20219, 20265), 'scipy.stats.norm', 'sp_norm', ([], {'loc': 'SM_acc_mean', 'scale': 'SM_acc_std_err'}), '(loc=SM_acc_mean, scale=SM_acc_std_err)\n', (20226, 20265), True, 'from scipy.stats import norm as sp_norm\n'), ((20366, 20389), 'numpy.average', 'np.average', (['SM_acc_vals'], {}), '(SM_acc_vals)\n', (20376, 20389), True, 'import numpy as np\n'), ((20442, 20461), 'numpy.std', 'np.std', (['SM_acc_vals'], {}), '(SM_acc_vals)\n', (20448, 20461), True, 'import numpy as np\n'), ((20587, 20617), 'numpy.percentile', 'np.percentile', (['SM_acc_vals', '(50)'], {}), '(SM_acc_vals, 50)\n', (20600, 20617), True, 'import numpy as np\n'), ((20693, 20722), 'numpy.percentile', 'np.percentile', (['SM_acc_vals', '(5)'], {}), '(SM_acc_vals, 5)\n', (20706, 20722), True, 'import numpy as np\n'), ((20799, 20829), 'numpy.percentile', 'np.percentile', (['SM_acc_vals', '(95)'], {}), '(SM_acc_vals, 95)\n', (20812, 20829), True, 'import numpy as np\n'), ((20906, 20936), 'numpy.percentile', 'np.percentile', (['SM_acc_vals', '(25)'], {}), '(SM_acc_vals, 25)\n', (20919, 20936), True, 'import numpy as np\n'), ((21013, 21043), 'numpy.percentile', 'np.percentile', (['SM_acc_vals', '(75)'], {}), '(SM_acc_vals, 75)\n', (21026, 21043), True, 'import numpy as np\n'), ((21847, 21866), 'numpy.average', 'np.average', (['BS_vals'], {}), '(BS_vals)\n', (21857, 21866), True, 'import numpy as np\n'), ((21909, 21935), 'numpy.percentile', 'np.percentile', (['BS_vals', '(50)'], {}), '(BS_vals, 50)\n', (21922, 21935), True, 'import numpy as np\n'), ((22006, 22032), 'numpy.percentile', 'np.percentile', (['BS_vals', '(25)'], {}), '(BS_vals, 25)\n', (22019, 22032), True, 'import numpy as np\n'), ((22103, 22129), 'numpy.percentile', 'np.percentile', (['BS_vals', '(75)'], {}), '(BS_vals, 75)\n', (22116, 22129), True, 'import numpy as np\n'), ((22171, 22196), 'numpy.percentile', 'np.percentile', (['BS_vals', '(5)'], {}), '(BS_vals, 5)\n', (22184, 22196), True, 'import numpy as np\n'), ((22239, 22265), 'numpy.percentile', 'np.percentile', (['BS_vals', '(95)'], {}), '(BS_vals, 95)\n', (22252, 22265), True, 'import numpy as np\n'), ((22444, 22465), 'numpy.average', 'np.average', (['MCMC_vals'], {}), '(MCMC_vals)\n', (22454, 22465), True, 'import numpy as np\n'), ((22510, 22538), 'numpy.percentile', 'np.percentile', (['MCMC_vals', '(50)'], {}), '(MCMC_vals, 50)\n', (22523, 22538), True, 'import numpy as np\n'), ((22582, 22609), 'numpy.percentile', 'np.percentile', (['MCMC_vals', '(5)'], {}), '(MCMC_vals, 5)\n', (22595, 22609), True, 'import numpy as np\n'), ((22654, 22682), 'numpy.percentile', 'np.percentile', (['MCMC_vals', '(95)'], {}), '(MCMC_vals, 95)\n', (22667, 22682), True, 'import numpy as np\n'), ((22755, 22783), 'numpy.percentile', 'np.percentile', (['MCMC_vals', '(25)'], {}), '(MCMC_vals, 25)\n', (22768, 22783), True, 'import numpy as np\n'), ((22856, 22884), 'numpy.percentile', 'np.percentile', (['MCMC_vals', '(75)'], {}), '(MCMC_vals, 75)\n', (22869, 22884), True, 'import numpy as np\n'), ((23070, 23089), 'numpy.average', 'np.average', (['LS_vals'], {}), '(LS_vals)\n', (23080, 23089), True, 'import numpy as np\n'), ((23141, 23167), 'numpy.percentile', 'np.percentile', (['LS_vals', '(50)'], {}), '(LS_vals, 50)\n', (23154, 23167), True, 'import numpy as np\n'), ((23246, 23271), 'numpy.percentile', 'np.percentile', (['LS_vals', '(5)'], {}), '(LS_vals, 5)\n', (23259, 23271), True, 'import numpy as np\n'), ((23351, 23377), 'numpy.percentile', 'np.percentile', (['LS_vals', '(95)'], {}), '(LS_vals, 95)\n', (23364, 23377), True, 'import numpy as np\n'), ((23457, 23483), 'numpy.percentile', 'np.percentile', (['LS_vals', '(25)'], {}), '(LS_vals, 25)\n', (23470, 23483), True, 'import numpy as np\n'), ((23563, 23589), 'numpy.percentile', 'np.percentile', (['LS_vals', '(75)'], {}), '(LS_vals, 75)\n', (23576, 23589), True, 'import numpy as np\n'), ((23768, 23787), 'numpy.average', 'np.average', (['SM_vals'], {}), '(SM_vals)\n', (23778, 23787), True, 'import numpy as np\n'), ((23836, 23851), 'numpy.std', 'np.std', (['SM_vals'], {}), '(SM_vals)\n', (23842, 23851), True, 'import numpy as np\n'), ((23965, 23991), 'numpy.percentile', 'np.percentile', (['SM_vals', '(50)'], {}), '(SM_vals, 50)\n', (23978, 23991), True, 'import numpy as np\n'), ((24063, 24088), 'numpy.percentile', 'np.percentile', (['SM_vals', '(5)'], {}), '(SM_vals, 5)\n', (24076, 24088), True, 'import numpy as np\n'), ((24161, 24187), 'numpy.percentile', 'np.percentile', (['SM_vals', '(95)'], {}), '(SM_vals, 95)\n', (24174, 24187), True, 'import numpy as np\n'), ((24260, 24286), 'numpy.percentile', 'np.percentile', (['SM_vals', '(25)'], {}), '(SM_vals, 25)\n', (24273, 24286), True, 'import numpy as np\n'), ((24359, 24385), 'numpy.percentile', 'np.percentile', (['SM_vals', '(75)'], {}), '(SM_vals, 75)\n', (24372, 24385), True, 'import numpy as np\n'), ((25642, 25664), 'numpy.average', 'np.average', (['PyMC3_vals'], {}), '(PyMC3_vals)\n', (25652, 25664), True, 'import numpy as np\n'), ((25707, 25725), 'numpy.std', 'np.std', (['PyMC3_vals'], {}), '(PyMC3_vals)\n', (25713, 25725), True, 'import numpy as np\n'), ((25764, 25793), 'numpy.percentile', 'np.percentile', (['PyMC3_vals', '(50)'], {}), '(PyMC3_vals, 50)\n', (25777, 25793), True, 'import numpy as np\n'), ((25859, 25887), 'numpy.percentile', 'np.percentile', (['PyMC3_vals', '(5)'], {}), '(PyMC3_vals, 5)\n', (25872, 25887), True, 'import numpy as np\n'), ((25954, 25983), 'numpy.percentile', 'np.percentile', (['PyMC3_vals', '(95)'], {}), '(PyMC3_vals, 95)\n', (25967, 25983), True, 'import numpy as np\n'), ((26050, 26079), 'numpy.percentile', 'np.percentile', (['PyMC3_vals', '(25)'], {}), '(PyMC3_vals, 25)\n', (26063, 26079), True, 'import numpy as np\n'), ((26146, 26175), 'numpy.percentile', 'np.percentile', (['PyMC3_vals', '(75)'], {}), '(PyMC3_vals, 75)\n', (26159, 26175), True, 'import numpy as np\n'), ((20511, 20530), 'numpy.std', 'np.std', (['SM_acc_vals'], {}), '(SM_acc_vals)\n', (20517, 20530), True, 'import numpy as np\n'), ((23897, 23912), 'numpy.std', 'np.std', (['SM_vals'], {}), '(SM_vals)\n', (23903, 23912), True, 'import numpy as np\n'), ((24642, 24683), 'numpy.average', 'np.average', (['approx_type_vals[approx_type]'], {}), '(approx_type_vals[approx_type])\n', (24652, 24683), True, 'import numpy as np\n'), ((24748, 24785), 'numpy.std', 'np.std', (['approx_type_vals[approx_type]'], {}), '(approx_type_vals[approx_type])\n', (24754, 24785), True, 'import numpy as np\n'), ((24846, 24894), 'numpy.percentile', 'np.percentile', (['approx_type_vals[approx_type]', '(50)'], {}), '(approx_type_vals[approx_type], 50)\n', (24859, 24894), True, 'import numpy as np\n'), ((24986, 25033), 'numpy.percentile', 'np.percentile', (['approx_type_vals[approx_type]', '(5)'], {}), '(approx_type_vals[approx_type], 5)\n', (24999, 25033), True, 'import numpy as np\n'), ((25126, 25174), 'numpy.percentile', 'np.percentile', (['approx_type_vals[approx_type]', '(95)'], {}), '(approx_type_vals[approx_type], 95)\n', (25139, 25174), True, 'import numpy as np\n'), ((25267, 25315), 'numpy.percentile', 'np.percentile', (['approx_type_vals[approx_type]', '(25)'], {}), '(approx_type_vals[approx_type], 25)\n', (25280, 25315), True, 'import numpy as np\n'), ((25408, 25456), 'numpy.percentile', 'np.percentile', (['approx_type_vals[approx_type]', '(75)'], {}), '(approx_type_vals[approx_type], 75)\n', (25421, 25456), True, 'import numpy as np\n')]
import ast import contextlib import os from collections import defaultdict from os.path import expandvars from pathlib import Path from time import time import numpy as np import torch import yaml from addict import Dict from comet_ml import Experiment from funkybob import RandomNameGenerator from yaml import safe_load COMET_KWARGS = { "auto_metric_logging": False, "parse_args": True, "log_env_gpu": True, "log_env_cpu": True, "display_summary_level": 0, } KNOWN_TASKS = set(["discrete", "pendulum", "fluidbox", "attractor"]) ROOT = Path(__file__).resolve().parent.parent def mem_size(model): """ Get model size in GB (as str: "N GB") """ mem_params = sum( [param.nelement() * param.element_size() for param in model.parameters()] ) mem_bufs = sum([buf.nelement() * buf.element_size() for buf in model.buffers()]) mem = mem_params + mem_bufs return f"{mem / 1e9:.4f} GB" def num_params(model): """ Print number of parameters in model's named children and total """ s = "Number of parameters:\n" n_params = 0 for name, child in model.named_children(): n = sum(p.numel() for p in child.parameters()) s += f" • {name:<15}: {n}\n" n_params += n s += f"{'total':<19}: {n_params}" return s def resolve(path): """ fully resolve a path: resolve env vars ($HOME etc.) -> expand user (~) -> make absolute Returns: pathlib.Path: resolved absolute path """ return Path(expandvars(str(path))).expanduser().resolve() def load_opts(defaults=ROOT / "config/defaults.yaml", task=None, task_yaml=None): """ Load opts from a yaml config for a specific task Returns: addict.Dict: dot-accessible dict """ p = resolve(defaults) print("Loading default parameters from {}".format(str(p))) with p.open("r") as f: all_params = safe_load(f) if task_yaml is None: if task is None: if "task" not in all_params: raise ValueError("No task or task_yaml provided") task = all_params["task"] else: all_params["task"] = task task_yaml = ( Path(__file__).parent.parent / "config" / "tasks" / f'{all_params["task"]}.yaml' ) else: task_yaml = resolve(task_yaml) print("Updating default parameters from {}".format(str(task_yaml))) with task_yaml.open("r") as f: task_params = yaml.safe_load(f) all_params.update(task_params) return Dict(all_params) def new_unique_path(path): """ generates a new path from the input one by adding a random `adjective-noun` suffix. eg: new_unique_path("~/hello.txt") -> /Users/victor/hello.txt if it does not already exist -> /Users/victor/hello-gifted-boyed.txt if it does Works similarly for dirs Args: path (pathlike): path to get uniquely modified if it exists Returns: pathlib.Path: new non-existing path based on the input's path name and parent """ path = resolve(path) if not path.exists(): return path stem = path.stem suffix = path.suffix funky_gen = iter(RandomNameGenerator(members=2, separator="-")) while path.exists(): funky = next(funky_gen) path = path.parent / (stem + "-" + funky + suffix) return path def make_output_dir(path, dev=False): """ Create output dir with the path's name. If it exists, will append random `-adjective-name` suffix to make it uniquely identifiable mkdir will not be called if `dev` is True Returns: pathlib.Path: path to a unique empty dir """ path = new_unique_path(path) if not dev: path.mkdir(exist_ok=False, parents=True) else: print("Dev mode: output directory is not created") print("Using output directory:", str(path)) return path def get_optimizer(opts, model): """ Create optimizer and scheduler according to the opts """ opt_name = opts.optimizer.name.lower() if opt_name == "adam": opt_class = torch.optim.Adam else: raise NotImplementedError("Unknown optimizer " + opts.optimizer.name) optimizer = opt_class(model.parameters(), lr=opts.optimizer.lr) scheduler_name = opts.optimizer.get("scheduler", "").lower() if scheduler_name == "plateau": scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, factor=0.5, patience=20, min_lr=1e-6, ) else: scheduler = None return optimizer, scheduler def upload_code_and_parameters(exp: Experiment, opts: Dict): # code py_files = [] py_files += list(Path(__file__).resolve().parent.parent.glob("./*.py")) py_files += list(Path(__file__).resolve().parent.parent.glob("./scripts/*.py")) py_files += list(Path(__file__).resolve().parent.parent.glob("./aiphysim/*.py")) for py in py_files: exp.log_asset(str(py), file_name=f"{py.parent.name}/{py.name}") # parameters opts_dict = flatten_opts(opts) opts_dict["output_path"] = str(opts_dict["output_path"]) exp.log_parameters(opts_dict, prefix="opts") def save_config(opts, exp=None): if opts.get("dev"): print("Dev mode : config not saved to disk") return output_path = opts.output_path to_save = opts.to_dict() to_save["output_path"] = str(to_save["output_path"]) with open(output_path / "opts.yaml", "w") as f: yaml.safe_dump(to_save, f) if exp is not None: with open(output_path / "comet_url.txt", "w") as f: f.write(exp.url) def find_existing_comet_id(path): comet_file = path / "comet_url.txt" assert comet_file.exists() with comet_file.open("r") as f: comet_url = f.read().strip() return comet_url.split("/")[-1] def flatten_opts(opts: Dict) -> dict: """Flattens a multi-level addict.Dict or native dictionnary into a single level native dict with string keys representing the keys sequence to reach a value in the original argument. d = addict.Dict() d.a.b.c = 2 d.a.b.d = 3 d.a.e = 4 d.f = 5 flatten_opts(d) >>> { "a.b.c": 2, "a.b.d": 3, "a.e": 4, "f": 5, } Args: opts (addict.Dict or dict): addict dictionnary to flatten Returns: dict: flattened dictionnary """ values_list = [] def p(d, prefix="", vals=None): if vals is None: vals = [] for k, v in d.items(): if isinstance(v, (Dict, dict)): p(v, prefix + k + ".", vals) elif isinstance(v, list): if v and isinstance(v[0], (Dict, dict)): for i, m in enumerate(v): p(m, prefix + k + "." + str(i) + ".", vals) else: vals.append((prefix + k, str(v))) else: if isinstance(v, Path): v = str(v) vals.append((prefix + k, v)) p(opts, vals=values_list) return dict(values_list) def clean_checkpoints(path, n_max=5): path = resolve(path) ckpts = list(path.glob("*.ckpt")) ckpts = [c for c in ckpts if c.name not in ["latest.ckpt", "best.ckpt"]] if len(ckpts) < n_max: return sorted_ckpts = sorted(ckpts, key=lambda c: float(c.stem.split("loss_")[-1])) os.remove(sorted_ckpts[-1]) def dat_to_array(fname, shape=3): with resolve(fname).open("r") as f: lines = f.readlines() values = [list(map(ast.literal_eval, line.strip().split())) for line in lines] matrix = [ [v for value_tuple in tuple_list for v in value_tuple] for tuple_list in values ] array = np.array(matrix) return np.reshape(array, (-1, shape, array.shape[-1])) def timeit(func): def wrapper_time(*args, **kwargs): # https://math.stackexchange.com/questions/106700/incremental-averageing self = args[0] if not hasattr(self, "_times"): self._times = defaultdict(list) if not hasattr(self, "_mean_times"): self._mean_times = defaultdict(int) t = time() return_values = func(*args, **kwargs) new_duration = time() - t self._times[func.__name__].append(new_duration) n = len(self._times[func.__name__]) m = self._mean_times[func.__name__] self._mean_times[func.__name__] = m + (new_duration - m) / n return return_values return wrapper_time @contextlib.contextmanager def temp_seed(seed): state = np.random.get_state() np.random.seed(seed) try: yield finally: np.random.set_state(state)
[ "os.remove", "numpy.random.seed", "yaml.safe_dump", "numpy.random.get_state", "torch.optim.lr_scheduler.ReduceLROnPlateau", "time.time", "funkybob.RandomNameGenerator", "numpy.random.set_state", "collections.defaultdict", "pathlib.Path", "numpy.array", "numpy.reshape", "yaml.safe_load", "addict.Dict" ]
[((2586, 2602), 'addict.Dict', 'Dict', (['all_params'], {}), '(all_params)\n', (2590, 2602), False, 'from addict import Dict\n'), ((7529, 7556), 'os.remove', 'os.remove', (['sorted_ckpts[-1]'], {}), '(sorted_ckpts[-1])\n', (7538, 7556), False, 'import os\n'), ((7867, 7883), 'numpy.array', 'np.array', (['matrix'], {}), '(matrix)\n', (7875, 7883), True, 'import numpy as np\n'), ((7896, 7943), 'numpy.reshape', 'np.reshape', (['array', '(-1, shape, array.shape[-1])'], {}), '(array, (-1, shape, array.shape[-1]))\n', (7906, 7943), True, 'import numpy as np\n'), ((8713, 8734), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (8732, 8734), True, 'import numpy as np\n'), ((8739, 8759), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (8753, 8759), True, 'import numpy as np\n'), ((1916, 1928), 'yaml.safe_load', 'safe_load', (['f'], {}), '(f)\n', (1925, 1928), False, 'from yaml import safe_load\n'), ((2520, 2537), 'yaml.safe_load', 'yaml.safe_load', (['f'], {}), '(f)\n', (2534, 2537), False, 'import yaml\n'), ((3257, 3302), 'funkybob.RandomNameGenerator', 'RandomNameGenerator', ([], {'members': '(2)', 'separator': '"""-"""'}), "(members=2, separator='-')\n", (3276, 3302), False, 'from funkybob import RandomNameGenerator\n'), ((4473, 4570), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'torch.optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'factor': '(0.5)', 'patience': '(20)', 'min_lr': '(1e-06)'}), '(optimizer, factor=0.5, patience=\n 20, min_lr=1e-06)\n', (4515, 4570), False, 'import torch\n'), ((5596, 5622), 'yaml.safe_dump', 'yaml.safe_dump', (['to_save', 'f'], {}), '(to_save, f)\n', (5610, 5622), False, 'import yaml\n'), ((8296, 8302), 'time.time', 'time', ([], {}), '()\n', (8300, 8302), False, 'from time import time\n'), ((8804, 8830), 'numpy.random.set_state', 'np.random.set_state', (['state'], {}), '(state)\n', (8823, 8830), True, 'import numpy as np\n'), ((8173, 8190), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (8184, 8190), False, 'from collections import defaultdict\n'), ((8267, 8283), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (8278, 8283), False, 'from collections import defaultdict\n'), ((8372, 8378), 'time.time', 'time', ([], {}), '()\n', (8376, 8378), False, 'from time import time\n'), ((560, 574), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (564, 574), False, 'from pathlib import Path\n'), ((2213, 2227), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (2217, 2227), False, 'from pathlib import Path\n'), ((4805, 4819), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (4809, 4819), False, 'from pathlib import Path\n'), ((4881, 4895), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (4885, 4895), False, 'from pathlib import Path\n'), ((4965, 4979), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (4969, 4979), False, 'from pathlib import Path\n')]
import util.util as util import numpy as np import math def sigmoid(x): """ Logistic function for perceptron :param x: value to pass through logistic function :return: Float between 0.0 and 1.0 """ try: return 1 / (1 + math.exp(-x)) except OverflowError: if x < -50.0: return 1.0 return 0.0 class Perceptron: def __init__(self, fen, file): self.fen = fen self.weights = [] self.init_weights(file) def init_weights(self, file): """ Gets weights when perceptron is initialized. Updates self.weights :param file: File to get weights from :return: """ if file == "data/weights.npy": length = len(util.get_data(self.fen)) ret = util.get_weights( file, layer_sizes=np.array([ length, 128, 64, 1 ], dtype=object) ) for w in ret: self.weights.append(w) elif file == "data/promote_weights.npy": length = len(util.get_promote_data(self.fen, "n")) ret = util.get_weights( file, layer_sizes=np.array([ length, 128, 64, 1 ], dtype=object) ) for w in ret: self.weights.append(w) else: raise Exception("Filename should either be \"data/weights.npy\" or \"data/promote_weights.npy\"") def predict(self, data): """ Predicts chance of winning from fen-string and move :param data: a list with all the data :return: chance of winning """ output = 0.5 activation = data.copy() activations = [activation] for lr in range(len(self.weights)): biased_data = util.add_bias(activation) layer = np.zeros(len(self.weights[lr].T)) for to_node in range(len(layer)): for w in range(len(self.weights[lr])): b_data = biased_data[w] if b_data != 0: weight = self.weights[lr][w, to_node] layer[to_node] += b_data * weight layer[to_node] = sigmoid(layer[to_node]) if lr == len(self.weights) - 1: output = layer[0] else: activation = layer.copy() activations.append(activation) return output, activations def back_prop(self, data, predict, target, eta=0.1): """ Backpropagation for perceptron. Updates weights. :param data: old weights and activations :param predict: Predicted value :param target: Target value :param eta: Learning Rate :return: new weights """ ret_weights = [] full_data = data.copy() full_data.append([predict]) delta = [(predict - target) * predict * (1 - predict)] for lr in range(-1, -len(self.weights)-1, -1): new_weights = np.array([self.weights[lr][i] for i in range(len(self.weights[lr]))]) current_data = full_data[lr] biased_activation = util.add_bias(full_data[lr - 1]) delta.append([]) for i in range(len(new_weights)): if lr != abs(len(self.weights)): delta[abs(lr)].append( biased_activation[i] * (1 - biased_activation[i]) ) if lr == -1: new_weights[i] = new_weights[i] - eta * delta[0] * current_data[0] delta[abs(lr)][i] += delta[0] * self.weights[lr][i] elif lr != -len(self.weights): delta_times = 0.0 for j in range(len(new_weights[i])): new_weights[i][j] = self.weights[lr][i][j] - eta * delta[abs(lr+1)][j+1] * biased_activation[i] delta_times += delta[abs(lr+1)][j+1] * self.weights[lr][i][j] delta[abs(lr)][i] = delta[abs(lr)][i] * delta_times else: if biased_activation[i] != 0: for j in range(len(new_weights[i])): new_weights[i][j] = self.weights[lr][i][j] - eta \ * delta[abs(lr+1)][j+1] * biased_activation[i] ret_weights.append(new_weights) ret_weights.reverse() return ret_weights
[ "math.exp", "util.util.get_promote_data", "util.util.get_data", "numpy.array", "util.util.add_bias" ]
[((1985, 2010), 'util.util.add_bias', 'util.add_bias', (['activation'], {}), '(activation)\n', (1998, 2010), True, 'import util.util as util\n'), ((3350, 3382), 'util.util.add_bias', 'util.add_bias', (['full_data[lr - 1]'], {}), '(full_data[lr - 1])\n', (3363, 3382), True, 'import util.util as util\n'), ((253, 265), 'math.exp', 'math.exp', (['(-x)'], {}), '(-x)\n', (261, 265), False, 'import math\n'), ((753, 776), 'util.util.get_data', 'util.get_data', (['self.fen'], {}), '(self.fen)\n', (766, 776), True, 'import util.util as util\n'), ((864, 908), 'numpy.array', 'np.array', (['[length, 128, 64, 1]'], {'dtype': 'object'}), '([length, 128, 64, 1], dtype=object)\n', (872, 908), True, 'import numpy as np\n'), ((1161, 1197), 'util.util.get_promote_data', 'util.get_promote_data', (['self.fen', '"""n"""'], {}), "(self.fen, 'n')\n", (1182, 1197), True, 'import util.util as util\n'), ((1285, 1329), 'numpy.array', 'np.array', (['[length, 128, 64, 1]'], {'dtype': 'object'}), '([length, 128, 64, 1], dtype=object)\n', (1293, 1329), True, 'import numpy as np\n')]
import os import numpy as np import open3d as o3d # from TUM_RGBD import load_K_Rt_from_P from vis_cameras import visualize def get_box(vol_bnds): points = [ [vol_bnds[0, 0], vol_bnds[1, 0], vol_bnds[2, 0]], [vol_bnds[0, 1], vol_bnds[1, 0], vol_bnds[2, 0]], [vol_bnds[0, 0], vol_bnds[1, 1], vol_bnds[2, 0]], [vol_bnds[0, 1], vol_bnds[1, 1], vol_bnds[2, 0]], [vol_bnds[0, 0], vol_bnds[1, 0], vol_bnds[2, 1]], [vol_bnds[0, 1], vol_bnds[1, 0], vol_bnds[2, 1]], [vol_bnds[0, 0], vol_bnds[1, 1], vol_bnds[2, 1]], [vol_bnds[0, 1], vol_bnds[1, 1], vol_bnds[2, 1]], ] lines = [ [0, 1], [0, 2], [1, 3], [2, 3], [4, 5], [4, 6], [5, 7], [6, 7], [0, 4], [1, 5], [2, 6], [3, 7], ] colors = [[1, 0, 0] for i in range(len(lines))] line_set = o3d.geometry.LineSet( points=o3d.utility.Vector3dVector(points), lines=o3d.utility.Vector2iVector(lines), ) line_set.colors = o3d.utility.Vector3dVector(colors) return line_set if __name__ == "__main__": base_dir = "../DATAROOT/ICL/living_room_traj2_frei" # cam_dict = np.load(os.path.join(base_dir, "processed", "cameras.npz")) # world_mats = cam_dict["world_mats"] # poses = [] # # for i, P in enumerate(world_mats): # if i % 30 != 0: # continue # P = P[:3, :4] # K, pose = load_K_Rt_from_P(P) # poses += [pose[None, ...]] # extrinsics = np.concatenate(poses, axis=0) mesh = o3d.io.read_triangle_mesh(os.path.join(base_dir, "mesh-aligned.ply")) # mesh = o3d.io.read_triangle_mesh("/home/jingwen/vision/dev/Atlas/results/release/semseg/test_final/mesh.ply") xmin, xmax = -2., 3.5 ymin, ymax = -1.5, 5. zmin, zmax = -1.3, 1.5 vol_bnds = np.array([[xmin, xmax], [ymin, ymax], [zmin, zmax]]) inner_sphere = get_box(vol_bnds) things_to_draw = [inner_sphere, mesh] # mesh = o3d.io.read_triangle_mesh("/home/jingwen/Vision/dev/sdf-nerf/logs/fr3_long_office_depth/3/testset_050000/mesh.ply") # T = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # cube = draw_cuboid(T=T) # cube.scale(2., [0., 0., 0.]) visualize(things_to_draw=things_to_draw)
[ "os.path.join", "vis_cameras.visualize", "open3d.utility.Vector2iVector", "numpy.array", "open3d.utility.Vector3dVector" ]
[((1063, 1097), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['colors'], {}), '(colors)\n', (1089, 1097), True, 'import open3d as o3d\n'), ((1876, 1928), 'numpy.array', 'np.array', (['[[xmin, xmax], [ymin, ymax], [zmin, zmax]]'], {}), '([[xmin, xmax], [ymin, ymax], [zmin, zmax]])\n', (1884, 1928), True, 'import numpy as np\n'), ((2350, 2390), 'vis_cameras.visualize', 'visualize', ([], {'things_to_draw': 'things_to_draw'}), '(things_to_draw=things_to_draw)\n', (2359, 2390), False, 'from vis_cameras import visualize\n'), ((1622, 1664), 'os.path.join', 'os.path.join', (['base_dir', '"""mesh-aligned.ply"""'], {}), "(base_dir, 'mesh-aligned.ply')\n", (1634, 1664), False, 'import os\n'), ((950, 984), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['points'], {}), '(points)\n', (976, 984), True, 'import open3d as o3d\n'), ((1000, 1033), 'open3d.utility.Vector2iVector', 'o3d.utility.Vector2iVector', (['lines'], {}), '(lines)\n', (1026, 1033), True, 'import open3d as o3d\n')]
#!/usr/bin/env python3 # Copyright 2018 archproj-bmwteam # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import argparse import numpy as np from graph_tool.all import * from pprint import pprint import jsonparser import graph_analyzer STANDARD_OUT_DIR = "../out/" def shared_sub_graphs_direct_list(node_compare_list1: list, node_compare_list2: list, head_list1: list, head_list2: list): """ The function takes two lists of lists containing subgraphs that should be checked for overlap with each element of the other list. also takes two "head_lists" which have to be the same length as their respective node_compare_list and contain identifiers for the subgraphs at the same position as in node_compare_list. The function is a helper to call shared_sub_graphs_direct with every element of the first list and the second list. :param node_compare_list1: list of lists each containing the node_ids of an individual subgraph. :param node_compare_list2: list of lists each containing the node_ids of an individual subgraph. :param head_list1: list of identifiers belonging to the head-node of each list in node_compare_list1. Has to have the same order and length as node_compare_list1. :param head_list2: list of identifiers belonging to the head-node of each list in node_compare_list2. Has to have the same order and length as node_compare_list2. :return: a list of identifier pairs (depending on the head_lists) whose subgraphs are directly overlapping. """ result = [] for i in range(0, len(node_compare_list1)): ncl1_dict = {} for node in node_compare_list1[i]: ncl1_dict[str(node)] = True result_i = shared_sub_graphs_direct(ncl1_dict, node_compare_list2, head_list2) for name in result_i: result.append((head_list1[i], name)) return result def shared_sub_graphs_direct(main_nodes: dict, node_compare_list: list, head_list: list): """ The function takes a dictionary of a subgraph and a list of lists containing other subgraphs. It also takes a "head_list" which has to be the same length as node_compare_list and contains identifiers for the subgraphs at the same position as in node_compare_list. The function checks whether any of the subgraphs in the list shares a node with the subgraph-dictionary and returns a list of identifiers of the overlapping subgraphs. :param main_nodes: a dictionary containing True at every node_id of an original graph. :param node_compare_list: list of lists each containing the node_ids of an individual subgraph. :param head_list: list of identifiers belonging to the head_node of each list in node_compare_list. Has to have the same order and length as node_compare_list. :return: a list of identifiers (depending on head_list) whose subgraphs are directly overlapping with any of the main_nodes. """ result_list = [] for i in range(0, len(node_compare_list)): compare_nodes = node_compare_list[i] is_overlapping = False for n in compare_nodes: if main_nodes.get(str(n)) is True: is_overlapping = True break if is_overlapping is True: result_list.append(head_list[i]) return result_list def shared_sub_graphs_indirect(graph: Graph, node_compare_list: list): """ The function takes a graph and a list of lists containing node_ids. It checks which node_ids subgraphs are connected either directly or indirectly via other node_id subgraphs. This means two nodes either sharing a part of their subgraph or being indirectly connected via other nodes from the node_compare_list. :param graph: the graph whose nodes should be checked. :param node_compare_list: the nodes to be compared with each other :return: a list of lists, each containing all nodes in/directly connected to each other. Each node from node_compare_list only appears once. """ # load all subgraphs once loaded_nodes = [] # for i in node_compare_list: for i in range(0, len(node_compare_list)): vertices = graph_analyzer.collect_subgraph_vertices(graph, int(node_compare_list[i])) loaded_nodes.append(vertices) overlapping_information = [] for i in range(0, len(node_compare_list) - 1): # current main node for subgraph-check current_node_compare_list = loaded_nodes[(i + 1):] head_list = node_compare_list[(i + 1):] main_nodes_vtx = loaded_nodes[i] main_nodes = {} for vtx in main_nodes_vtx: main_nodes[str(vtx)] = True overlapping_subgraphs = shared_sub_graphs_direct(main_nodes, current_node_compare_list, head_list) overlapping_information.append(overlapping_subgraphs) overlapping_information[i].append(node_compare_list[i]) # by now we got all direct connections of subgraphs. test03.dot would output [['2', '1'], ['3', '2'], ['4', '3']] result_list = find_adjacent(overlapping_information, node_compare_list) # here we've got all indirect connections. test03.dot would output [['1', '2', '3', '4']] return result_list def find_adjacent(overlapping_information: list, existing_nodes: list): """ Gets a list of directly connected subgraphs and creates the indirect connections. :param overlapping_information: a list of lists each containing direct connections betweeen some subgraphs. :param existing_nodes: a list containing each existing node once. :return: a list of lists each containing all reachable subgraphs with other connected subgraphs in between. """ result_connections = [] for node in existing_nodes: already_checked = False for c in result_connections: if node in c: already_checked = True break if already_checked is True: continue connection_list = [] connection_list.append(node) has_changed = True while has_changed is True: has_changed = False for direct_connection in overlapping_information: will_be_checked = False for n in connection_list: if n in direct_connection: will_be_checked = True break if will_be_checked is True: for new_node in direct_connection: if new_node not in connection_list: connection_list.append(new_node) has_changed = True result_connections.append(connection_list) return result_connections def validate_children_subgraphs(graph: Graph, parent_dictionary: dict): """ The function takes a graph and the corresponding dictionary containing parent names as keys and children ID lists as values (as created in find_childnodes) and checks for every parent whether every childrens subgraphs overlap or not. :param graph: the graph for which the nodes in the dictionary should be validated :param parent_dictionary: a dictionary as created in find_childnodes :return: a list filled with one list for each parent whose children are not part of exactly one graph (judging by the connection of their subgraphs). Each list contains lists of all nodes connected among each other. Also at the end of every list regarding one parent, there is a string containing the name of the parent """ results = [] counter = 1 for key, node_collection in parent_dictionary.items(): print("---------------------------------- node_collection " "%i of %i (with size %i): %s" % (counter, len(parent_dictionary), len(node_collection), key)) counter = counter + 1 connected_graphs = shared_sub_graphs_indirect(graph, node_collection) print("For this key there is/are %i different subgraph/s" % len(connected_graphs)) if len(connected_graphs) != 1: for g in connected_graphs: print(g) if len(connected_graphs) != 1: connected_graphs.append(key) results.append(connected_graphs) # result looks like [[[node1, node2], [node3, node4], "graph1"], [[node5], [node6, node7, node8], "graph2"]] return results def create_parents(graph_filename: str, json_filename: str): """ The function takes the paths to a graph and a json file (in our bmw-json format) and searches the graph for all names contained in the json file. Afterwards the graph_analyzer is used to each create a parent node "containing" all found child nodes. :param graph_filename: the path to the graph to be searched :param json_filename: the path to a json file (in our bmw-json format) with search names as names containing all the names for the parent creation """ graph = load_graph(graph_filename) parent_dictionary = find_childnodes(graph, json_filename) # combine all childnodes of components to a parentnode for name, childnodes in parent_dictionary.items(): graph = graph_analyzer.add_parent(graph, name, childnodes) # add domains, contextGroups and abstractionLayers as parents of the components domain_list = jsonparser.get_domains(json_filename) for domain in domain_list: comp_list = jsonparser.search_by_domain(json_filename, domain) comp_list_new = [] for c in comp_list: if ("no Match" in c) or ("kein Match" in c): continue comp_list_new.append(c) lis = graph_analyzer.parse_node_values(graph, comp_list_new) graph = graph_analyzer.add_parent(graph, domain, lis) context_group_list = jsonparser.get_context_groups(json_filename) for context in context_group_list: comp_list = jsonparser.search_by_context(json_filename, context) comp_list_new = [] for c in comp_list: if ("no Match" in c) or ("kein Match" in c): continue comp_list_new.append(c) lis = graph_analyzer.parse_node_values(graph, comp_list_new) graph = graph_analyzer.add_parent(graph, context, lis) abstraction_layer_list = jsonparser.get_abstraction_layers(json_filename) for layer in abstraction_layer_list: comp_list = jsonparser.search_by_abstraction(json_filename, layer) comp_list_new = [] for c in comp_list: if ("no Match" in c) or ("kein Match" in c): continue comp_list_new.append(c) lis = graph_analyzer.parse_node_values(graph, comp_list_new) graph = graph_analyzer.add_parent(graph, layer, lis) # add one node for domains, context groups and abstraction layers each domain_list_ids = graph_analyzer.parse_node_values(graph, domain_list) graph = graph_analyzer.add_parent(graph, "DOMAINS", domain_list_ids) context_group_ids = graph_analyzer.parse_node_values(graph, context_group_list) graph = graph_analyzer.add_parent(graph, "CONTEXT_GROUPS", context_group_ids) abstraction_layer_ids = graph_analyzer.parse_node_values(graph, abstraction_layer_list) graph = graph_analyzer.add_parent(graph, "ABSTRACTION_LAYERS", abstraction_layer_ids) graph_analyzer.export_graph(graph, STANDARD_OUT_DIR + "parent_handler_output") def find_childnodes(graph: Graph, json_filename: str): """ The function gets a graph and a json filename in our bmw-json format and searches the graph for all component names in the json file. Those names can have the form "App&CD;Pie" causing a search for nodes containing both the words "App" and "CD" and nodes containing "Pie" - just like in the grep_adapter. The nodes are then listed in a dictionary with the original name from the json file as the key. This dictionary is then retured. :param graph: the graph to be searched :param json_filename: the path to a json file (in our bmw-json format) containing all the names for the search :return: a dictionary with names from the json file as keys and all found nodes in a list as value """ parent_dictionary = {} all_names = jsonparser.all_components(json_filename) for name in all_names: if ("kein Match" in name) or ("no Match" in name): continue search_names = name.split(";") node_collection = [] for s_name in search_names: s_parts = s_name.split("&") # search for nodes containing every word in s_parts # initialize word_result_list with results of the first word wrl = graph_analyzer.search_vertices(graph, s_parts[0]) # change from vertex object to string word_result_list = [] for v in wrl: word_result_list.append(str(v)) # word_result_list = list(set(word_result_list)) for word in s_parts: nl = graph_analyzer.search_vertices(graph, word) # change from vertex object to string node_list = [] for v in nl: node_list.append(str(v)) # remove nodes from word_result_list that are not in node_list remove_list = [] for node in word_result_list: if node not in node_list: # word_result_list.remove(node) remove_list.append(node) for node in remove_list: word_result_list.remove(node) # append result to node_collection for n in word_result_list: if n not in node_collection: node_collection.append(n) if not node_collection: print("there were no results for the search '%s'" % name) parent_dictionary[name] = node_collection return parent_dictionary def get_validation_dict_domains(graph: Graph, json_filename: str): """ The function gets a graph and searches it for all Domain names. It returns a dictionary which can be given to validate_children_subgraphs, checking the Isolation Constraint for all Domains individually. Thus its form is the name of a Domain as key and all this Domains direct children in a list as values. :param graph: the graph to be searched :param json_filename: the path to a json file (in our bmw-json format) containing at least every Domain name once at any component (it is suggested to use the json file containing search names or the one conatining HLA-names) :return: a dictionary with Domain names as keys and all found children in a list as value """ domain_list = jsonparser.get_domains(json_filename) domain_list_new = [] for d in domain_list: if ("no Match" in d) or ("kein Match" in d): continue domain_list_new.append(d) domain_list_ids = graph_analyzer.parse_node_values(graph, domain_list_new) domain_dict = {} for d in domain_list_new: domain_dict[d] = [] for d in range(0, len(domain_list_ids)): domain_childnodes = graph.get_out_neighbours(domain_list_ids[d]) for child in domain_childnodes: domain_dict[domain_list_new[d]].append(child) return domain_dict def get_validation_dict_context_groups(graph: Graph, json_filename: str): """ The function gets a graph and searches it for all Context Group names. It returns a dictionary which can be given to validate_children_subgraphs, checking the Isolation Constraint for all Context Groups individually. Thus its form is the name of a Context Group as key and all this Context Groups direct children in a list as values. :param graph: the graph to be searched :param json_filename: the path to a json file (in our bmw-json format) containing at least every Context Group name once at any component (it is suggested to use the json file containing search names or the one conatining HLA-names) :return: a dictionary with Context Group names as keys and all found children in a list as value """ context_group_list = jsonparser.get_context_groups(json_filename) context_group_list_new = [] for c in context_group_list: if ("no Match" in c) or ("kein Match" in c): continue context_group_list_new.append(c) context_group_list_ids = graph_analyzer.parse_node_values(graph, context_group_list_new) context_group_dict = {} for c in context_group_list_new: context_group_dict[c] = [] for c in range(0, len(context_group_list_ids)): context_group_childnodes = graph.get_out_neighbours(context_group_list_ids[c]) for child in context_group_childnodes: context_group_dict[context_group_list_new[c]].append(child) return context_group_dict def get_validation_dict_abstraction_layers(graph: Graph, json_filename: str): """ The function gets a graph and searches it for all Abstraction Layer names. It returns a dictionary which can be given to validate_children_subgraphs, checking the Isolation Constraint for all Abstraction Layers individually. Thus its form is the name of a Abstraction Layer as key and all this Abstraction Layers direct children in a list as values. :param graph: the graph to be searched :param json_filename: the path to a json file (in our bmw-json format) containing at least every Abstraction Layer name once at any component (it is suggested to use the json file containing search names or the one conatining HLA-names) :return: a dictionary with Abstraction Layer names as keys and all found children in a list as value """ abstraction_layer_list = jsonparser.get_abstraction_layers(json_filename) abstraction_layer_list_new = [] for a in abstraction_layer_list: if ("no Match" in a) or ("kein Match" in a): continue abstraction_layer_list_new.append(a) abstraction_layer_list_ids = graph_analyzer.parse_node_values(graph, abstraction_layer_list_new) abstraction_layer_dict = {} for a in abstraction_layer_list_new: abstraction_layer_dict[a] = [] for a in range(0, len(abstraction_layer_list_ids)): abstraction_layer_childnodes = graph.get_out_neighbours(abstraction_layer_list_ids[a]) for child in abstraction_layer_childnodes: abstraction_layer_dict[abstraction_layer_list_new[a]].append(child) return abstraction_layer_dict def print_top_level_connections(graph: Graph, json_filename: str): """ Gets a graph and searches all Domain/ContextGroup/AbstractionLayer-names (which can be created using parent_handler -c). The function each checks the connections between every member of those and prints the result using print_connection_dict. :param graph: The graph to be checked. :param json_filename: the path to a json file (in our bmw-json format) containing the names of the top-level nodes """ domain_list = jsonparser.get_domains(json_filename) context_group_list = jsonparser.get_context_groups(json_filename) abstraction_layer_list = jsonparser.get_abstraction_layers(json_filename) domain_list_new = [] context_group_list_new = [] abstraction_layer_list_new = [] for d in domain_list: if ("no Match" in d) or ("kein Match" in d): continue domain_list_new.append(d) for c in context_group_list: if ("no Match" in c) or ("kein Match" in c): continue context_group_list_new.append(c) for a in abstraction_layer_list: if ("no Match" in a) or ("kein Match" in a): continue abstraction_layer_list_new.append(a) domain_list_ids = graph_analyzer.parse_node_values(graph, domain_list_new) context_group_ids = graph_analyzer.parse_node_values(graph, context_group_list_new) abstraction_layer_ids = graph_analyzer.parse_node_values(graph, abstraction_layer_list_new) domain_subgraphs = [] # length equals amount of domains. # Contains all nodes of one domain and its subgraph at each field. # [[subgraph1],[subgraph2]] domain_child_subgraphs = [] # length equals amount of domains. # Contains a list of lists each containing all children of a domain # (components) and their complete subgraph at each field. # [[[copm_subgraph1], [comp_subgraph2]], [[copm_subgraph1], [comp_subgraph2]]] context_group_subgraphs = [] context_group_child_subgraphs = [] abstraction_layer_subgraphs = [] abstraction_layer_child_subgraphs = [] # load vertices for d in range(0, len(domain_list_ids)): domain_subgraphs.append([domain_list_ids[d]]) domain_child_subgraphs.append([]) children = graph.get_out_neighbours(domain_list_ids[d]) for child in children: child_subgraph = graph_analyzer.collect_subgraph_vertices(graph, child) for n in child_subgraph: domain_subgraphs[d].append(n) domain_child_subgraphs[d].append(child_subgraph) for c in range(0, len(context_group_ids)): context_group_subgraphs.append([context_group_ids[c]]) context_group_child_subgraphs.append([]) children = graph.get_out_neighbours(context_group_ids[c]) for child in children: child_subgraph = graph_analyzer.collect_subgraph_vertices(graph, child) for n in child_subgraph: context_group_subgraphs[c].append(n) context_group_child_subgraphs[c].append(child_subgraph) for a in range(0, len(abstraction_layer_ids)): abstraction_layer_subgraphs.append([abstraction_layer_ids[a]]) abstraction_layer_child_subgraphs.append([]) children = graph.get_out_neighbours(abstraction_layer_ids[a]) for child in children: child_subgraph = graph_analyzer.collect_subgraph_vertices(graph, child) for n in child_subgraph: abstraction_layer_subgraphs[a].append(n) abstraction_layer_child_subgraphs[a].append(child_subgraph) domain_dict_all_collisions = {} domain_dict_component_collisions = {} context_dict_all_collisions = {} context_dict_component_collisions = {} abstraction_dict_all_collisions = {} abstraction_dict_component_collisions = {} # compare subgraphs for i in range(0, len(domain_list_ids)): print( "currently checking Domains at position %i of %i (%s)" % (i, len(domain_list_ids) - 1, domain_list_new[i])) domain_dict_all_collisions[domain_list_new[i]] = [] domain_dict_component_collisions[domain_list_new[i]] = [] for j in range(0, len(domain_list_ids)): subcollisions = 0 # count all subcollisions component_collisions = 0 # count all collisions of components if i == j: subcollisions = -1 component_collisions = -1 else: subcollision_list = graph_analyzer.list_shared_sub_vertices(graph, domain_list_ids[i], domain_list_ids[j]) subcollisions = len(subcollision_list) component_subcollision_list = shared_sub_graphs_direct_list(domain_child_subgraphs[i], domain_child_subgraphs[j], domain_child_subgraphs[i], domain_child_subgraphs[j]) component_collisions = len(component_subcollision_list) # append to solution subcollisions_pair = (domain_list_new[j], subcollisions) domain_dict_all_collisions[domain_list_new[i]].append(subcollisions_pair) component_collisions_pair = (domain_list_new[j], component_collisions) domain_dict_component_collisions[domain_list_new[i]].append(component_collisions_pair) print("Domains done.") print_connection_dict_advanced(domain_dict_all_collisions, STANDARD_OUT_DIR + "domain.csv") print_connection_dict_advanced(domain_dict_component_collisions, STANDARD_OUT_DIR + "domain_component_collisions.csv") print("Domains output written") for i in range(0, len(context_group_ids)): print("currently checking Context Groups at position %i of %i (%s)" % (i, len(context_group_ids) - 1, context_group_list_new[i])) context_dict_all_collisions[context_group_list_new[i]] = [] context_dict_component_collisions[context_group_list_new[i]] = [] for j in range(0, len(context_group_ids)): subcollisions = 0 # count all subcollisions component_collisions = 0 # count all collisions of components if i == j: subcollisions = -1 component_collisions = -1 else: subcollision_list = graph_analyzer.list_shared_sub_vertices(graph, context_group_ids[i], context_group_ids[j]) subcollisions = len(subcollision_list) component_subcollision_list = shared_sub_graphs_direct_list(context_group_child_subgraphs[i], context_group_child_subgraphs[j], context_group_child_subgraphs[i], context_group_child_subgraphs[j]) component_collisions = len(component_subcollision_list) # append to solution subcollisions_pair = (context_group_list_new[j], subcollisions) context_dict_all_collisions[context_group_list_new[i]].append(subcollisions_pair) component_collisions_pair = (context_group_list_new[j], component_collisions) context_dict_component_collisions[context_group_list_new[i]].append(component_collisions_pair) print("Context Groups done.") print_connection_dict_advanced(context_dict_all_collisions, STANDARD_OUT_DIR + "context.csv") print_connection_dict_advanced(context_dict_component_collisions, STANDARD_OUT_DIR + "context_component_collisions.csv") print("Context Groups Output written") for i in range(0, len(abstraction_layer_ids)): print("currently checking Abstraction Layers at position %i of %i (%s)" % (i, len(abstraction_layer_ids) - 1, abstraction_layer_list_new[i])) abstraction_dict_all_collisions[abstraction_layer_list_new[i]] = [] abstraction_dict_component_collisions[abstraction_layer_list_new[i]] = [] for j in range(0, len(abstraction_layer_ids)): subcollisions = 0 # count all subcollisions component_collisions = 0 # count all collisions of components if i == j: subcollisions = -1 component_collisions = -1 else: subcollision_list = graph_analyzer.list_shared_sub_vertices(graph, abstraction_layer_ids[i], abstraction_layer_ids[j]) subcollisions = len(subcollision_list) component_subcollision_list = shared_sub_graphs_direct_list(abstraction_layer_child_subgraphs[i], abstraction_layer_child_subgraphs[j], abstraction_layer_child_subgraphs[i], abstraction_layer_child_subgraphs[j]) component_collisions = len(component_subcollision_list) # append to solution subcollisions_pair = (abstraction_layer_list_new[j], subcollisions) abstraction_dict_all_collisions[abstraction_layer_list_new[i]].append(subcollisions_pair) component_collisions_pair = (abstraction_layer_list_new[j], component_collisions) abstraction_dict_component_collisions[abstraction_layer_list_new[i]].append(component_collisions_pair) print("Abstraction Layers done. Now writing output.") print_connection_dict_advanced(abstraction_dict_all_collisions, STANDARD_OUT_DIR + "abstraction.csv") print_connection_dict_advanced(abstraction_dict_component_collisions, STANDARD_OUT_DIR + "abstraction_component_collisions.csv") print("Done") def print_connection_dict_advanced(d: dict, file_name: str): """ Gets a dictionary with Domain/ContextGroup/AbstractionLayer-names as keys and a list with all the Domains/ContextGroups/AbstractionLayers they overlap with as values. Prints stuff sorted alphabetically to command line / file. :param d: A dictionary containing advanced overlapping information. :param file_name: the name of the output file. """ output_array = np.zeros((len(d), len(d))) i = 0 key_list = sorted(d.keys()) for key in key_list: list_of_name_count_pairs = d[key] for name_count_pair in list_of_name_count_pairs: name, count = name_count_pair j = key_list.index(name) output_array[i][j] = count i = i + 1 np.savetxt(file_name, output_array, delimiter=",", fmt="%.0f") print(output_array) print("") print(key_list) print("") print("") with open(STANDARD_OUT_DIR + file_name, "r+", encoding="utf-8") as outfile: content = outfile.read() s = ', '.join(map(str, key_list)) outfile.write(s) outfile.seek(0, 0) outfile.write(s.rstrip('\r\n') + '\n' + content) def main(argv): """ Main function which parses the passed arguments. :param argv: the argument list passed by the command line """ parser = argparse.ArgumentParser( description="A script to search a graph for all nodes mentioned in a json file (in our bmw-json format). " "Those nodes are then each combined into a parent node and the resulting graph is then outputted " "in another file. " "This has to be called from withing our src folder as it uses the jsonparser and graph_analyzer. " "Another service is the validation of parent nodes. This checks whether all children are somehow " "connected to each other. " "For testing you can also call this with test03.dot and test03.json.") parser.add_argument('file1', type=str, metavar='GRAPH_FILE', help=".dot or .gt file containing a graph.") parser.add_argument('-j', '--json_file', type=str, metavar='JSON_FILE', help=".json file containing node names.") parser.add_argument('-c', '--createParents', action='store_true', help="Create parents according to the json file.") parser.add_argument('-v', '--validate', action='store_true', help="Validate connection of the children in the json file.") parser.add_argument('--validate_components_only', action='store_true', help="Calls the normal validation, but only for Components. Used for examples") parser.add_argument('-p', '--print_top_level_connections', action='store_true', help="Prints Connections between domains & co. and which nodes cause them.") args = parser.parse_args() if (not args.file1) or (not args.json_file): print("Try 'parent_handler -h' for more information.") sys.exit(1) if args.createParents: create_parents(args.file1, args.json_file) return if args.validate or args.validate_components_only: graph = load_graph(args.file1) print("creation of dictionaries has begun") component_dict = find_childnodes(graph, args.json_file) validation_dict_domains = {} validation_dict_context_groups = {} validation_dict_abstraction_layers = {} if args.validate_components_only is False: validation_dict_domains = get_validation_dict_domains(graph, args.json_file) validation_dict_context_groups = get_validation_dict_context_groups(graph, args.json_file) validation_dict_abstraction_layers = get_validation_dict_abstraction_layers(graph, args.json_file) print("validation has begun") print("\nvalidating Isolation Constraint of all Components\n") trouble_list1 = validate_children_subgraphs(graph, component_dict) print("\nvalidating Isolation Constraint of all Domains\n") trouble_list2 = validate_children_subgraphs(graph, validation_dict_domains) print("\nvalidating Isolation Constraint of all Context Groups\n") trouble_list3 = validate_children_subgraphs(graph, validation_dict_context_groups) print("\nvalidating Isolation Constraint of all Abstraction Layers\n") trouble_list4 = validate_children_subgraphs(graph, validation_dict_abstraction_layers) trouble_list = trouble_list1 + trouble_list2 + trouble_list3 + trouble_list4 if trouble_list: # print on command line print("the following nodes and their subgraphs aren't connected even though they share the same parent:") for graph in trouble_list: print(graph[len(graph) - 1] + ":") for i in range(0, len(graph) - 1): print(graph[i]) print("") # write to file with open(STANDARD_OUT_DIR + "parent_handler_validation.txt", "w", encoding="utf-8") as file: for graph in trouble_list: file.write(graph[len(graph) - 1] + "\n") lists = graph[0:len(graph) - 1] for lis in lists: file.write(lis[0]) for i in range(1, len(lis)): file.write(",") file.write(lis[i]) file.write("\n") file.write("\n") else: print("Everything is fine. All nodes with the same parent are somewhere connected within their subgraphs") return if args.print_top_level_connections: graph = load_graph(args.file1) print_top_level_connections(graph, args.json_file) return if __name__ == "__main__": main(sys.argv[1:])
[ "jsonparser.search_by_abstraction", "argparse.ArgumentParser", "jsonparser.get_abstraction_layers", "jsonparser.search_by_domain", "graph_analyzer.add_parent", "graph_analyzer.list_shared_sub_vertices", "numpy.savetxt", "jsonparser.get_domains", "jsonparser.search_by_context", "graph_analyzer.search_vertices", "graph_analyzer.collect_subgraph_vertices", "jsonparser.get_context_groups", "jsonparser.all_components", "graph_analyzer.parse_node_values", "sys.exit", "graph_analyzer.export_graph" ]
[((9970, 10007), 'jsonparser.get_domains', 'jsonparser.get_domains', (['json_filename'], {}), '(json_filename)\n', (9992, 10007), False, 'import jsonparser\n'), ((10440, 10484), 'jsonparser.get_context_groups', 'jsonparser.get_context_groups', (['json_filename'], {}), '(json_filename)\n', (10469, 10484), False, 'import jsonparser\n'), ((10932, 10980), 'jsonparser.get_abstraction_layers', 'jsonparser.get_abstraction_layers', (['json_filename'], {}), '(json_filename)\n', (10965, 10980), False, 'import jsonparser\n'), ((11498, 11550), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'domain_list'], {}), '(graph, domain_list)\n', (11530, 11550), False, 'import graph_analyzer\n'), ((11563, 11623), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', '"""DOMAINS"""', 'domain_list_ids'], {}), "(graph, 'DOMAINS', domain_list_ids)\n", (11588, 11623), False, 'import graph_analyzer\n'), ((11649, 11708), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'context_group_list'], {}), '(graph, context_group_list)\n', (11681, 11708), False, 'import graph_analyzer\n'), ((11721, 11790), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', '"""CONTEXT_GROUPS"""', 'context_group_ids'], {}), "(graph, 'CONTEXT_GROUPS', context_group_ids)\n", (11746, 11790), False, 'import graph_analyzer\n'), ((11820, 11883), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'abstraction_layer_list'], {}), '(graph, abstraction_layer_list)\n', (11852, 11883), False, 'import graph_analyzer\n'), ((11896, 11973), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', '"""ABSTRACTION_LAYERS"""', 'abstraction_layer_ids'], {}), "(graph, 'ABSTRACTION_LAYERS', abstraction_layer_ids)\n", (11921, 11973), False, 'import graph_analyzer\n'), ((11979, 12057), 'graph_analyzer.export_graph', 'graph_analyzer.export_graph', (['graph', "(STANDARD_OUT_DIR + 'parent_handler_output')"], {}), "(graph, STANDARD_OUT_DIR + 'parent_handler_output')\n", (12006, 12057), False, 'import graph_analyzer\n'), ((12894, 12934), 'jsonparser.all_components', 'jsonparser.all_components', (['json_filename'], {}), '(json_filename)\n', (12919, 12934), False, 'import jsonparser\n'), ((15433, 15470), 'jsonparser.get_domains', 'jsonparser.get_domains', (['json_filename'], {}), '(json_filename)\n', (15455, 15470), False, 'import jsonparser\n'), ((15653, 15709), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'domain_list_new'], {}), '(graph, domain_list_new)\n', (15685, 15709), False, 'import graph_analyzer\n'), ((16900, 16944), 'jsonparser.get_context_groups', 'jsonparser.get_context_groups', (['json_filename'], {}), '(json_filename)\n', (16929, 16944), False, 'import jsonparser\n'), ((17155, 17218), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'context_group_list_new'], {}), '(graph, context_group_list_new)\n', (17187, 17218), False, 'import graph_analyzer\n'), ((18515, 18563), 'jsonparser.get_abstraction_layers', 'jsonparser.get_abstraction_layers', (['json_filename'], {}), '(json_filename)\n', (18548, 18563), False, 'import jsonparser\n'), ((18790, 18857), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'abstraction_layer_list_new'], {}), '(graph, abstraction_layer_list_new)\n', (18822, 18857), False, 'import graph_analyzer\n'), ((19814, 19851), 'jsonparser.get_domains', 'jsonparser.get_domains', (['json_filename'], {}), '(json_filename)\n', (19836, 19851), False, 'import jsonparser\n'), ((19877, 19921), 'jsonparser.get_context_groups', 'jsonparser.get_context_groups', (['json_filename'], {}), '(json_filename)\n', (19906, 19921), False, 'import jsonparser\n'), ((19951, 19999), 'jsonparser.get_abstraction_layers', 'jsonparser.get_abstraction_layers', (['json_filename'], {}), '(json_filename)\n', (19984, 19999), False, 'import jsonparser\n'), ((20558, 20614), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'domain_list_new'], {}), '(graph, domain_list_new)\n', (20590, 20614), False, 'import graph_analyzer\n'), ((20639, 20702), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'context_group_list_new'], {}), '(graph, context_group_list_new)\n', (20671, 20702), False, 'import graph_analyzer\n'), ((20731, 20798), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'abstraction_layer_list_new'], {}), '(graph, abstraction_layer_list_new)\n', (20763, 20798), False, 'import graph_analyzer\n'), ((30422, 30484), 'numpy.savetxt', 'np.savetxt', (['file_name', 'output_array'], {'delimiter': '""","""', 'fmt': '"""%.0f"""'}), "(file_name, output_array, delimiter=',', fmt='%.0f')\n", (30432, 30484), True, 'import numpy as np\n'), ((30999, 31537), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""A script to search a graph for all nodes mentioned in a json file (in our bmw-json format). Those nodes are then each combined into a parent node and the resulting graph is then outputted in another file. This has to be called from withing our src folder as it uses the jsonparser and graph_analyzer. Another service is the validation of parent nodes. This checks whether all children are somehow connected to each other. For testing you can also call this with test03.dot and test03.json."""'}), "(description=\n 'A script to search a graph for all nodes mentioned in a json file (in our bmw-json format). Those nodes are then each combined into a parent node and the resulting graph is then outputted in another file. This has to be called from withing our src folder as it uses the jsonparser and graph_analyzer. Another service is the validation of parent nodes. This checks whether all children are somehow connected to each other. For testing you can also call this with test03.dot and test03.json.'\n )\n", (31022, 31537), False, 'import argparse\n'), ((9816, 9866), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', 'name', 'childnodes'], {}), '(graph, name, childnodes)\n', (9841, 9866), False, 'import graph_analyzer\n'), ((10059, 10109), 'jsonparser.search_by_domain', 'jsonparser.search_by_domain', (['json_filename', 'domain'], {}), '(json_filename, domain)\n', (10086, 10109), False, 'import jsonparser\n'), ((10297, 10351), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'comp_list_new'], {}), '(graph, comp_list_new)\n', (10329, 10351), False, 'import graph_analyzer\n'), ((10368, 10413), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', 'domain', 'lis'], {}), '(graph, domain, lis)\n', (10393, 10413), False, 'import graph_analyzer\n'), ((10544, 10596), 'jsonparser.search_by_context', 'jsonparser.search_by_context', (['json_filename', 'context'], {}), '(json_filename, context)\n', (10572, 10596), False, 'import jsonparser\n'), ((10784, 10838), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'comp_list_new'], {}), '(graph, comp_list_new)\n', (10816, 10838), False, 'import graph_analyzer\n'), ((10855, 10901), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', 'context', 'lis'], {}), '(graph, context, lis)\n', (10880, 10901), False, 'import graph_analyzer\n'), ((11042, 11096), 'jsonparser.search_by_abstraction', 'jsonparser.search_by_abstraction', (['json_filename', 'layer'], {}), '(json_filename, layer)\n', (11074, 11096), False, 'import jsonparser\n'), ((11284, 11338), 'graph_analyzer.parse_node_values', 'graph_analyzer.parse_node_values', (['graph', 'comp_list_new'], {}), '(graph, comp_list_new)\n', (11316, 11338), False, 'import graph_analyzer\n'), ((11355, 11399), 'graph_analyzer.add_parent', 'graph_analyzer.add_parent', (['graph', 'layer', 'lis'], {}), '(graph, layer, lis)\n', (11380, 11399), False, 'import graph_analyzer\n'), ((32715, 32726), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (32723, 32726), False, 'import sys\n'), ((13343, 13392), 'graph_analyzer.search_vertices', 'graph_analyzer.search_vertices', (['graph', 's_parts[0]'], {}), '(graph, s_parts[0])\n', (13373, 13392), False, 'import graph_analyzer\n'), ((21690, 21744), 'graph_analyzer.collect_subgraph_vertices', 'graph_analyzer.collect_subgraph_vertices', (['graph', 'child'], {}), '(graph, child)\n', (21730, 21744), False, 'import graph_analyzer\n'), ((22175, 22229), 'graph_analyzer.collect_subgraph_vertices', 'graph_analyzer.collect_subgraph_vertices', (['graph', 'child'], {}), '(graph, child)\n', (22215, 22229), False, 'import graph_analyzer\n'), ((22694, 22748), 'graph_analyzer.collect_subgraph_vertices', 'graph_analyzer.collect_subgraph_vertices', (['graph', 'child'], {}), '(graph, child)\n', (22734, 22748), False, 'import graph_analyzer\n'), ((13667, 13710), 'graph_analyzer.search_vertices', 'graph_analyzer.search_vertices', (['graph', 'word'], {}), '(graph, word)\n', (13697, 13710), False, 'import graph_analyzer\n'), ((23831, 23921), 'graph_analyzer.list_shared_sub_vertices', 'graph_analyzer.list_shared_sub_vertices', (['graph', 'domain_list_ids[i]', 'domain_list_ids[j]'], {}), '(graph, domain_list_ids[i],\n domain_list_ids[j])\n', (23870, 23921), False, 'import graph_analyzer\n'), ((25904, 25998), 'graph_analyzer.list_shared_sub_vertices', 'graph_analyzer.list_shared_sub_vertices', (['graph', 'context_group_ids[i]', 'context_group_ids[j]'], {}), '(graph, context_group_ids[i],\n context_group_ids[j])\n', (25943, 25998), False, 'import graph_analyzer\n'), ((28093, 28195), 'graph_analyzer.list_shared_sub_vertices', 'graph_analyzer.list_shared_sub_vertices', (['graph', 'abstraction_layer_ids[i]', 'abstraction_layer_ids[j]'], {}), '(graph, abstraction_layer_ids[i],\n abstraction_layer_ids[j])\n', (28132, 28195), False, 'import graph_analyzer\n')]
import bpy import numpy as np X = np.loadtxt('/Users/papiit/Desktop/Reinforcement_Learning/Proyecto2/XYZ.txt') A = np.loadtxt('/Users/papiit/Desktop/Reinforcement_Learning/Proyecto2/ang.txt') posiciones, angulos = [],[] for i in range(len(X[0])): posiciones.append([X[0][i],X[1][1],X[2][i]]) angulos.append([A[0][i],A[1][1],A[2][i]]) ob = bpy.data.objects["drone"] frame_num = 0 for i in range(len(angulos)): bpy.context.scene.frame_set(frame_num) ob.location = posiciones[i] ob.rotation_euler = angulos[i] ob.keyframe_insert(data_path = "location",index = -1) ob.keyframe_insert("rotation_euler", frame= frame_num) frame_num += 1
[ "numpy.loadtxt", "bpy.context.scene.frame_set" ]
[((37, 113), 'numpy.loadtxt', 'np.loadtxt', (['"""/Users/papiit/Desktop/Reinforcement_Learning/Proyecto2/XYZ.txt"""'], {}), "('/Users/papiit/Desktop/Reinforcement_Learning/Proyecto2/XYZ.txt')\n", (47, 113), True, 'import numpy as np\n'), ((118, 194), 'numpy.loadtxt', 'np.loadtxt', (['"""/Users/papiit/Desktop/Reinforcement_Learning/Proyecto2/ang.txt"""'], {}), "('/Users/papiit/Desktop/Reinforcement_Learning/Proyecto2/ang.txt')\n", (128, 194), True, 'import numpy as np\n'), ((425, 463), 'bpy.context.scene.frame_set', 'bpy.context.scene.frame_set', (['frame_num'], {}), '(frame_num)\n', (452, 463), False, 'import bpy\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt import glob2 import PIL try: import Image except ImportError: from PIL import Image import cv2 from skimage import io, color from tensorflow import keras import tensorflow as tf tf.__version__ from keras.layers import * from tqdm import tqdm import ast import shutil def resize_image(image_path): al = plt.imread(image_path) #print('the initial shape is:',al.shape) if len(al.shape) == 2: al = cv2.merge((al,al,al)) elif al.shape[2] == 4: al = cv2.cvtColor(al, cv2.COLOR_BGRA2BGR) else: al = al w = al.shape[1] #store the width h = al.shape[0] #store the height c = al.shape[2] #store the number of channels(3 in this case) #print(c) # In case image is horizontally orientated if w > h: combine = np.zeros((w,w,c)) combino = combine for i in range(c): combino[int((w-h)/2):int(((w-h)/2)+h) ,: ,i] = al[:,:,i] resized = cv2.resize(combino, (480, 480), interpolation=cv2.INTER_NEAREST) # In case image is vertically orientated elif w < h: combine = np.zeros((h,h,c)) combino = combine for i in range(c): combino[: ,int((h-w)/2):int(((h-w)/2)+w) ,i] = al[:,:,i] resized = cv2.resize(combino, (480, 480), interpolation=cv2.INTER_NEAREST) # In case image is squared else: resized = cv2.resize(al, (480, 480), interpolation=cv2.INTER_NEAREST) al = resized #plt.imshow(al.astype(np.uint8)) # to Clip input data to the valid range for imshow with RGB data. #plt.show() #print('the final shape is:',al.shape) return al def resize_mask(ali): w = ali.shape[1] #store the width h = ali.shape[0] #store the height #c = al.shape[2] #store the number of channels(3 in this case) #print(c) al = ali.reshape((h,w)) #print('the initial shape is:',al.shape) # In case image is horizontally orientated if w > h: combine = np.zeros((w,w)) combine[int((w-h)/2):int(((w-h)/2)+h) ,:] = al[:,:] resized = cv2.resize(combine, (480, 480), interpolation=cv2.INTER_NEAREST) # In case image is vertically orientated elif w < h: combine = np.zeros((h,h)) combine[: ,int((h-w)/2):int(((h-w)/2)+w)] = al[:,:] resized = cv2.resize(combine, (480, 480), interpolation=cv2.INTER_NEAREST) # In case image is squared else: resized = cv2.resize(al, (480, 480), interpolation=cv2.INTER_NEAREST) #print('the final shape of resized is:',resized.shape) alou = np.reshape(resized, (480, 480, 1)) #plt.imshow(resized) # to Clip input data to the valid range for imshow with RGB data. #plt.show() #print('the final shape is:',alai.shape) return alou def resize_distancegeo(npy_path): al = npy_path #al = np.load(npy_path) #print('the initial shape is:',al.shape) w = al.shape[1] #store the width h = al.shape[0] #store the height c = al.shape[2] #store the number of channels(3 in this case) #print(c) # In case image is horizontally orientated if w > h: combine = np.zeros((w,w,c)) combino = combine for i in range(c): combino[int((w-h)/2):int(((w-h)/2)+h) ,: ,i] = al[:,:,i] resized = cv2.resize(combino, (480, 480), interpolation=cv2.INTER_NEAREST) # In case image is vertically orientated elif w < h: combine = np.zeros((h,h,c)) combino = combine for i in range(c): combino[: ,int((h-w)/2):int(((h-w)/2)+w) ,i] = al[:,:,i] resized = cv2.resize(combino, (480, 480), interpolation=cv2.INTER_NEAREST) # In case image is squared else: resized = cv2.resize(al, (480, 480), interpolation=cv2.INTER_NEAREST) al = resized #plt.imshow(al.astype(np.uint8)) # to Clip input data to the valid range for imshow with RGB data. #plt.show() #print('the final shape is:',al.shape) return al
[ "cv2.cvtColor", "numpy.zeros", "numpy.reshape", "cv2.merge", "matplotlib.pyplot.imread", "cv2.resize" ]
[((395, 417), 'matplotlib.pyplot.imread', 'plt.imread', (['image_path'], {}), '(image_path)\n', (405, 417), True, 'import matplotlib.pyplot as plt\n'), ((2510, 2544), 'numpy.reshape', 'np.reshape', (['resized', '(480, 480, 1)'], {}), '(resized, (480, 480, 1))\n', (2520, 2544), True, 'import numpy as np\n'), ((498, 521), 'cv2.merge', 'cv2.merge', (['(al, al, al)'], {}), '((al, al, al))\n', (507, 521), False, 'import cv2\n'), ((847, 866), 'numpy.zeros', 'np.zeros', (['(w, w, c)'], {}), '((w, w, c))\n', (855, 866), True, 'import numpy as np\n'), ((987, 1051), 'cv2.resize', 'cv2.resize', (['combino', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(combino, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (997, 1051), False, 'import cv2\n'), ((1955, 1971), 'numpy.zeros', 'np.zeros', (['(w, w)'], {}), '((w, w))\n', (1963, 1971), True, 'import numpy as np\n'), ((2041, 2105), 'cv2.resize', 'cv2.resize', (['combine', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(combine, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (2051, 2105), False, 'import cv2\n'), ((3059, 3078), 'numpy.zeros', 'np.zeros', (['(w, w, c)'], {}), '((w, w, c))\n', (3067, 3078), True, 'import numpy as np\n'), ((3199, 3263), 'cv2.resize', 'cv2.resize', (['combino', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(combino, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (3209, 3263), False, 'import cv2\n'), ((559, 595), 'cv2.cvtColor', 'cv2.cvtColor', (['al', 'cv2.COLOR_BGRA2BGR'], {}), '(al, cv2.COLOR_BGRA2BGR)\n', (571, 595), False, 'import cv2\n'), ((1124, 1143), 'numpy.zeros', 'np.zeros', (['(h, h, c)'], {}), '((h, h, c))\n', (1132, 1143), True, 'import numpy as np\n'), ((1264, 1328), 'cv2.resize', 'cv2.resize', (['combino', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(combino, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (1274, 1328), False, 'import cv2\n'), ((1381, 1440), 'cv2.resize', 'cv2.resize', (['al', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(al, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (1391, 1440), False, 'import cv2\n'), ((2178, 2194), 'numpy.zeros', 'np.zeros', (['(h, h)'], {}), '((h, h))\n', (2186, 2194), True, 'import numpy as np\n'), ((2264, 2328), 'cv2.resize', 'cv2.resize', (['combine', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(combine, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (2274, 2328), False, 'import cv2\n'), ((2381, 2440), 'cv2.resize', 'cv2.resize', (['al', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(al, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (2391, 2440), False, 'import cv2\n'), ((3336, 3355), 'numpy.zeros', 'np.zeros', (['(h, h, c)'], {}), '((h, h, c))\n', (3344, 3355), True, 'import numpy as np\n'), ((3476, 3540), 'cv2.resize', 'cv2.resize', (['combino', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(combino, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (3486, 3540), False, 'import cv2\n'), ((3593, 3652), 'cv2.resize', 'cv2.resize', (['al', '(480, 480)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(al, (480, 480), interpolation=cv2.INTER_NEAREST)\n', (3603, 3652), False, 'import cv2\n')]
import os import argparse import numpy as np import trimesh import pyrender import matplotlib.pyplot as plt import pddlgym from loader import load_scenegraph from pddlgym_planners.fd import FD from pddlgym_planners.planner import (PlanningFailure, PlanningTimeout) def plot_plan(domain_name, model): """Plot the plan returned by Fast-Downward in the specified domain / problem pair. """ # create PDDLGym Env env = pddlgym.make("PDDLEnv{}-v0".format(domain_name.capitalize())) domain_fname = env.domain.domain_fname problem_idx = None for i, problem in enumerate(env.problems): if model.lower() in problem.problem_name: problem_idx = i break assert (problem_idx is not None) problem_fname = env.problems[problem_idx].problem_fname env.fix_problem_index(problem_idx) state, _ = env.reset() planner = FD(alias_flag='--alias lama-first') # attempt to plan try: plan = planner.plan_to_action_from_pddl(env.domain, state, domain_fname, problem_fname, timeout=10) except PlanningTimeout as timeout: print(timeout) except PlanningFailure as failure: print(failure) class SceneGraphVisualizer: def __init__(self, datapath, meshpath): # data = np.load(datapath, allow_pickle=True) # self.data = data["output"].item() # self.scenegraph = load_scenegraph(datapath) self.mesh = trimesh.load(meshpath) self.scene = pyrender.Scene() def reset(self): self.scene = pyrender.Scene() def add_mesh(self, mesh=None, color=None): if mesh is None: mesh = self.mesh pymesh = pyrender.Mesh.from_trimesh(mesh) self.scene.add(pymesh) def render_topdown(self): # position camera at scene centroid pymesh = pyrender.Mesh.from_trimesh(self.mesh) ang = -np.pi / 2 cam_to_world = np.array([ [1.0, 0.0, 0.0, 0.0], [0.0, np.cos(ang), -np.sin(ang), 0.0], [0.0, np.sin(ang), np.cos(ang), 0.0], [0.0, 0.0, 0.0, 1.0] ], dtype=float) cam_to_world[:3, 3] = pymesh.centroid + np.array([0.0, 10.0, 0.0]) # add camera and directional light camera = pyrender.camera.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1.0) directlight = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=3.0) self.scene.add(camera, pose=cam_to_world) self.scene.add(directlight, pose=cam_to_world) pyrender.Viewer(self.scene) def render_offscreen(self): r = pyrender.OffscreenRenderer(400, 400) color, depth = r.render(self.scene) plt.figure() plt.axis('off') plt.imshow(color) plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--data-root', type=str, default="/home/agiachris/data/") parser.add_argument('--model', type=str, default='Allensville') args = parser.parse_args() # get scene graph and mesh path data_path = os.path.join(args.data_root, '3dscenegraph', 'tiny') model_type = "verified_graph" if os.path.basename(data_path) == 'tiny' else "automated_graph" datapath = os.path.join(data_path, model_type, "3DSceneGraph_" + args.model + ".npz") meshpath = os.path.join(args.data_root, 'gibson_tiny', args.model, 'mesh.obj') # plot_plan('taskographyv2tiny2', args.model) # exit() vis = SceneGraphVisualizer(datapath, meshpath) vis.add_mesh() vis.render_topdown() vis.render_offscreen()
[ "pyrender.camera.PerspectiveCamera", "trimesh.load", "matplotlib.pyplot.show", "argparse.ArgumentParser", "os.path.basename", "pyrender.DirectionalLight", "matplotlib.pyplot.imshow", "pyrender.Viewer", "pddlgym_planners.fd.FD", "matplotlib.pyplot.axis", "pyrender.Mesh.from_trimesh", "matplotlib.pyplot.figure", "numpy.array", "pyrender.OffscreenRenderer", "pyrender.Scene", "numpy.cos", "numpy.sin", "os.path.join" ]
[((882, 917), 'pddlgym_planners.fd.FD', 'FD', ([], {'alias_flag': '"""--alias lama-first"""'}), "(alias_flag='--alias lama-first')\n", (884, 917), False, 'from pddlgym_planners.fd import FD\n'), ((2821, 2846), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2844, 2846), False, 'import argparse\n'), ((3081, 3133), 'os.path.join', 'os.path.join', (['args.data_root', '"""3dscenegraph"""', '"""tiny"""'], {}), "(args.data_root, '3dscenegraph', 'tiny')\n", (3093, 3133), False, 'import os\n'), ((3247, 3321), 'os.path.join', 'os.path.join', (['data_path', 'model_type', "('3DSceneGraph_' + args.model + '.npz')"], {}), "(data_path, model_type, '3DSceneGraph_' + args.model + '.npz')\n", (3259, 3321), False, 'import os\n'), ((3337, 3404), 'os.path.join', 'os.path.join', (['args.data_root', '"""gibson_tiny"""', 'args.model', '"""mesh.obj"""'], {}), "(args.data_root, 'gibson_tiny', args.model, 'mesh.obj')\n", (3349, 3404), False, 'import os\n'), ((1438, 1460), 'trimesh.load', 'trimesh.load', (['meshpath'], {}), '(meshpath)\n', (1450, 1460), False, 'import trimesh\n'), ((1482, 1498), 'pyrender.Scene', 'pyrender.Scene', ([], {}), '()\n', (1496, 1498), False, 'import pyrender\n'), ((1546, 1562), 'pyrender.Scene', 'pyrender.Scene', ([], {}), '()\n', (1560, 1562), False, 'import pyrender\n'), ((1682, 1714), 'pyrender.Mesh.from_trimesh', 'pyrender.Mesh.from_trimesh', (['mesh'], {}), '(mesh)\n', (1708, 1714), False, 'import pyrender\n'), ((1838, 1875), 'pyrender.Mesh.from_trimesh', 'pyrender.Mesh.from_trimesh', (['self.mesh'], {}), '(self.mesh)\n', (1864, 1875), False, 'import pyrender\n'), ((2263, 2331), 'pyrender.camera.PerspectiveCamera', 'pyrender.camera.PerspectiveCamera', ([], {'yfov': '(np.pi / 3.0)', 'aspectRatio': '(1.0)'}), '(yfov=np.pi / 3.0, aspectRatio=1.0)\n', (2296, 2331), False, 'import pyrender\n'), ((2354, 2417), 'pyrender.DirectionalLight', 'pyrender.DirectionalLight', ([], {'color': '[1.0, 1.0, 1.0]', 'intensity': '(3.0)'}), '(color=[1.0, 1.0, 1.0], intensity=3.0)\n', (2379, 2417), False, 'import pyrender\n'), ((2531, 2558), 'pyrender.Viewer', 'pyrender.Viewer', (['self.scene'], {}), '(self.scene)\n', (2546, 2558), False, 'import pyrender\n'), ((2608, 2644), 'pyrender.OffscreenRenderer', 'pyrender.OffscreenRenderer', (['(400)', '(400)'], {}), '(400, 400)\n', (2634, 2644), False, 'import pyrender\n'), ((2697, 2709), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2707, 2709), True, 'import matplotlib.pyplot as plt\n'), ((2718, 2733), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2726, 2733), True, 'import matplotlib.pyplot as plt\n'), ((2742, 2759), 'matplotlib.pyplot.imshow', 'plt.imshow', (['color'], {}), '(color)\n', (2752, 2759), True, 'import matplotlib.pyplot as plt\n'), ((2768, 2778), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2776, 2778), True, 'import matplotlib.pyplot as plt\n'), ((2175, 2201), 'numpy.array', 'np.array', (['[0.0, 10.0, 0.0]'], {}), '([0.0, 10.0, 0.0])\n', (2183, 2201), True, 'import numpy as np\n'), ((3171, 3198), 'os.path.basename', 'os.path.basename', (['data_path'], {}), '(data_path)\n', (3187, 3198), False, 'import os\n'), ((1987, 1998), 'numpy.cos', 'np.cos', (['ang'], {}), '(ang)\n', (1993, 1998), True, 'import numpy as np\n'), ((2038, 2049), 'numpy.sin', 'np.sin', (['ang'], {}), '(ang)\n', (2044, 2049), True, 'import numpy as np\n'), ((2051, 2062), 'numpy.cos', 'np.cos', (['ang'], {}), '(ang)\n', (2057, 2062), True, 'import numpy as np\n'), ((2001, 2012), 'numpy.sin', 'np.sin', (['ang'], {}), '(ang)\n', (2007, 2012), True, 'import numpy as np\n')]
import numpy as np def maze_7x5(a=-1.0, b=-5.0, goal=15.0): nx, ny = 7, 5 S = np.zeros([nx, ny]) + a # blocks S[1,3] = b S[2,1:3] = b S[4,4:] = b S[4,:2] = b # S[1,4] = b S[6,3] = b # S[6,1] = goal return S def maze_13x13(a=-1.0, b=-5.0, goal=15.0): nx, ny = 13, 13 S = np.zeros([nx, ny]) - a S[1,4] = b S[2,2] = b S[4,4:8] = b S[4,:2] = b S[1:3,8] = b S[3,10:] = b S[7,8:12] = b S[6:12,2] = b # S[:1,4] = b S[5:8,4] = b S[7:,6] = b # S[12,11] = goal return S
[ "numpy.zeros" ]
[((90, 108), 'numpy.zeros', 'np.zeros', (['[nx, ny]'], {}), '([nx, ny])\n', (98, 108), True, 'import numpy as np\n'), ((343, 361), 'numpy.zeros', 'np.zeros', (['[nx, ny]'], {}), '([nx, ny])\n', (351, 361), True, 'import numpy as np\n')]
#!/home/xwu/bin/python #-*- coding:utf-8 -*- from sklearn.linear_model import LogisticRegression from sklearn.externals import joblib from sklearn.model_selection import train_test_split import numpy as np import os class Model(): def __init__(self,filename,suffix,assessment,filteration=None,coefs_file='coefs.txt',): self._filename=filename self._suffix=suffix self._assessment=assessment self._filteration=filteration self._coefs_file=coefs_file data=self.loadFeature() if data[0]=='train': self.Train(data) else: self.Test(data) def Train(self,data): del_model = LogisticRegression(C=100000.0, penalty='l2', tol=0.0001,solver='liblinear') dup_model = LogisticRegression(C=100000.0, penalty='l2', tol=0.0001,solver='liblinear') del_model.fit(data[1][0],data[1][1]) dup_model.fit(data[2][0],data[2][1]) print ('The training score of deletion group is',del_model.score(data[1][0],data[1][1])) print ('The training score of duplication group is',dup_model.score(data[2][0],data[2][1])) joblib.dump(del_model,'del_'+self._suffix) joblib.dump(dup_model,'dup_'+self._suffix) #coefs model_dict={'del_model':del_model,'dup_model':dup_model} f=open(self._coefs_file,'w') f.write('#\t'+'\t'.join(data[-1][0][7:])+'\tintercept\n') for m in ['del_model','dup_model']: f.write(m+'\t') #scale=abs(model_dict[m].intercept_) coefs=model_dict[m].coef_[0] intercept=model_dict[m].intercept_ for i in range(len(coefs)): f.write(str(coefs[i])+'\t') f.write(str(intercept)+'\n') f.close() #new data file del_dpp=np.array([del_model.decision_function(data[1][0]), np.max(del_model.predict_proba(data[1][0]),1), del_model.predict(data[1][0])]).T dup_dpp=np.array([dup_model.decision_function(data[2][0]), np.max(dup_model.predict_proba(data[2][0]),1), dup_model.predict(data[2][0])]).T dpp=np.vstack((del_dpp,dup_dpp)).astype(str) titled_dpp=np.vstack((np.array([['z-value','p-value','prediction']]),dpp)) assessment_data=np.hstack((data[-1],titled_dpp)) np.savetxt(self._assessment,assessment_data,fmt='%s',delimiter='\t') def Test(self,data): if os.path.exists('del_'+self._suffix) and os.path.exists('dup_'+self._suffix): del_model=joblib.load('del_'+self._suffix) dup_model=joblib.load('dup_'+self._suffix) #new data file del_dpp=np.array([del_model.decision_function(data[1]), np.max(del_model.predict_proba(data[1]),1), del_model.predict(data[1])]).T dup_dpp=np.array([dup_model.decision_function(data[2]), np.max(dup_model.predict_proba(data[2]),1), dup_model.predict(data[2])]).T dpp=np.vstack((del_dpp,dup_dpp)).astype(str) titled_dpp=np.vstack((np.array([['z-value','p-value','prediction']]),dpp)) assessment_data=np.hstack((data[-1],titled_dpp)) np.savetxt(self._assessment,assessment_data,fmt='%s',delimiter='\t') col_name=assessment_data[0] targets=assessment_data[1:] filteration_targets=np.array([l for l in targets if float(l[17])==1]) filteration_data=np.vstack((col_name,filteration_targets))[:,(0,1,2,3,4,16)] np.savetxt(self._filteration,filteration_data,fmt='%s',delimiter='\t') else: print ('model is missing!') def loadFeature(self): data=np.loadtxt(self._filename,skiprows=0,dtype=str,delimiter='\t',) col_name=data[0] targets=data[1:] del_group=np.array([l for l in targets if l[4]=='DEL']) dup_group=np.array([l for l in targets if l[4]=='DUP']) group=np.vstack((del_group,dup_group)) group=np.vstack((col_name,group)) if 'category' in col_name: del_y=del_group[:,6].astype(float) del_x=del_group[:,7:].astype(float) dup_y=dup_group[:,6].astype(float) dup_x=dup_group[:,7:].astype(float) return 'train',(del_x,del_y),(dup_x,dup_y),group else: del_x=del_group[:,5:].astype(float) dup_x=dup_group[:,5:].astype(float) return 'test',del_x,dup_x,group
[ "sklearn.externals.joblib.dump", "numpy.savetxt", "os.path.exists", "numpy.hstack", "sklearn.linear_model.LogisticRegression", "numpy.array", "numpy.loadtxt", "sklearn.externals.joblib.load", "numpy.vstack" ]
[((598, 674), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'C': '(100000.0)', 'penalty': '"""l2"""', 'tol': '(0.0001)', 'solver': '"""liblinear"""'}), "(C=100000.0, penalty='l2', tol=0.0001, solver='liblinear')\n", (616, 674), False, 'from sklearn.linear_model import LogisticRegression\n'), ((688, 764), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'C': '(100000.0)', 'penalty': '"""l2"""', 'tol': '(0.0001)', 'solver': '"""liblinear"""'}), "(C=100000.0, penalty='l2', tol=0.0001, solver='liblinear')\n", (706, 764), False, 'from sklearn.linear_model import LogisticRegression\n'), ((1029, 1074), 'sklearn.externals.joblib.dump', 'joblib.dump', (['del_model', "('del_' + self._suffix)"], {}), "(del_model, 'del_' + self._suffix)\n", (1040, 1074), False, 'from sklearn.externals import joblib\n'), ((1074, 1119), 'sklearn.externals.joblib.dump', 'joblib.dump', (['dup_model', "('dup_' + self._suffix)"], {}), "(dup_model, 'dup_' + self._suffix)\n", (1085, 1119), False, 'from sklearn.externals import joblib\n'), ((2009, 2042), 'numpy.hstack', 'np.hstack', (['(data[-1], titled_dpp)'], {}), '((data[-1], titled_dpp))\n', (2018, 2042), True, 'import numpy as np\n'), ((2044, 2115), 'numpy.savetxt', 'np.savetxt', (['self._assessment', 'assessment_data'], {'fmt': '"""%s"""', 'delimiter': '"""\t"""'}), "(self._assessment, assessment_data, fmt='%s', delimiter='\\t')\n", (2054, 2115), True, 'import numpy as np\n'), ((3234, 3299), 'numpy.loadtxt', 'np.loadtxt', (['self._filename'], {'skiprows': '(0)', 'dtype': 'str', 'delimiter': '"""\t"""'}), "(self._filename, skiprows=0, dtype=str, delimiter='\\t')\n", (3244, 3299), True, 'import numpy as np\n'), ((3348, 3395), 'numpy.array', 'np.array', (["[l for l in targets if l[4] == 'DEL']"], {}), "([l for l in targets if l[4] == 'DEL'])\n", (3356, 3395), True, 'import numpy as np\n'), ((3406, 3453), 'numpy.array', 'np.array', (["[l for l in targets if l[4] == 'DUP']"], {}), "([l for l in targets if l[4] == 'DUP'])\n", (3414, 3453), True, 'import numpy as np\n'), ((3460, 3493), 'numpy.vstack', 'np.vstack', (['(del_group, dup_group)'], {}), '((del_group, dup_group))\n', (3469, 3493), True, 'import numpy as np\n'), ((3501, 3529), 'numpy.vstack', 'np.vstack', (['(col_name, group)'], {}), '((col_name, group))\n', (3510, 3529), True, 'import numpy as np\n'), ((2144, 2181), 'os.path.exists', 'os.path.exists', (["('del_' + self._suffix)"], {}), "('del_' + self._suffix)\n", (2158, 2181), False, 'import os\n'), ((2184, 2221), 'os.path.exists', 'os.path.exists', (["('dup_' + self._suffix)"], {}), "('dup_' + self._suffix)\n", (2198, 2221), False, 'import os\n'), ((2234, 2268), 'sklearn.externals.joblib.load', 'joblib.load', (["('del_' + self._suffix)"], {}), "('del_' + self._suffix)\n", (2245, 2268), False, 'from sklearn.externals import joblib\n'), ((2280, 2314), 'sklearn.externals.joblib.load', 'joblib.load', (["('dup_' + self._suffix)"], {}), "('dup_' + self._suffix)\n", (2291, 2314), False, 'from sklearn.externals import joblib\n'), ((2764, 2797), 'numpy.hstack', 'np.hstack', (['(data[-1], titled_dpp)'], {}), '((data[-1], titled_dpp))\n', (2773, 2797), True, 'import numpy as np\n'), ((2800, 2871), 'numpy.savetxt', 'np.savetxt', (['self._assessment', 'assessment_data'], {'fmt': '"""%s"""', 'delimiter': '"""\t"""'}), "(self._assessment, assessment_data, fmt='%s', delimiter='\\t')\n", (2810, 2871), True, 'import numpy as np\n'), ((3091, 3164), 'numpy.savetxt', 'np.savetxt', (['self._filteration', 'filteration_data'], {'fmt': '"""%s"""', 'delimiter': '"""\t"""'}), "(self._filteration, filteration_data, fmt='%s', delimiter='\\t')\n", (3101, 3164), True, 'import numpy as np\n'), ((1873, 1902), 'numpy.vstack', 'np.vstack', (['(del_dpp, dup_dpp)'], {}), '((del_dpp, dup_dpp))\n', (1882, 1902), True, 'import numpy as np\n'), ((1938, 1986), 'numpy.array', 'np.array', (["[['z-value', 'p-value', 'prediction']]"], {}), "([['z-value', 'p-value', 'prediction']])\n", (1946, 1986), True, 'import numpy as np\n'), ((3028, 3070), 'numpy.vstack', 'np.vstack', (['(col_name, filteration_targets)'], {}), '((col_name, filteration_targets))\n', (3037, 3070), True, 'import numpy as np\n'), ((2626, 2655), 'numpy.vstack', 'np.vstack', (['(del_dpp, dup_dpp)'], {}), '((del_dpp, dup_dpp))\n', (2635, 2655), True, 'import numpy as np\n'), ((2692, 2740), 'numpy.array', 'np.array', (["[['z-value', 'p-value', 'prediction']]"], {}), "([['z-value', 'p-value', 'prediction']])\n", (2700, 2740), True, 'import numpy as np\n')]
#!/bin/sh /cvmfs/icecube.opensciencegrid.org/py2-v1/icetray-start #METAPROJECT /data/user/jbourbeau/metaprojects/icerec/V05-00-00/build import numpy as np import pandas as pd import time import glob import argparse import os from collections import defaultdict from icecube.weighting.weighting import from_simprod from icecube.weighting.fluxes import GaisserH3a, GaisserH4a import composition as comp if __name__ == "__main__": # Setup global path names mypaths = comp.Paths() comp.checkdir(mypaths.comp_data_dir) p = argparse.ArgumentParser( description='Runs extra modules over a given fileList') p.add_argument('-o', '--outfile', dest='outfile', help='Output file') args = p.parse_args() dataframe_dict = defaultdict(list) # Get simulation information t_sim = time.time() print('Loading simulation information...') file_list = sorted(glob.glob(mypaths.comp_data_dir + '/IT73_sim/files/sim_????.hdf5')) value_keys = ['IceTopMaxSignal', 'IceTopMaxSignalInEdge', 'IceTopMaxSignalString', 'IceTopNeighbourMaxSignal', 'InIce_charge_1_60', 'NChannels_1_60', 'max_qfrac_1_60', 'InIce_charge_1_45', 'NChannels_1_45', 'max_qfrac_1_45', 'InIce_charge_1_30', 'NChannels_1_30', 'max_qfrac_1_30', 'InIce_charge_1_15', 'NChannels_1_15', 'max_qfrac_1_15', 'InIce_charge_1_6', 'NChannels_1_6', 'max_qfrac_1_6', 'NStations', 'StationDensity', 'IceTop_FractionContainment', 'InIce_FractionContainment', 'Laputop_IceTop_FractionContainment', 'Laputop_InIce_FractionContainment'] for f in file_list: print('\tWorking on {}'.format(f)) sim_dict = {} store = pd.HDFStore(f) for key in value_keys: sim_dict[key] = store.select(key).value # Get MCPrimary information for key in ['x', 'y', 'energy', 'zenith', 'azimuth', 'type']: sim_dict['MC_{}'.format(key)] = store.select('MCPrimary')[key] # Add simulation set number and corresponding composition sim_num = os.path.splitext(f)[0].split('_')[-1] sim_dict['sim'] = np.array([sim_num] * len(store.select('MCPrimary'))) sim_dict['MC_comp'] = np.array( [comp.simfunctions.sim2comp(sim_num)] * len(store.select('MCPrimary'))) # Get Laputop data sim_dict['lap_fitstatus_ok'] = store.select('Laputop_fitstatus_ok').value.astype(bool) Laputop_particle = store.select('Laputop') sim_dict['lap_s125'] = store.select('LaputopParams')['s125'] sim_dict['lap_chi2'] = store.select('LaputopParams')[ 'chi2'] / store.select('LaputopParams')['ndf'] sim_dict['lap_beta'] = store.select('LaputopParams')['beta'] sim_dict['lap_x'] = store.select('Laputop')['x'] sim_dict['lap_y'] = store.select('Laputop')['y'] sim_dict['lap_zenith'] = store.select('Laputop')['zenith'] sim_dict['lap_energy'] = store.select('LaputopParams')['e_h4a'] sim_dict['lap_likelihood'] = store.select('LaputopParams')['rlogl'] # sim_dict['lap_ang_res'] = store.select('LaputopParams')['angular_resolution'] store.close() for key in sim_dict.keys(): dataframe_dict[key] += sim_dict[key].tolist() # # Calculate simulation event weights # print('\nCalculating simulation event weights...\n') # simlist = np.unique(dataframe_dict['sim']) # num_files_dict = {'7006': 30000, '7007': 30000, # '7579': 12000, '7784': 12000} # for i, sim in enumerate(simlist): # if i == 0: # generator = num_files_dict[sim] * from_simprod(int(sim)) # else: # generator += num_files_dict[sim] * from_simprod(int(sim)) # flux = GaisserH3a() # dataframe_dict['weights_H3a'] = flux(dataframe_dict['MC_energy'], dataframe_dict[ # 'MC_type']) / generator(dataframe_dict['MC_energy'], dataframe_dict['MC_type']) # flux = GaisserH4a() # dataframe_dict['weights_H4a'] = flux(dataframe_dict['MC_energy'], dataframe_dict['MC_type']) / \ # generator(dataframe_dict['MC_energy'], dataframe_dict['MC_type']) # dataframe_dict['areas'] = 1.0 / generator(dataframe_dict['MC_energy'], dataframe_dict['MC_type']) print('Time taken: {}'.format(time.time() - t_sim)) print('Time per file: {}\n'.format((time.time() - t_sim) / 4)) # Get ShowerLLH reconstruction information t_LLH = time.time() print('Loading ShowerLLH reconstructions...') file_list = sorted(glob.glob(mypaths.llh_dir + '/IT73_sim/files/SimLLH_????_logdist.hdf5')) for f in file_list: print('\tWorking on {}'.format(f)) LLH_dict = {} store = pd.HDFStore(f) # Get most-likely composition LLH_particle = store.select('ShowerLLH') LLH_dict['reco_exists'] = LLH_particle.exists.astype(bool) # Get ML energy LLH_dict['reco_energy'] = LLH_particle.energy # Get ML core position LLH_dict['reco_x'] = LLH_particle.x LLH_dict['reco_y'] = LLH_particle.y # Get ML core radius LLH_dict['reco_radius'] = np.sqrt( LLH_dict['reco_x']**2 + LLH_dict['reco_y']**2) # Get ML zenith LLH_dict['reco_zenith'] = LLH_particle.zenith # Get ShowerLLH containment information LLH_dict['reco_IT_containment'] = store.select( 'ShowerLLH_IceTop_containment').value LLH_dict['reco_InIce_containment'] = store.select( 'ShowerLLH_InIce_containment').value # Get ShowerLLH+lap hybrid containment information LLHLF_particle = store.select('LLHLF_particle') LLH_dict['LLHLF_zenith'] = LLHLF_particle.zenith LLH_dict['LLHLF_IT_containment'] = store.select( 'LLHLF_IceTop_containment').value LLH_dict['LLHLF_InIce_containment'] = store.select( 'LLHLF_InIce_containment').value LLH_dict['LLHLF_reco_exists'] = LLHLF_particle.exists.astype(bool) # Get ShowerLLH+lap hybrid containment information LLHlap_particle = store.select('LLHlap_particle') LLH_dict['LLHlap_zenith'] = LLHlap_particle.zenith LLH_dict['LLHlap_IT_containment'] = store.select( 'LLHlap_IceTop_containment').value LLH_dict['LLHlap_InIce_containment'] = store.select( 'LLHlap_InIce_containment').value LLH_dict['LLHlap_reco_exists'] = LLHlap_particle.exists.astype(bool) store.close() for key in LLH_dict.keys(): dataframe_dict[key] += LLH_dict[key].tolist() print('Time taken: {}'.format(time.time() - t_LLH)) print('Time per file: {}'.format((time.time() - t_LLH) / 4)) # Convert value lists to arrays (faster than using np.append?) for key in dataframe_dict.keys(): dataframe_dict[key] = np.asarray(dataframe_dict[key]) df = pd.DataFrame.from_dict(dataframe_dict) df.to_hdf('{}/IT73_sim/sim_dataframe.hdf5'.format(mypaths.comp_data_dir), 'dataframe', mode='w')
[ "composition.checkdir", "argparse.ArgumentParser", "pandas.DataFrame.from_dict", "pandas.HDFStore", "numpy.asarray", "time.time", "collections.defaultdict", "composition.Paths", "composition.simfunctions.sim2comp", "os.path.splitext", "glob.glob", "numpy.sqrt" ]
[((477, 489), 'composition.Paths', 'comp.Paths', ([], {}), '()\n', (487, 489), True, 'import composition as comp\n'), ((494, 530), 'composition.checkdir', 'comp.checkdir', (['mypaths.comp_data_dir'], {}), '(mypaths.comp_data_dir)\n', (507, 530), True, 'import composition as comp\n'), ((540, 619), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Runs extra modules over a given fileList"""'}), "(description='Runs extra modules over a given fileList')\n", (563, 619), False, 'import argparse\n'), ((770, 787), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (781, 787), False, 'from collections import defaultdict\n'), ((834, 845), 'time.time', 'time.time', ([], {}), '()\n', (843, 845), False, 'import time\n'), ((4701, 4712), 'time.time', 'time.time', ([], {}), '()\n', (4710, 4712), False, 'import time\n'), ((7300, 7338), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['dataframe_dict'], {}), '(dataframe_dict)\n', (7322, 7338), True, 'import pandas as pd\n'), ((916, 982), 'glob.glob', 'glob.glob', (["(mypaths.comp_data_dir + '/IT73_sim/files/sim_????.hdf5')"], {}), "(mypaths.comp_data_dir + '/IT73_sim/files/sim_????.hdf5')\n", (925, 982), False, 'import glob\n'), ((1936, 1950), 'pandas.HDFStore', 'pd.HDFStore', (['f'], {}), '(f)\n', (1947, 1950), True, 'import pandas as pd\n'), ((4786, 4857), 'glob.glob', 'glob.glob', (["(mypaths.llh_dir + '/IT73_sim/files/SimLLH_????_logdist.hdf5')"], {}), "(mypaths.llh_dir + '/IT73_sim/files/SimLLH_????_logdist.hdf5')\n", (4795, 4857), False, 'import glob\n'), ((4997, 5011), 'pandas.HDFStore', 'pd.HDFStore', (['f'], {}), '(f)\n', (5008, 5011), True, 'import pandas as pd\n'), ((5426, 5484), 'numpy.sqrt', 'np.sqrt', (["(LLH_dict['reco_x'] ** 2 + LLH_dict['reco_y'] ** 2)"], {}), "(LLH_dict['reco_x'] ** 2 + LLH_dict['reco_y'] ** 2)\n", (5433, 5484), True, 'import numpy as np\n'), ((7258, 7289), 'numpy.asarray', 'np.asarray', (['dataframe_dict[key]'], {}), '(dataframe_dict[key])\n', (7268, 7289), True, 'import numpy as np\n'), ((4552, 4563), 'time.time', 'time.time', ([], {}), '()\n', (4561, 4563), False, 'import time\n'), ((7035, 7046), 'time.time', 'time.time', ([], {}), '()\n', (7044, 7046), False, 'import time\n'), ((2469, 2504), 'composition.simfunctions.sim2comp', 'comp.simfunctions.sim2comp', (['sim_num'], {}), '(sim_num)\n', (2495, 2504), True, 'import composition as comp\n'), ((4614, 4625), 'time.time', 'time.time', ([], {}), '()\n', (4623, 4625), False, 'import time\n'), ((7095, 7106), 'time.time', 'time.time', ([], {}), '()\n', (7104, 7106), False, 'import time\n'), ((2299, 2318), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (2315, 2318), False, 'import os\n')]
import unittest import numpy as np import math import rotate3d class TestRotate3dMisc(unittest.TestCase): """A basic test suite for rotate3d helper functions""" def test_normalize_x(self): (x,y,z) = rotate3d.normalize(5,0,0) np.testing.assert_almost_equal(x, 1) np.testing.assert_almost_equal(y, 0) np.testing.assert_almost_equal(z, 0) def test_normalize_y(self): (x,y,z) = rotate3d.normalize(0,10,0) np.testing.assert_almost_equal(x, 0) np.testing.assert_almost_equal(y, 1) np.testing.assert_almost_equal(z, 0) def test_normalize_x(self): (x,y,z) = rotate3d.normalize(0,0,20) np.testing.assert_almost_equal(x, 0) np.testing.assert_almost_equal(y, 0) np.testing.assert_almost_equal(z, 1) def test_normalize_xy(self): (x,y,z) = rotate3d.normalize(5,5,0) np.testing.assert_almost_equal(x, 1/math.sqrt(2)) np.testing.assert_almost_equal(y, 1/math.sqrt(2)) np.testing.assert_almost_equal(z, 0) def test_rotation_matrix_x(self): matrix1 = rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(90)) matrix2 = np.array([[1,0,0],[0,0,-1],[0,1,0]]) np.testing.assert_array_almost_equal(matrix1,matrix2) def test_rotation_matrix_y(self): matrix1 = rotate3d.axis_angle_to_rotation_matrix(0,1,0,math.radians(90)) matrix2 = np.array([[0,0,1],[0,1,0],[-1,0,0]]) np.testing.assert_array_almost_equal(matrix1,matrix2) class TestRotate3dObject3d(unittest.TestCase): """A basic test suite for rotate3d.Object3d""" def setUp(self): v = [[1,1,-1],[1,-1,-1],[-1,-1,-1],[-1,1,-1],[0,0,1]] vn = [] f = [[1,2,5],[2,3,5],[3,4,5],[4,1,5]] self.obj1 = rotate3d.Object3d('test_object_1', np.array(v), np.array(vn), np.array(f)) self.obj2 = rotate3d.Object3d('test_object_2', np.array(v), np.array(vn), np.array(f)) def test_object_init(self): v = [[1,1,-1],[1,-1,-1],[-1,-1,-1],[-1,1,-1],[0,0,1]] vn = [] f = [[1,2,5],[2,3,5],[3,4,5],[4,1,5]] np.testing.assert_array_equal(self.obj1.v, v) np.testing.assert_array_equal(self.obj1.vn, vn) np.testing.assert_array_equal(self.obj1.f, f) def test_value_equivalence(self): np.testing.assert_array_equal(self.obj1.v, self.obj2.v) np.testing.assert_array_equal(self.obj1.vn, self.obj2.vn) np.testing.assert_array_equal(self.obj1.f, self.obj2.f) def test_rotate_and_reverse_x(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(90)), False) self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(-90)), False) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_rotate_and_reverse_y(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,1,0,math.radians(90)), False) self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,1,0,math.radians(-90)), False) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_rotate_and_reverse_z(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(90)), False) self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(-90)), False) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_cw_90_equals_ccw_270_x(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(90)), False) self.obj2.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0, math.radians(-270)), False) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_cw_90_equals_ccw_270_y(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,1,0,math.radians(90)), False) self.obj2.rotate(rotate3d.axis_angle_to_rotation_matrix(0,1,0, math.radians(-270)), False) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_cw_90_equals_ccw_270_z(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(90)), False) self.obj2.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1, math.radians(-270)), False) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_colinear_axis(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(90)), False) self.obj2.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(90)), True) np.testing.assert_array_equal(self.obj1.v, self.obj2.v) def test_noncolinear_axis(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(90)), True) self.obj2.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(90)), False) self.assertRaises(AssertionError, np.testing.assert_array_almost_equal, self.obj1.v, self.obj2.v) def test_rotation_does_not_affect_faces(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(90)), False) np.testing.assert_array_equal(self.obj1.f, self.obj2.f) def test_axis_rotations_x_y_negative_x_equals_z(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(90)), True) self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,1,0,math.radians(90)), True) self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(-90)), True) self.obj2.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(90)), True) np.testing.assert_array_almost_equal(self.obj1.v, self.obj2.v) def test_45_degree_math_check_x(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(1,0,0,math.radians(45)), True) v = np.array([[1,0,-math.sqrt(2)],[1,-math.sqrt(2),0],[-1,-math.sqrt(2),0],[-1,0,-math.sqrt(2)],[0,1/math.sqrt(2),1/math.sqrt(2)]]) np.testing.assert_array_almost_equal(self.obj1.v, v) def test_45_degree_math_check_y(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,1,0,math.radians(45)), True) v = np.array([[math.sqrt(2),1,0],[math.sqrt(2),-1,0],[0,-1,-math.sqrt(2)],[0,1,-math.sqrt(2)],[-1/math.sqrt(2),0,1/math.sqrt(2)]]) np.testing.assert_array_almost_equal(self.obj1.v, v) def test_45_degree_math_check_z(self): self.obj1.rotate(rotate3d.axis_angle_to_rotation_matrix(0,0,1,math.radians(45)), True) v = np.array([[math.sqrt(2),0,-1],[0,-math.sqrt(2),-1],[-math.sqrt(2),0,-1],[0,math.sqrt(2),-1],[0,0,1]]) np.testing.assert_array_almost_equal(self.obj1.v, v) if __name__ == '__main__': unittest.main()
[ "unittest.main", "math.sqrt", "math.radians", "numpy.testing.assert_almost_equal", "numpy.testing.assert_array_equal", "numpy.array", "numpy.testing.assert_array_almost_equal", "rotate3d.normalize" ]
[((6202, 6217), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6215, 6217), False, 'import unittest\n'), ((206, 233), 'rotate3d.normalize', 'rotate3d.normalize', (['(5)', '(0)', '(0)'], {}), '(5, 0, 0)\n', (224, 233), False, 'import rotate3d\n'), ((234, 270), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['x', '(1)'], {}), '(x, 1)\n', (264, 270), True, 'import numpy as np\n'), ((273, 309), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['y', '(0)'], {}), '(y, 0)\n', (303, 309), True, 'import numpy as np\n'), ((312, 348), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['z', '(0)'], {}), '(z, 0)\n', (342, 348), True, 'import numpy as np\n'), ((391, 419), 'rotate3d.normalize', 'rotate3d.normalize', (['(0)', '(10)', '(0)'], {}), '(0, 10, 0)\n', (409, 419), False, 'import rotate3d\n'), ((420, 456), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['x', '(0)'], {}), '(x, 0)\n', (450, 456), True, 'import numpy as np\n'), ((459, 495), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['y', '(1)'], {}), '(y, 1)\n', (489, 495), True, 'import numpy as np\n'), ((498, 534), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['z', '(0)'], {}), '(z, 0)\n', (528, 534), True, 'import numpy as np\n'), ((577, 605), 'rotate3d.normalize', 'rotate3d.normalize', (['(0)', '(0)', '(20)'], {}), '(0, 0, 20)\n', (595, 605), False, 'import rotate3d\n'), ((606, 642), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['x', '(0)'], {}), '(x, 0)\n', (636, 642), True, 'import numpy as np\n'), ((645, 681), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['y', '(0)'], {}), '(y, 0)\n', (675, 681), True, 'import numpy as np\n'), ((684, 720), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['z', '(1)'], {}), '(z, 1)\n', (714, 720), True, 'import numpy as np\n'), ((764, 791), 'rotate3d.normalize', 'rotate3d.normalize', (['(5)', '(5)', '(0)'], {}), '(5, 5, 0)\n', (782, 791), False, 'import rotate3d\n'), ((896, 932), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['z', '(0)'], {}), '(z, 0)\n', (926, 932), True, 'import numpy as np\n'), ((1056, 1100), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, 0, -1], [0, 1, 0]]'], {}), '([[1, 0, 0], [0, 0, -1], [0, 1, 0]])\n', (1064, 1100), True, 'import numpy as np\n'), ((1095, 1149), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['matrix1', 'matrix2'], {}), '(matrix1, matrix2)\n', (1131, 1149), True, 'import numpy as np\n'), ((1272, 1316), 'numpy.array', 'np.array', (['[[0, 0, 1], [0, 1, 0], [-1, 0, 0]]'], {}), '([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])\n', (1280, 1316), True, 'import numpy as np\n'), ((1311, 1365), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['matrix1', 'matrix2'], {}), '(matrix1, matrix2)\n', (1347, 1365), True, 'import numpy as np\n'), ((1905, 1950), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.v', 'v'], {}), '(self.obj1.v, v)\n', (1934, 1950), True, 'import numpy as np\n'), ((1953, 2000), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.vn', 'vn'], {}), '(self.obj1.vn, vn)\n', (1982, 2000), True, 'import numpy as np\n'), ((2003, 2048), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.f', 'f'], {}), '(self.obj1.f, f)\n', (2032, 2048), True, 'import numpy as np\n'), ((2087, 2142), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (2116, 2142), True, 'import numpy as np\n'), ((2145, 2202), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.vn', 'self.obj2.vn'], {}), '(self.obj1.vn, self.obj2.vn)\n', (2174, 2202), True, 'import numpy as np\n'), ((2205, 2260), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.f', 'self.obj2.f'], {}), '(self.obj1.f, self.obj2.f)\n', (2234, 2260), True, 'import numpy as np\n'), ((2483, 2545), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (2519, 2545), True, 'import numpy as np\n'), ((2768, 2830), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (2804, 2830), True, 'import numpy as np\n'), ((3053, 3115), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (3089, 3115), True, 'import numpy as np\n'), ((3342, 3404), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (3378, 3404), True, 'import numpy as np\n'), ((3631, 3693), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (3667, 3693), True, 'import numpy as np\n'), ((3920, 3982), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (3956, 3982), True, 'import numpy as np\n'), ((4196, 4251), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (4225, 4251), True, 'import numpy as np\n'), ((4707, 4762), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['self.obj1.f', 'self.obj2.f'], {}), '(self.obj1.f, self.obj2.f)\n', (4736, 4762), True, 'import numpy as np\n'), ((5179, 5241), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'self.obj2.v'], {}), '(self.obj1.v, self.obj2.v)\n', (5215, 5241), True, 'import numpy as np\n'), ((5508, 5560), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'v'], {}), '(self.obj1.v, v)\n', (5544, 5560), True, 'import numpy as np\n'), ((5826, 5878), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'v'], {}), '(self.obj1.v, v)\n', (5862, 5878), True, 'import numpy as np\n'), ((6119, 6171), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['self.obj1.v', 'v'], {}), '(self.obj1.v, v)\n', (6155, 6171), True, 'import numpy as np\n'), ((1026, 1042), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (1038, 1042), False, 'import math\n'), ((1242, 1258), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (1254, 1258), False, 'import math\n'), ((1636, 1647), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (1644, 1647), True, 'import numpy as np\n'), ((1649, 1661), 'numpy.array', 'np.array', (['vn'], {}), '(vn)\n', (1657, 1661), True, 'import numpy as np\n'), ((1663, 1674), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (1671, 1674), True, 'import numpy as np\n'), ((1725, 1736), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (1733, 1736), True, 'import numpy as np\n'), ((1738, 1750), 'numpy.array', 'np.array', (['vn'], {}), '(vn)\n', (1746, 1750), True, 'import numpy as np\n'), ((1752, 1763), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (1760, 1763), True, 'import numpy as np\n'), ((828, 840), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (837, 840), False, 'import math\n'), ((880, 892), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (889, 892), False, 'import math\n'), ((2364, 2380), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (2376, 2380), False, 'import math\n'), ((2454, 2471), 'math.radians', 'math.radians', (['(-90)'], {}), '(-90)\n', (2466, 2471), False, 'import math\n'), ((2649, 2665), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (2661, 2665), False, 'import math\n'), ((2739, 2756), 'math.radians', 'math.radians', (['(-90)'], {}), '(-90)\n', (2751, 2756), False, 'import math\n'), ((2934, 2950), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (2946, 2950), False, 'import math\n'), ((3024, 3041), 'math.radians', 'math.radians', (['(-90)'], {}), '(-90)\n', (3036, 3041), False, 'import math\n'), ((3221, 3237), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (3233, 3237), False, 'import math\n'), ((3312, 3330), 'math.radians', 'math.radians', (['(-270)'], {}), '(-270)\n', (3324, 3330), False, 'import math\n'), ((3510, 3526), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (3522, 3526), False, 'import math\n'), ((3601, 3619), 'math.radians', 'math.radians', (['(-270)'], {}), '(-270)\n', (3613, 3619), False, 'import math\n'), ((3799, 3815), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (3811, 3815), False, 'import math\n'), ((3890, 3908), 'math.radians', 'math.radians', (['(-270)'], {}), '(-270)\n', (3902, 3908), False, 'import math\n'), ((4079, 4095), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4091, 4095), False, 'import math\n'), ((4169, 4185), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4181, 4185), False, 'import math\n'), ((4351, 4367), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4363, 4367), False, 'import math\n'), ((4440, 4456), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4452, 4456), False, 'import math\n'), ((4679, 4695), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4691, 4695), False, 'import math\n'), ((4884, 4900), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4896, 4900), False, 'import math\n'), ((4973, 4989), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (4985, 4989), False, 'import math\n'), ((5062, 5079), 'math.radians', 'math.radians', (['(-90)'], {}), '(-90)\n', (5074, 5079), False, 'import math\n'), ((5152, 5168), 'math.radians', 'math.radians', (['(90)'], {}), '(90)\n', (5164, 5168), False, 'import math\n'), ((5347, 5363), 'math.radians', 'math.radians', (['(45)'], {}), '(45)\n', (5359, 5363), False, 'import math\n'), ((5666, 5682), 'math.radians', 'math.radians', (['(45)'], {}), '(45)\n', (5678, 5682), False, 'import math\n'), ((5984, 6000), 'math.radians', 'math.radians', (['(45)'], {}), '(45)\n', (5996, 6000), False, 'import math\n'), ((5708, 5720), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5717, 5720), False, 'import math\n'), ((5727, 5739), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5736, 5739), False, 'import math\n'), ((6026, 6038), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (6035, 6038), False, 'import math\n'), ((6090, 6102), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (6099, 6102), False, 'import math\n'), ((5394, 5406), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5403, 5406), False, 'import math\n'), ((5412, 5424), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5421, 5424), False, 'import math\n'), ((5433, 5445), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5442, 5445), False, 'import math\n'), ((5456, 5468), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5465, 5468), False, 'import math\n'), ((5475, 5487), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5484, 5487), False, 'import math\n'), ((5490, 5502), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5499, 5502), False, 'import math\n'), ((5753, 5765), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5762, 5765), False, 'import math\n'), ((5773, 5785), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5782, 5785), False, 'import math\n'), ((5791, 5803), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5800, 5803), False, 'import math\n'), ((5808, 5820), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (5817, 5820), False, 'import math\n'), ((6049, 6061), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (6058, 6061), False, 'import math\n'), ((6068, 6080), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (6077, 6080), False, 'import math\n')]
from . import params from . import defineCnst as C import numpy as np import torch as tr def placeCars(envCars, traffic_density): # do this for all the cars # index starts from 1 as ego car is car_0 if len(envCars) > 15: MAX_DIST = params.SIM_MAX_DISTANCE*2 else: MAX_DIST = params.SIM_MAX_DISTANCE # params.SIM_MAX_DISTANCE = 240 MAX_DIST = MAX_DIST * traffic_density SAFE_DISTANCE = params.CAR_SAFE_DISTANCE * traffic_density for i in range(1, len(envCars)): laneOverlap = True while laneOverlap: xPos = MAX_DIST * (np.random.random() - 0.5) # place cars between -0.5*maxSimDist to +0.5*maxSimDist # random number of cars per lane 3 lanes shifted by 2 due to lane marking laneNum = np.random.randint(3)*params.ROAD_CENTER_LANE laneOverlap = False for j in range(0, i): # only 0 to i cars have been placed already. 0-->ego car if (laneNum == envCars[j].laneNum) and (abs(xPos-envCars[j].xPos) < SAFE_DISTANCE): # at least 20m of gap is between two cars between center of cars it is 18m laneOverlap = True break # overlap so start a new if not laneOverlap: # no break happened so assign x,y position and lanenumber to car i envCars[i].xPos = xPos # as of now use between min and max velocity must be changed latter envCars[i].xVel = params.CAR_MIN_SPEED + np.random.randint(0, 6) * params.CAR_ACCEL_RATE # 3.6 is the lane width and 1.8 is the center of the lane envCars[i].yPos = laneNum * params.ROAD_LN_GAP + params.ROAD_LANE_CENTER envCars[i].MaxVel = envCars[i].xVel envCars[i].laneNum = laneNum def getAffordInd(envCars): # get affordance indicator # print(len(envCars)) indiNum = np.ones([len(envCars), params.CAR_NUM_STATES], dtype='f')*-1e3 tmp = np.ones([len(envCars), params.NUM_VIS_CARS], dtype=int) # there are 6 vehicles which are visible to every car for i in range(len(envCars)): indiNum[i], tmp[i] = envCars[i].getAffIndiOfaCar(envCars) return indiNum, tmp[0] # only the ego car used to indicate which cars are visible def setAction(envCars, afInd): # set action for rest of the cars car # this only works for level 0 # modify this to include level 1 policy for ego car later # as of now no acceleration and no lane change same as uofm for i in range(len(envCars)): # include based on front center car + accl if there is no other car # get the front car velocity and distance # IDM + accl cf_d = params.CAR_MAXVIS_DISTANCE cf_v = params.CAR_MAX_SPEED eg_v = afInd[i, C.E_SP] eg_ln = afInd[i, C.E_LN] eg_pos = envCars[i].xPos if eg_ln == params.ROAD_LEFT_LANE: # on left lane cf_d = afInd[i, C.FL_D] cf_v = afInd[i, C.FL_V] elif eg_ln == params.ROAD_CENTER_LANE: # on center lane cf_d = afInd[i, C.FC_D] cf_v = afInd[i, C.FC_V] elif eg_ln == params.ROAD_RIGHT_LANE: # on right lane cf_d = afInd[i, C.FR_D] cf_v = afInd[i, C.FR_V] if cf_d <= params.CAR_DISTANCE_1 and (eg_v-cf_v) >= params.CAR_ACCEL_RATE: envCars[i].xVelAct = params.CAR_HARD_DECEL_RATE envCars[i].yPosAct = params.CAR_MAINTAIN envCars[i].laneNumAct = params.CAR_MAINTAIN envCars[i].ActNum = C.A_HM elif (cf_d <= params.CAR_DISTANCE_0 and eg_v > params.CAR_MIN_SPEED) or \ (cf_d <= params.CAR_DISTANCE_2 and (eg_v - cf_v) >= params.CAR_ACCEL_RATE): envCars[i].xVelAct = params.CAR_DECEL_RATE envCars[i].yPosAct = params.CAR_MAINTAIN envCars[i].laneNumAct = params.CAR_MAINTAIN envCars[i].ActNum = C.A_BM elif eg_pos < 170 and cf_d >= params.CAR_DISTANCE_3 and (cf_v - eg_v) >= params.CAR_ACCEL_RATE: # front car is far away and also moving away # ego car has enough space in front of it envCars[i].xVelAct = params.CAR_ACCEL_RATE envCars[i].yPosAct = params.CAR_MAINTAIN envCars[i].laneNumAct = params.CAR_MAINTAIN envCars[i].ActNum = C.A_AM else: envCars[i].xVelAct = params.CAR_MAINTAIN envCars[i].yPosAct = params.CAR_MAINTAIN envCars[i].laneNumAct = params.CAR_MAINTAIN envCars[i].ActNum = C.A_MM def setEgoCarAction(egoCar, act): # set action for ego car # default is maintain egoCar.ActNum = act if act == C.A_AM: # accelerate egoCar.xVelAct = params.CAR_ACCEL_RATE egoCar.yPosAct = params.CAR_MAINTAIN egoCar.laneNumAct = params.CAR_MAINTAIN elif act == C.A_BM: # Hard accelerate egoCar.xVelAct = params.CAR_DECEL_RATE egoCar.yPosAct = params.CAR_MAINTAIN egoCar.laneNumAct = params.CAR_MAINTAIN elif act == C.A_HM: # decelerate egoCar.xVelAct = params.CAR_HARD_DECEL_RATE egoCar.yPosAct = params.CAR_MAINTAIN egoCar.laneNumAct = params.CAR_MAINTAIN elif act == C.A_ML: # change lane to left egoCar.xVelAct = params.CAR_MAINTAIN egoCar.yPosAct = params.CAR_TO_LEFT egoCar.laneNumAct = params.CAR_TO_LEFT_LN elif act == C.A_MR: # change lane to right egoCar.xVelAzzct = params.CAR_MAINTAIN egoCar.yPosAct = params.CAR_TO_RIGHT egoCar.laneNumAct = params.CAR_TO_RIGH_LN elif act == C.A_BL: # change lane to right egoCar.xVelAct = params.CAR_DECEL_RATE egoCar.yPosAct = params.CAR_TO_LEFT egoCar.laneNumAct = params.CAR_TO_LEFT_LN elif act == C.A_BR: # change lane to right egoCar.xVelAct = params.CAR_DECEL_RATE egoCar.yPosAct = params.CAR_TO_RIGHT egoCar.laneNumAct = params.CAR_TO_RIGH_LN else: # either invalid action number or 0 so maintain egoCar.xVelAct = params.CAR_MAINTAIN egoCar.yPosAct = params.CAR_MAINTAIN egoCar.laneNumAct = params.CAR_MAINTAIN def appAction(envCars): # Action has been set now apply for every car egoCarVel = envCars[0].xVel for i in range(len(envCars)): if i > 0: # ego car has adjusted its velocity take new velocity into consideration egoCarVel = envCars[0].xVel envCars[i].stateUpdate(egoCarVel) def storeCarsPos(envCars, posHist, timeIdx): for i in range(len(envCars)): # currently store x and y position for all the cars in the history array posHist[i][timeIdx] = np.array([envCars[i].xPos, envCars[i].yPos, envCars[i].xVel, envCars[i].xVelAct]) def scaleState(afIndNum): sScl = np.zeros(params.CAR_NUM_STATES) carIdx = np.arange(1, 7) # car number 1 to 6 xIdx = carIdx*3-1 vIdx = carIdx*3 yIdx = carIdx*3+1 # car sScl[0] = afIndNum[0] / params.ROAD_LEFT_LANE sScl[1] = (afIndNum[1]-params.CAR_MIN_SPEED)/params.CAR_SPD_RANGE # envi sScl[xIdx] = afIndNum[xIdx]/params.CAR_MAXVIS_DISTANCE # relative x position sScl[vIdx] = (afIndNum[vIdx]-afIndNum[1])/params.CAR_SPD_RANGE # relative velocity sScl[yIdx] = (afIndNum[yIdx]-afIndNum[0])/params.ROAD_LEFT_LANE # relative y position return np.around(sScl, decimals=4) # for CVAE, calculate whole batch def scaleStateTensor(afIndNum, device): sScl = tr.zeros(afIndNum.shape).to(device) carIdx = np.arange(1, 7) # car number 1 to 6 xIdx = carIdx*3-1 vIdx = carIdx*3 yIdx = carIdx*3+1 # car sScl[:, 0] = afIndNum[:, 0] / params.ROAD_LEFT_LANE sScl[:, 1] = (afIndNum[:, 1] - params.CAR_MIN_SPEED)/ params.CAR_SPD_RANGE # envi sScl[:, xIdx] = afIndNum[:, xIdx]/params.CAR_MAXVIS_DISTANCE sScl[:, vIdx] = (afIndNum[:, vIdx]-tr.transpose(afIndNum[:, 1].repeat(6,1), 0,1))/params.CAR_SPD_RANGE sScl[:, yIdx] = (afIndNum[:, yIdx]-tr.transpose(afIndNum[:, 0].repeat(6,1), 0,1))/params.ROAD_LEFT_LANE return sScl def reverseScaleStateTensor(afIndNum, device): sScl = tr.zeros(afIndNum.shape).to(device) carIdx = np.arange(1, 7) # car number 1 to 6 xIdx = carIdx*3-1 vIdx = carIdx*3 yIdx = carIdx*3+1 # car sScl[:, 0] = afIndNum[:, 0] * params.ROAD_LEFT_LANE sScl[:, 1] = afIndNum[:, 1] * params.CAR_SPD_RANGE + params.CAR_MIN_SPEED # envi sScl[:, xIdx] = afIndNum[:, xIdx]*params.CAR_MAXVIS_DISTANCE # relative x position sScl[:, vIdx] = afIndNum[:, vIdx]*params.CAR_SPD_RANGE + tr.transpose(sScl[:,1].repeat(6,1), 0,1) # absolute velocity sScl[:, yIdx] = afIndNum[:, yIdx]*params.ROAD_LEFT_LANE + tr.transpose(sScl[:,0].repeat(6,1), 0,1) # absolute y position return sScl def checkColi4Ego(eIdC, eIdC_N, act): e_ln = eIdC[C.E_LN] collision = False if e_ln == params.ROAD_RIGHT_LANE and (act == C.A_BR or act == C.A_MR): # this implies some problem with safety controller collision = True elif e_ln == params.ROAD_LEFT_LANE and (act == C.A_BL or act == C.A_ML): # this implies some problem with safety controller collision = True else: # only this condition is valid for i in range(C.NUM_CAR_P_LN): fxPos = C.NUM_AFID_E+i*C.NUM_AFID_R # 2+i*3: FL_D=2, FC_D=5, FR_D=8 rxPos = fxPos+C.AFID_XPOS_OFFSET # fxPos + 9: RL_D=11, RC_D=14, RR_D=17 fyPos = fxPos+C.X_Y_POS_OFFSET # fxPos + 2: FL_P=4, FC_P=7, FR_P=10 ryPos = rxPos+C.X_Y_POS_OFFSET # rxPos + 2: RL_P=13, RC_P=16, RR_P=19 if (abs(eIdC_N[fyPos]-eIdC_N[C.E_LN])*C.LN_LENGTH < C.Y_COL_LMT and abs(eIdC_N[fxPos]) < C.X_COL_LMT) \ or (abs(eIdC_N[ryPos] - eIdC_N[C.E_LN]) * C.LN_LENGTH < C.Y_COL_LMT and abs(eIdC_N[rxPos]) < C.X_COL_LMT): collision = True return collision def rplAct(eg_v, cf_d, cf_v): if cf_d <= params.CAR_DISTANCE_1 and (eg_v-cf_v) >= params.CAR_ACCEL_RATE: return C.A_HM elif (cf_d <= params.CAR_DISTANCE_0 and eg_v > params.CAR_MIN_SPEED) \ or chkSafeDist(eg_v, cf_d, cf_v) <= 0 \ or (cf_d < params.CAR_DISTANCE_2 and (eg_v - cf_v) >= params.CAR_ACCEL_RATE): return C.A_BM else: return C.A_MM def getVY(eIDC_N, cf_d): # this code works only when other cars are not changing the lane maxV = params.CAR_MIN_SPEED disY = eIDC_N[C.E_LN] eV = eIDC_N[C.E_SP] eP = eIDC_N[C.E_LN] # get the distance&velocity to closest front car fl_d, fc_d, fr_d = eIDC_N[C.FL_D], eIDC_N[C.FC_D], eIDC_N[C.FR_D] fl_v, fc_v, fr_v = eIDC_N[C.FL_V], eIDC_N[C.FC_V], eIDC_N[C.FR_V] # get the distance&velocity to closest rear car rl_d, rc_d, rr_d = eIDC_N[C.RL_D], eIDC_N[C.RC_D], eIDC_N[C.RR_D] rl_v, rc_v, rr_v = eIDC_N[C.RL_V], eIDC_N[C.RC_V], eIDC_N[C.RR_V] if fr_v > maxV or (fr_v == maxV and eP == C.R_LN): maxV = fr_v disY = C.R_LN if fl_v > maxV or (fl_v == maxV and eP == C.L_LN): maxV = fl_v disY = C.L_LN if fc_v > maxV or (fc_v == maxV and eP == C.C_LN): # by changing it to >= preference can be given for center lane maxV = fc_v disY = C.C_LN if abs(eV - maxV) < 1e-2: # dont penalize if ego car is going at maximum possible velocity disY = eP if (eP % 4) == 0 and cf_d > C.M_ACL_DIST: maxV = params.CAR_MAX_SPEED disY = eP if (eP % 4) == 0: # on lane mark if disY < eP: if eP == C.L_LN and (chkSafeDist(eV, fl_d, fl_v) <= 0 or chkSafeDist(eV, fc_d, fc_v) <= 0 or chkRearSafeDist(eV, rc_d, rc_v) <= 0): # currently on left lane but desired lane is right of me # not possible to change lane as it will be overwritten by safety maxV = eV disY = eP if eP == C.C_LN and (chkSafeDist(eV, fc_d, fc_v) <= 0 or chkSafeDist(eV, fr_d, fr_v) <= 0 or chkRearSafeDist(eV, rr_d, rr_v) <= 0): # currently on center lane but desired lane is right of me # not possible to change lane as it will be overwritten by safety maxV = eV disY = eP if disY > eP: if eP == C.R_LN and (chkSafeDist(eV, fr_d, fr_v) <= 0 or chkSafeDist(eV, fc_d, fc_v) <= 0 or chkRearSafeDist(eV, rc_d, rc_v) <= 0): # currently on right lane but desired lane is left of me # not possible to change lane as it will be overwritten by safety maxV = eV disY = eP if eP == C.C_LN and (chkSafeDist(eV, fc_d, fc_v) <= 0 or chkSafeDist(eV, fl_d, fl_v) <= 0 or chkRearSafeDist(eV, rl_d, rl_v) <= 0): # currently on center lane but desired lane is left of me # not possible to change lane as it will be overwritten by safety maxV = eV disY = eP return maxV, disY def getcfDV(eIDC_N): eP = eIDC_N[C.E_LN] # get the distance to closest front car fl_d, fc_d, fr_d = eIDC_N[C.FL_D], eIDC_N[C.FC_D], eIDC_N[C.FR_D] fl_v, fc_v, fr_v = eIDC_N[C.FL_V], eIDC_N[C.FC_V], eIDC_N[C.FR_V] cf_d = params.CAR_DISTANCE_0 if eP % C.C_LN == 0: # on center of lane if eP == C.R_LN: cf_d = fr_d cf_v = fr_v elif eP == C.C_LN: cf_d = fc_d cf_v = fc_v elif eP == C.L_LN: cf_d = fl_d cf_v = fl_v else: # between lanes if eP < C.C_LN: if fc_d < fr_d: cf_d = fc_d cf_v = fc_v else: cf_d = fr_d cf_v = fr_v elif eP < C.L_LN: if fc_d < fl_d: cf_d = fc_d cf_v = fc_v else: cf_d = fl_d cf_v = fl_v else: cf_d = fl_d cf_v = fl_v return cf_d, cf_v def isOnLaneMark(ln): return (ln % 4) != 0 def getRewCmp(eIDC_N): # this would only work for level 1 - level 0 scenario where level 0 is modified IDM with no lane change option eV = eIDC_N[C.E_SP] eP = eIDC_N[C.E_LN] # get front dist and rel vel cf_d, cf_v = getcfDV(eIDC_N) # Check this plz cf_relv = eV-cf_v # get feasible V and Y maxV, disY = getVY(eIDC_N, cf_d) # Check this plz # between lanes when ego car is at a lower speed than maximum speed dont penalize rewV = 0 if (eP % 4) == 0 or eV > maxV: # on lane penalize if going over or under speed # if eV is higher than maxV then penalize (this will happen only between lanes) rewV = np.exp(-(eV-maxV)**2/(2*2*params.CAR_ACCEL_RATE**2))-1 # dont penalize when there is no front car rewY = 0 if cf_d < C.M_ACL_DIST: # when there is a front car and there is a potential for ego car to achieve higher velocity rewY = np.exp(-(eP-disY)**2/(2*params.CAR_ACCEL_RATE**2))-1 sfDist = (C.NOM_DIST * C.LEN_SCL) + (eV - cf_v) * C.NO_COLI_TIME midDis = sfDist+(C.M_ACL_DIST-sfDist)/C.LEN_SCL rewX = 0 if (eP % 4) == 0 and cf_relv > 0 and cf_d < midDis: rewX = np.exp(-(cf_d-midDis)**2/(2*C.NOM_DIST**2))-1 return rewV, rewY, rewX, cf_d, maxV, disY, eV, cf_v, midDis # modified safety check based on inputs by Shankar see his slides def chkRearSafeDist(e_v, r_d, r_v): if e_v < r_v: return -((r_d + C.NOM_DIST * C.LEN_SCL) - (e_v - r_v)*C.VEL_SCL) else: return -(r_d + C.NOM_DIST * C.LEN_SCL) def chkSafeDist(e_v, f_d, f_v): # f_d,e_v,f_v all are +ve numbers if e_v > f_v: return (f_d - C.NOM_DIST * C.LEN_SCL) - (e_v - f_v) * C.NO_COLI_TIME else: return f_d - C.NOM_DIST * C.LEN_SCL def safeAct2(act, eIdC): newAct = act rstPrfAct = True e_ln = eIdC[C.E_LN] eg_v = eIdC[C.E_SP] # default is lower than the bound, forced accl only if on lane and distance is higher than bound cf_d = C.M_ACL_DIST - 1 cf_v = params.CAR_MIN_SPEED if e_ln % 4 == 0: if e_ln == params.ROAD_RIGHT_LANE: cf_d = eIdC[C.FR_D] cf_v = eIdC[C.FR_V] elif e_ln == params.ROAD_CENTER_LANE: cf_d = eIdC[C.FC_D] cf_v = eIdC[C.FC_V] elif e_ln == params.ROAD_LEFT_LANE: cf_d = eIdC[C.FL_D] cf_v = eIdC[C.FL_V] # safety check # in lane as of now disabled change M_ACL_DIST to get different value # just accl as the front car is really far away if (e_ln % 4) == 0 and ((act <= C.A_HM and chkSafeDist(eg_v, cf_d, cf_v) <= 0) or (act >= C.A_BL)): # in lane and action is maintain, accl or decl check for safety # if it leads to collision get a replacement action newAct = rplAct(eg_v, cf_d, cf_v) return newAct, rstPrfAct elif (e_ln % 4) == 0 and cf_d >= C.M_ACL_DIST and\ (eg_v < params.CAR_MAX_SPEED) and (act != C.A_AM): # no front car and not accl hence force accl newAct = C.A_AM return newAct, rstPrfAct elif (e_ln % 4) == 0 and cf_d >= C.M_ACL_DIST and\ (eg_v == params.CAR_MAX_SPEED) and (act != C.A_MM): # no front car and maximum speed # maximum speed hence cant accelerate further newAct = C.A_MM return newAct, rstPrfAct elif e_ln <= params.ROAD_RIGHT_LANE: # on Right lane if act == C.A_BR or act == C.A_MR: # not possible to change lane to right cf_d = eIdC[C.FR_D] cf_v = eIdC[C.FR_V] newAct = rplAct(eg_v, cf_d, cf_v) return newAct, rstPrfAct elif e_ln >= params.ROAD_LEFT_LANE: # on left lane if act == C.A_BL or act == C.A_ML: # not possible to change lane to right cf_d = eIdC[C.FL_D] cf_v = eIdC[C.FL_V] newAct = rplAct(eg_v, cf_d, cf_v) return newAct, rstPrfAct if act == C.A_ML: # if action is change lane to left check for safe action if it leads to collision # get left car works only for level 0 if e_ln < C.C_LN: # on right line # left car position and velocity fl_d = eIdC[C.FC_D] fl_v = eIdC[C.FC_V] rl_d = eIdC[C.RC_D] rl_v = eIdC[C.RC_V] # right car position and velocity + lane number fr_d = eIdC[C.FR_D] fr_v = eIdC[C.FR_V] fr_ln = eIdC[C.FR_P] else: fl_d = eIdC[C.FL_D] fl_v = eIdC[C.FL_V] rl_d = eIdC[C.RL_D] rl_v = eIdC[C.RL_V] fr_d = eIdC[C.FC_D] fr_v = eIdC[C.FC_V] fr_ln = eIdC[C.FC_P] if (chkSafeDist(eg_v, fl_d, fl_v) <= 0) \ or ((chkSafeDist(eg_v, fr_d, fr_v) <= 0) and abs(e_ln-fr_ln) < C.MIN_LN_SEP)\ or (chkRearSafeDist(eg_v, rl_d, rl_v) <= 0): if (e_ln % 4) != 0 and e_ln >= params.ROAD_RIGHT_LANE: # only on lane mark newAct = np.random.randint(C.A_BL, params.CAR_NUM_ACTIONS) rstPrfAct = True else: # get alternate action for in lane newAct = rplAct(eg_v, cf_d, cf_v) rstPrfAct = True else: newAct = act rstPrfAct = False return newAct, rstPrfAct elif act == C.A_MR: # if action is change lane to right check for safe action if it leads to collision # get right car works only for level 0 if e_ln > C.C_LN: fr_d = eIdC[C.FC_D] fr_v = eIdC[C.FC_V] rr_d = eIdC[C.RC_D] rr_v = eIdC[C.RC_V] fl_d = eIdC[C.FL_D] fl_v = eIdC[C.FL_V] fl_ln = eIdC[C.FL_P] else: fr_d = eIdC[C.FR_D] fr_v = eIdC[C.FR_V] rr_d = eIdC[C.RR_D] rr_v = eIdC[C.RR_V] fl_d = eIdC[C.FC_D] fl_v = eIdC[C.FC_V] fl_ln = eIdC[C.FC_P] if (chkSafeDist(eg_v, fr_d, fr_v) <= 0) \ or ((chkSafeDist(eg_v, fl_d, fl_v) <= 0) and (e_ln-fl_ln) < C.MIN_LN_SEP) \ or (chkRearSafeDist(eg_v, rr_d, rr_v) <= 0): if (e_ln % 4) != 0 and e_ln <= params.ROAD_LEFT_LANE: newAct = np.random.randint(C.A_BL, params.CAR_NUM_ACTIONS) rstPrfAct = True else: # get alternate action for in lane newAct = rplAct(eg_v, cf_d, cf_v) rstPrfAct = True else: newAct = act rstPrfAct = False return newAct, rstPrfAct elif act == C.A_BL: newAct = act rstPrfAct = False return newAct, rstPrfAct elif act == C.A_BR: newAct = act rstPrfAct = False return newAct, rstPrfAct # figure out best alternate action return newAct, rstPrfAct def safeActEval(act, eIdC, sfLMAct): newAct = act rstPrfAct = True e_ln = eIdC[C.E_LN] eg_v = eIdC[C.E_SP] # default is lower than the bound, forced accl only if on lane and distance is higher than bound cf_d = C.M_ACL_DIST - 1 cf_v = params.CAR_MIN_SPEED if e_ln % 4 == 0: if e_ln == params.ROAD_RIGHT_LANE: cf_d = eIdC[C.FR_D] cf_v = eIdC[C.FR_V] elif e_ln == params.ROAD_CENTER_LANE: cf_d = eIdC[C.FC_D] cf_v = eIdC[C.FC_V] elif e_ln == params.ROAD_LEFT_LANE: cf_d = eIdC[C.FL_D] cf_v = eIdC[C.FL_V] # safety check # in lane as of now disabled change M_ACL_DIST to get different value # just accl as the front car is really far away if e_ln % 4 == 0 and ((act <= C.A_HM and chkSafeDist(eg_v, cf_d, cf_v) <= 0) or (act >= C.A_BL)): # in lane and action is maintain, accl or decl check for safety # if it leads to collision get a replacement action newAct = rplAct(eg_v, cf_d, cf_v) return newAct, rstPrfAct elif (e_ln % 4) == 0 and cf_d >= params.CAR_MAXVIS_DISTANCE and cf_v >= params.CAR_MAX_SPEED and\ (eg_v < params.CAR_MAX_SPEED) and (act != C.A_AM): # no front car and not accl hence force accl newAct = C.A_AM return newAct, rstPrfAct elif (e_ln % 4) == 0 and cf_d >= params.CAR_MAXVIS_DISTANCE and cf_v >= params.CAR_MAX_SPEED and\ (eg_v == params.CAR_MAX_SPEED) and (act != C.A_MM): # no front car and maximum speed # maximum speed hence cant accelerate further newAct = C.A_MM return newAct, rstPrfAct elif e_ln == params.ROAD_RIGHT_LANE: # on Right lane if act == C.A_BR or act == C.A_MR: # not possible to change lane to right cf_d = eIdC[C.FR_D] cf_v = eIdC[C.FR_V] newAct = rplAct(eg_v, cf_d, cf_v) return newAct, rstPrfAct elif e_ln == params.ROAD_LEFT_LANE: # on left lane if act == C.A_BL or act == C.A_ML: # not possible to change lane to right cf_d = eIdC[C.FL_D] cf_v = eIdC[C.FL_V] newAct = rplAct(eg_v, cf_d, cf_v) return newAct, rstPrfAct if act == C.A_ML: # if action is change lane to left check for safe action if it leads to collision # get left car works only for level 0 if e_ln < C.C_LN: # left car position and velocity fl_d = eIdC[C.FC_D] fl_v = eIdC[C.FC_V] rl_d = eIdC[C.RC_D] rl_v = eIdC[C.RC_V] # right car position and velocity + lane number fr_d = eIdC[C.FR_D] fr_v = eIdC[C.FR_V] fr_ln = eIdC[C.FR_P] else: fl_d = eIdC[C.FL_D] fl_v = eIdC[C.FL_V] rl_d = eIdC[C.RL_D] rl_v = eIdC[C.RL_V] fr_d = eIdC[C.FC_D] fr_v = eIdC[C.FC_V] fr_ln = eIdC[C.FC_P] if (chkSafeDist(eg_v, fl_d, fl_v) <= 0) \ or ((chkSafeDist(eg_v, fr_d, fr_v) <= 0) and abs(e_ln-fr_ln) < C.MIN_LN_SEP)\ or (chkRearSafeDist(eg_v, rl_d, rl_v) <= 0): if isOnLaneMark(e_ln): # only on lane mark newAct = sfLMAct rstPrfAct = True else: # get alternate action for in lane newAct = rplAct(eg_v, cf_d, cf_v) rstPrfAct = True else: newAct = act rstPrfAct = False return newAct, rstPrfAct elif act == C.A_MR: # if action is change lane to right check for safe action if it leads to collision # get right car works only for level 0 if e_ln > C.C_LN: fr_d = eIdC[C.FC_D] fr_v = eIdC[C.FC_V] rr_d = eIdC[C.RC_D] rr_v = eIdC[C.RC_V] fl_d = eIdC[C.FL_D] fl_v = eIdC[C.FL_V] fl_ln = eIdC[C.FL_P] else: fr_d = eIdC[C.FR_D] fr_v = eIdC[C.FR_V] rr_d = eIdC[C.RR_D] rr_v = eIdC[C.RR_V] fl_d = eIdC[C.FC_D] fl_v = eIdC[C.FC_V] fl_ln = eIdC[C.FC_P] if (chkSafeDist(eg_v, fr_d, fr_v) <= 0) \ or ((chkSafeDist(eg_v, fl_d, fl_v) <= 0) and (e_ln-fl_ln) < C.MIN_LN_SEP)\ or (chkRearSafeDist(eg_v, rr_d, rr_v) <= 0): if (e_ln % 4) != 0: newAct = sfLMAct rstPrfAct = False else: # get alternate action for in lane newAct = rplAct(eg_v, cf_d, cf_v) rstPrfAct = True else: newAct = act rstPrfAct = False return newAct, rstPrfAct elif act == C.A_BL: newAct = act rstPrfAct = False return newAct, rstPrfAct elif act == C.A_BR: newAct = act rstPrfAct = False return newAct, rstPrfAct # figure out best alternate action return newAct, rstPrfAct
[ "numpy.zeros", "numpy.around", "numpy.random.randint", "numpy.array", "numpy.arange", "numpy.exp", "numpy.random.random", "torch.zeros" ]
[((6964, 6995), 'numpy.zeros', 'np.zeros', (['params.CAR_NUM_STATES'], {}), '(params.CAR_NUM_STATES)\n', (6972, 6995), True, 'import numpy as np\n'), ((7010, 7025), 'numpy.arange', 'np.arange', (['(1)', '(7)'], {}), '(1, 7)\n', (7019, 7025), True, 'import numpy as np\n'), ((7526, 7553), 'numpy.around', 'np.around', (['sScl'], {'decimals': '(4)'}), '(sScl, decimals=4)\n', (7535, 7553), True, 'import numpy as np\n'), ((7690, 7705), 'numpy.arange', 'np.arange', (['(1)', '(7)'], {}), '(1, 7)\n', (7699, 7705), True, 'import numpy as np\n'), ((8355, 8370), 'numpy.arange', 'np.arange', (['(1)', '(7)'], {}), '(1, 7)\n', (8364, 8370), True, 'import numpy as np\n'), ((6843, 6929), 'numpy.array', 'np.array', (['[envCars[i].xPos, envCars[i].yPos, envCars[i].xVel, envCars[i].xVelAct]'], {}), '([envCars[i].xPos, envCars[i].yPos, envCars[i].xVel, envCars[i].\n xVelAct])\n', (6851, 6929), True, 'import numpy as np\n'), ((7640, 7664), 'torch.zeros', 'tr.zeros', (['afIndNum.shape'], {}), '(afIndNum.shape)\n', (7648, 7664), True, 'import torch as tr\n'), ((8305, 8329), 'torch.zeros', 'tr.zeros', (['afIndNum.shape'], {}), '(afIndNum.shape)\n', (8313, 8329), True, 'import torch as tr\n'), ((15093, 15157), 'numpy.exp', 'np.exp', (['(-(eV - maxV) ** 2 / (2 * 2 * params.CAR_ACCEL_RATE ** 2))'], {}), '(-(eV - maxV) ** 2 / (2 * 2 * params.CAR_ACCEL_RATE ** 2))\n', (15099, 15157), True, 'import numpy as np\n'), ((15352, 15412), 'numpy.exp', 'np.exp', (['(-(eP - disY) ** 2 / (2 * params.CAR_ACCEL_RATE ** 2))'], {}), '(-(eP - disY) ** 2 / (2 * params.CAR_ACCEL_RATE ** 2))\n', (15358, 15412), True, 'import numpy as np\n'), ((15616, 15669), 'numpy.exp', 'np.exp', (['(-(cf_d - midDis) ** 2 / (2 * C.NOM_DIST ** 2))'], {}), '(-(cf_d - midDis) ** 2 / (2 * C.NOM_DIST ** 2))\n', (15622, 15669), True, 'import numpy as np\n'), ((786, 806), 'numpy.random.randint', 'np.random.randint', (['(3)'], {}), '(3)\n', (803, 806), True, 'import numpy as np\n'), ((19497, 19546), 'numpy.random.randint', 'np.random.randint', (['C.A_BL', 'params.CAR_NUM_ACTIONS'], {}), '(C.A_BL, params.CAR_NUM_ACTIONS)\n', (19514, 19546), True, 'import numpy as np\n'), ((595, 613), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (611, 613), True, 'import numpy as np\n'), ((20784, 20833), 'numpy.random.randint', 'np.random.randint', (['C.A_BL', 'params.CAR_NUM_ACTIONS'], {}), '(C.A_BL, params.CAR_NUM_ACTIONS)\n', (20801, 20833), True, 'import numpy as np\n'), ((1552, 1575), 'numpy.random.randint', 'np.random.randint', (['(0)', '(6)'], {}), '(0, 6)\n', (1569, 1575), True, 'import numpy as np\n')]
from astropy.io import fits, ascii from astropy.table import Table import numpy as NP project_MWA = False project_HERA = False project_beams = False project_drift_scan = True project_global_EoR = False if project_MWA: project_dir = 'project_MWA' if project_HERA: project_dir = 'project_HERA' if project_beams: project_dir = 'project_beams' if project_drift_scan: project_dir = 'project_drift_scan' if project_global_EoR: project_dir = 'project_global_EoR' telescope_id = 'custom' element_size = 0.74 element_shape = 'delta' phased_array = True if (telescope_id == 'mwa') or (telescope_id == 'mwa_dipole'): element_size = 0.74 element_shape = 'dipole' elif telescope_id == 'vla': element_size = 25.0 element_shape = 'dish' elif telescope_id == 'gmrt': element_size = 45.0 element_shape = 'dish' elif telescope_id == 'hera': element_size = 14.0 element_shape = 'dish' elif telescope_id == 'custom': if (element_shape is None) or (element_size is None): raise ValueError('Both antenna element shape and size must be specified for the custom telescope type.') elif element_size <= 0.0: raise ValueError('Antenna element size must be positive.') else: raise ValueError('telescope ID must be specified.') if telescope_id == 'custom': if element_shape == 'delta': telescope_id = 'delta' else: telescope_id = '{0:.1f}m_{1:}'.format(element_size, element_shape) if phased_array: telescope_id = telescope_id + '_array' telescope_str = telescope_id+'_' ground_plane = 0.3 # height of antenna element above ground plane if ground_plane is None: ground_plane_str = 'no_ground_' else: if ground_plane > 0.0: ground_plane_str = '{0:.1f}m_ground_'.format(ground_plane) else: raise ValueError('Height of antenna element above ground plane must be positive.') delayerr = 0.0 # delay error rms in ns if delayerr is None: delayerr_str = '' delayerr = 0.0 elif delayerr < 0.0: raise ValueError('delayerr must be non-negative.') else: delayerr_str = 'derr_{0:.3f}ns'.format(delayerr) delayerr *= 1e-9 gainerr = 0.0 # Gain error rms in dB if gainerr is None: gainerr_str = '' gainerr = 0.0 elif gainerr < 0.0: raise ValueError('gainerr must be non-negative.') else: gainerr_str = '_gerr_{0:.2f}dB'.format(gainerr) nrand = 1 # Number of random realizations if nrand is None: nrandom_str = '' nrand = 1 elif nrand < 1: raise ValueError('nrandom must be positive') else: nrandom_str = '_nrand_{0:0d}_'.format(nrand) if (delayerr_str == '') and (gainerr_str == ''): nrand = 1 nrandom_str = '' delaygain_err_str = delayerr_str + gainerr_str + nrandom_str if project_MWA: delaygain_err_str = '' # latitude = -26.701 # antenna_file = '/data3/t_nithyanandan/project_MWA/MWA_128T_antenna_locations_MNRAS_2012_Beardsley_et_al.txt' max_bl_length = None # Maximum baseline length (in m) # ant_locs = NP.loadtxt(antenna_file, skiprows=6, comments='#', usecols=(0,1,2,3)) # ref_bl, ref_bl_id = RI.baseline_generator(ant_locs[:,1:], ant_id=ant_locs[:,0].astype(int).astype(str), auto=False, conjugate=False) # ref_bl_length = NP.sqrt(NP.sum(ref_bl**2, axis=1)) # ref_bl_orientation = NP.angle(ref_bl[:,0] + 1j * ref_bl[:,1], deg=True) # neg_ref_bl_orientation_ind = ref_bl_orientation < 0.0 # ref_bl[neg_ref_bl_orientation_ind,:] = -1.0 * ref_bl[neg_ref_bl_orientation_ind,:] # ref_bl_orientation = NP.angle(ref_bl[:,0] + 1j * ref_bl[:,1], deg=True) # sortind = NP.argsort(ref_bl_length, kind='mergesort') # ref_bl = ref_bl[sortind,:] # ref_bl_length = ref_bl_length[sortind] # ref_bl_orientation = ref_bl_orientation[sortind] # ref_bl_id = ref_bl_id[sortind] # n_bins_baseline_orientation = 4 # nmax_baselines = 2048 # ref_bl = ref_bl[:nmax_baselines,:] # ref_bl_length = ref_bl_length[:nmax_baselines] # ref_bl_id = ref_bl_id[:nmax_baselines] # ref_bl_orientation = ref_bl_orientation[:nmax_baselines] # total_baselines = ref_bl_length.size Tsys = 440.0 # System temperature in K freq = 150.0e6 # center frequency in Hz oversampling_factor = 2.0 n_sky_sectors = 1 sky_sector = None # if None, use all sky sector. Accepted values are None, 0, 1, 2, or 3 if sky_sector is None: sky_sector_str = '_all_sky_' n_sky_sectors = 1 sky_sector = 0 else: sky_sector_str = '_sky_sector_{0:0d}_'.format(sky_sector) cspeed = 299792458.0 # Speed of light in m/s # n_bl_chunks = 16 # baseline_chunk_size = 128 # baseline_bin_indices = range(0,total_baselines,baseline_chunk_size) # bl_chunk = range(len(baseline_bin_indices)) # bl_chunk = bl_chunk[:n_bl_chunks] # truncated_ref_bl = NP.copy(ref_bl) # truncated_ref_bl_id = NP.copy(ref_bl_id) # truncated_ref_bl_length = NP.sqrt(NP.sum(truncated_ref_bl[:,:2]**2, axis=1)) # # truncated_ref_bl_length = NP.copy(ref_bl_length) # truncated_ref_bl_orientation = NP.copy(ref_bl_orientation) # truncated_total_baselines = truncated_ref_bl_length.size # if max_bl_length is not None: # truncated_ref_bl_ind = ref_bl_length <= max_bl_length # truncated_ref_bl = truncated_ref_bl[truncated_ref_bl_ind,:] # truncated_ref_bl_id = truncated_ref_bl_id[truncated_ref_bl_ind] # truncated_ref_bl_orientation = truncated_ref_bl_orientation[truncated_ref_bl_ind] # truncated_ref_bl_length = truncated_ref_bl_length[truncated_ref_bl_ind] # truncated_total_baselines = truncated_ref_bl_length.size spindex_rms = 0.0 spindex_seed = None spindex_seed_str = '' if spindex_rms > 0.0: spindex_rms_str = '{0:.1f}'.format(spindex_rms) else: spindex_rms = 0.0 if spindex_seed is not None: spindex_seed_str = '{0:0d}_'.format(spindex_seed) use_alt_spindex = False alt_spindex_rms = 0.3 alt_spindex_seed = 95 alt_spindex_seed_str = '' if alt_spindex_rms > 0.0: alt_spindex_rms_str = '{0:.1f}'.format(alt_spindex_rms) else: alt_spindex_rms = 0.0 if alt_spindex_seed is not None: alt_spindex_seed_str = '{0:0d}_'.format(alt_spindex_seed) nside = 64 use_GSM = True use_DSM = False use_CSM = False use_NVSS = False use_SUMSS = False use_MSS = False use_GLEAM = False use_PS = False obs_mode = 'drift' avg_drifts = False beam_switch = False snapshot_type_str = '' if avg_drifts: snapshot_type_str = 'drift_averaged_' if beam_switch: snapshot_type_str = 'beam_switches_' freq_resolution = 80e3 # in kHz nchan = 96 bw = nchan * freq_resolution if use_GSM: fg_str = 'asm' elif use_DSM: fg_str = 'dsm' elif use_CSM: fg_str = 'csm' elif use_SUMSS: fg_str = 'sumss' elif use_GLEAM: fg_str = 'gleam' elif use_PS: fg_str = 'point' elif use_NVSS: fg_str = 'nvss' else: fg_str = 'other' # Edit the following line to give the full and correct path to the simulation data file infile = '/data3/t_nithyanandan/'+project_dir+'/'+telescope_str+'multi_baseline_visibilities_'+ground_plane_str+snapshot_type_str+obs_mode+'_baseline_range_{0:.1f}-{1:.1f}_'.format(7.7, 321.7)+'gaussian_FG_model_'+fg_str+sky_sector_str+'sprms_{0:.1f}_'.format(spindex_rms)+spindex_seed_str+'nside_{0:0d}_'.format(nside)+delaygain_err_str+'Tsys_{0:.1f}K_{1:.1f}_MHz_{2:.1f}_MHz'.format(Tsys, freq/1e6, nchan*freq_resolution/1e6) hdulist = fits.open(infile+'.fits') extnames = [hdulist[i].header['EXTNAME'] for i in range(1,len(hdulist))] # Contains the names of different extensions in the FITS file # Generally, You can access an extension by: "quantity = hdulist[name of extension].data" such as shown below labels = hdulist['LABELS'].data['labels'] bl = hdulist['BASELINES'].data timestamps = hdulist['TIMESTAMPS'].data['timestamps'] chans = hdulist['SPECTRAL INFO'].data['frequency'] chan_num = NP.arange(chans.size) vis = hdulist['REAL_FREQ_OBS_VISIBILITY'].data + 1j * hdulist['IMAG_FREQ_OBS_VISIBILITY'].data skyvis = hdulist['REAL_FREQ_SKY_VISIBILITY'].data + 1j * hdulist['IMAG_FREQ_SKY_VISIBILITY'].data bpass = hdulist['BANDPASS'].data blproj = hdulist['PROJ_BASELINES'].data n_timestamps = timestamps.size n_baselines = bl.shape[0] nchan = chans.size wavlen = cspeed/chans ## Uncomment the next few lines if you want coarse band edges flagged # vis = vis * bpass # skyvis = skyvis * bpass ## Uncomment above lines if you want coarse band edges flagged bl_length = NP.sqrt(NP.sum(bl**2, axis=1)) timestamps_table = NP.tile(timestamps.reshape(-1,1,1), (1,n_baselines, nchan)).ravel() labels_table = NP.tile(labels.reshape(1,-1,1), (n_timestamps, 1, nchan)).ravel() blproj_table = blproj[NP.newaxis,...] # now it is 1 x n_baselines x 3 x n_timestamps blproj_table = NP.swapaxes(blproj_table, 0, 3) / wavlen.reshape(1,1,1,-1) # now it is n_timestamps x n_baselines x 3 x nchan u_table = blproj_table[:,:,0,:] # now it is n_timestamps x n_baselines x nchan v_table = blproj_table[:,:,1,:] # now it is n_timestamps x n_baselines x nchan w_table = blproj_table[:,:,2,:] # now it is n_timestamps x n_baselines x nchan u_table = u_table.ravel() v_table = v_table.ravel() w_table = w_table.ravel() uvdist_table = NP.sqrt(u_table**2 + v_table**2 + w_table**2) # uvdist = bl_length.reshape(1,-1,1) / wavlen.reshape(1,1,-1) # uvdist_table = NP.repeat(uvdist, n_timestamps, axis=0).ravel() channum_table = NP.tile(chan_num.reshape(1,1,-1), (n_timestamps, n_baselines, 1)).ravel() vis_amp_table = NP.rollaxis(NP.abs(vis), 2, start=0).ravel() vis_phs_table = NP.rollaxis(NP.angle(vis, deg=True), 2, start=0).ravel() skyvis_amp_table = NP.rollaxis(NP.abs(skyvis), 2, start=0).ravel() skyvis_phs_table = NP.rollaxis(NP.angle(skyvis, deg=True), 2, start=0).ravel() frmts = {} frmts['Timestamp'] = '%s12' frmts['Label'] = '%s' frmts['UVDist'] = '%0.2f' frmts['Chn'] = '%0d' frmts['Amp'] = '%0.3f' frmts['Phs'] = '%-0.2f' frmts['U'] = '%-0.2f' frmts['V'] = '%-0.2f' frmts['W'] = '%-0.2f' ## Test out first with smaller data set only first 5000 lines. Once tested, remove "[:5000]" from everywhere below to write out the entire data set data_dict = {} data_dict['Timestamp'] = timestamps_table[:5000] data_dict['Label'] = labels_table[:5000] data_dict['UVDist'] = uvdist_table[:5000] data_dict['Chn'] = channum_table[:5000] data_dict['U'] = u_table[:5000] data_dict['V'] = v_table[:5000] data_dict['W'] = w_table[:5000] ## Swap the commented and uncommented lines below if you want to switch between noisy and noiseles sky visibilities data_dict['Amp'] = vis_amp_table[:5000] data_dict['Phs'] = vis_phs_table[:5000] # data_dict['Amp'] = skyvis_amp_table[:5000] # data_dict['Phs'] = skyvis_phs_table[:5000] ## Swap the commented and uncommented lines above if you want to switch between noisy and noiseles sky visibilities # Edit the following line to give full path to your desired output text file outfile = infile+'.txt' tbdata = Table(data_dict, names=['Timestamp', 'Label', 'UVDist', 'Chn', 'Amp', 'Phs', 'U', 'V', 'W']) ascii.write(tbdata, output=outfile, format='fixed_width_two_line', formats=frmts, bookend=False, delimiter='|', delimiter_pad = ' ') hdulist.close()
[ "astropy.table.Table", "numpy.sum", "numpy.abs", "numpy.angle", "astropy.io.ascii.write", "numpy.arange", "astropy.io.fits.open", "numpy.swapaxes", "numpy.sqrt" ]
[((7202, 7229), 'astropy.io.fits.open', 'fits.open', (["(infile + '.fits')"], {}), "(infile + '.fits')\n", (7211, 7229), False, 'from astropy.io import fits, ascii\n'), ((7665, 7686), 'numpy.arange', 'NP.arange', (['chans.size'], {}), '(chans.size)\n', (7674, 7686), True, 'import numpy as NP\n'), ((8990, 9041), 'numpy.sqrt', 'NP.sqrt', (['(u_table ** 2 + v_table ** 2 + w_table ** 2)'], {}), '(u_table ** 2 + v_table ** 2 + w_table ** 2)\n', (8997, 9041), True, 'import numpy as NP\n'), ((10707, 10803), 'astropy.table.Table', 'Table', (['data_dict'], {'names': "['Timestamp', 'Label', 'UVDist', 'Chn', 'Amp', 'Phs', 'U', 'V', 'W']"}), "(data_dict, names=['Timestamp', 'Label', 'UVDist', 'Chn', 'Amp', 'Phs',\n 'U', 'V', 'W'])\n", (10712, 10803), False, 'from astropy.table import Table\n'), ((10800, 10935), 'astropy.io.ascii.write', 'ascii.write', (['tbdata'], {'output': 'outfile', 'format': '"""fixed_width_two_line"""', 'formats': 'frmts', 'bookend': '(False)', 'delimiter': '"""|"""', 'delimiter_pad': '""" """'}), "(tbdata, output=outfile, format='fixed_width_two_line', formats=\n frmts, bookend=False, delimiter='|', delimiter_pad=' ')\n", (10811, 10935), False, 'from astropy.io import fits, ascii\n'), ((8256, 8279), 'numpy.sum', 'NP.sum', (['(bl ** 2)'], {'axis': '(1)'}), '(bl ** 2, axis=1)\n', (8262, 8279), True, 'import numpy as NP\n'), ((8549, 8580), 'numpy.swapaxes', 'NP.swapaxes', (['blproj_table', '(0)', '(3)'], {}), '(blproj_table, 0, 3)\n', (8560, 8580), True, 'import numpy as NP\n'), ((9281, 9292), 'numpy.abs', 'NP.abs', (['vis'], {}), '(vis)\n', (9287, 9292), True, 'import numpy as NP\n'), ((9342, 9365), 'numpy.angle', 'NP.angle', (['vis'], {'deg': '(True)'}), '(vis, deg=True)\n', (9350, 9365), True, 'import numpy as NP\n'), ((9418, 9432), 'numpy.abs', 'NP.abs', (['skyvis'], {}), '(skyvis)\n', (9424, 9432), True, 'import numpy as NP\n'), ((9485, 9511), 'numpy.angle', 'NP.angle', (['skyvis'], {'deg': '(True)'}), '(skyvis, deg=True)\n', (9493, 9511), True, 'import numpy as NP\n')]
import pandas as pd from pyqmc.mc import vmc, initial_guess from pyscf import gto, scf, mcscf from pyqmc.slater import PySCFSlater from pyqmc.jastrowspin import JastrowSpin from pyqmc.accumulators import EnergyAccumulator from pyqmc.multiplywf import MultiplyWF from pyqmc.multislater import MultiSlater import numpy as np import time def test_ecp(): mol = gto.M( atom="""C 0 0 0 C 1 0 0 """, ecp="bfd", basis="bfd_vtz", ) mf = scf.RHF(mol).run() nconf = 1000 coords = initial_guess(mol, nconf) thresholds = [1e15, 100, 50, 20, 10, 5, 1] label = ["S", "J", "SJ"] ind = 0 for wf in [ PySCFSlater(mol, mf), JastrowSpin(mol), MultiplyWF(PySCFSlater(mol, mf), JastrowSpin(mol)), ]: wf.recompute(coords) print(label[ind]) ind += 1 for threshold in thresholds: eacc = EnergyAccumulator(mol, threshold) start = time.time() eacc(coords, wf) end = time.time() print("Threshold=", threshold, np.around(end - start, 2), "s") mc = mcscf.CASCI(mf, ncas=4, nelecas=(2, 2)) mc.kernel() label = ["MS"] ind = 0 for wf in [MultiSlater(mol, mf, mc)]: wf.recompute(coords) print(label[ind]) ind += 1 for threshold in thresholds: eacc = EnergyAccumulator(mol, threshold) start = time.time() eacc(coords, wf) end = time.time() print("Threshold=", threshold, np.around(end - start, 2), "s") if __name__ == "__main__": test_ecp()
[ "pyqmc.mc.initial_guess", "time.time", "numpy.around", "pyscf.gto.M", "pyscf.scf.RHF", "pyqmc.jastrowspin.JastrowSpin", "pyqmc.slater.PySCFSlater", "pyqmc.accumulators.EnergyAccumulator", "pyqmc.multislater.MultiSlater", "pyscf.mcscf.CASCI" ]
[((363, 438), 'pyscf.gto.M', 'gto.M', ([], {'atom': '"""C 0 0 0 \n C 1 0 0 \n """', 'ecp': '"""bfd"""', 'basis': '"""bfd_vtz"""'}), '(atom="""C 0 0 0 \n C 1 0 0 \n """, ecp=\'bfd\', basis=\'bfd_vtz\')\n', (368, 438), False, 'from pyscf import gto, scf, mcscf\n'), ((528, 553), 'pyqmc.mc.initial_guess', 'initial_guess', (['mol', 'nconf'], {}), '(mol, nconf)\n', (541, 553), False, 'from pyqmc.mc import vmc, initial_guess\n'), ((1118, 1157), 'pyscf.mcscf.CASCI', 'mcscf.CASCI', (['mf'], {'ncas': '(4)', 'nelecas': '(2, 2)'}), '(mf, ncas=4, nelecas=(2, 2))\n', (1129, 1157), False, 'from pyscf import gto, scf, mcscf\n'), ((666, 686), 'pyqmc.slater.PySCFSlater', 'PySCFSlater', (['mol', 'mf'], {}), '(mol, mf)\n', (677, 686), False, 'from pyqmc.slater import PySCFSlater\n'), ((696, 712), 'pyqmc.jastrowspin.JastrowSpin', 'JastrowSpin', (['mol'], {}), '(mol)\n', (707, 712), False, 'from pyqmc.jastrowspin import JastrowSpin\n'), ((1221, 1245), 'pyqmc.multislater.MultiSlater', 'MultiSlater', (['mol', 'mf', 'mc'], {}), '(mol, mf, mc)\n', (1232, 1245), False, 'from pyqmc.multislater import MultiSlater\n'), ((479, 491), 'pyscf.scf.RHF', 'scf.RHF', (['mol'], {}), '(mol)\n', (486, 491), False, 'from pyscf import gto, scf, mcscf\n'), ((733, 753), 'pyqmc.slater.PySCFSlater', 'PySCFSlater', (['mol', 'mf'], {}), '(mol, mf)\n', (744, 753), False, 'from pyqmc.slater import PySCFSlater\n'), ((755, 771), 'pyqmc.jastrowspin.JastrowSpin', 'JastrowSpin', (['mol'], {}), '(mol)\n', (766, 771), False, 'from pyqmc.jastrowspin import JastrowSpin\n'), ((909, 942), 'pyqmc.accumulators.EnergyAccumulator', 'EnergyAccumulator', (['mol', 'threshold'], {}), '(mol, threshold)\n', (926, 942), False, 'from pyqmc.accumulators import EnergyAccumulator\n'), ((963, 974), 'time.time', 'time.time', ([], {}), '()\n', (972, 974), False, 'import time\n'), ((1022, 1033), 'time.time', 'time.time', ([], {}), '()\n', (1031, 1033), False, 'import time\n'), ((1376, 1409), 'pyqmc.accumulators.EnergyAccumulator', 'EnergyAccumulator', (['mol', 'threshold'], {}), '(mol, threshold)\n', (1393, 1409), False, 'from pyqmc.accumulators import EnergyAccumulator\n'), ((1430, 1441), 'time.time', 'time.time', ([], {}), '()\n', (1439, 1441), False, 'import time\n'), ((1489, 1500), 'time.time', 'time.time', ([], {}), '()\n', (1498, 1500), False, 'import time\n'), ((1077, 1102), 'numpy.around', 'np.around', (['(end - start)', '(2)'], {}), '(end - start, 2)\n', (1086, 1102), True, 'import numpy as np\n'), ((1544, 1569), 'numpy.around', 'np.around', (['(end - start)', '(2)'], {}), '(end - start, 2)\n', (1553, 1569), True, 'import numpy as np\n')]
"""face_detect_mtcnn is used for aligning faces based on mtcnn algorithm. <NAME> and <NAME> and <NAME> and <NAME>, Face Detection and Alignment Using Multitask Cascaded Convolutional Networks, IEEE Signal Processing Letters """ ### The dataset should have the two level structure: ### Such as Casia-Webface, YoutubeFace: ### Casia-Webface: ### |--Subjects : Person0, Person1,.... ### |--images0, images1, images2, images3,... # MIT License from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy import misc import sys import os import argparse import tensorflow as tf import numpy as np import random #### libs of DavaideSanderburg #### sys.path.insert(0, '../../lib/facenet/src') import facenet ###### user custom lib import detect_face def main(args): output_dir = os.path.expanduser(args.output_dir) if not os.path.exists(output_dir): os.makedirs(output_dir) # Store some git revision info in a text file in the log directory src_path,_ = os.path.split(os.path.realpath(__file__)) facenet.store_revision_info(src_path, output_dir, ' '.join(sys.argv)) dataset = facenet.get_dataset(args.input_dir) print('Creating networks and loading parameters') with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) with sess.as_default(): pnet, rnet, onet = detect_face.create_mtcnn(sess, '../../data/') minsize = 20 # minimum size of face threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold factor = 0.709 # scale factor # Add a random key to the filename to allow alignment using multiple processes random_key = np.random.randint(0, high=99999) bounding_boxes_filename = os.path.join(output_dir, 'bounding_boxes_%05d.txt' % random_key) with open(bounding_boxes_filename, "w") as text_file: nrof_images_total = 0 nrof_successfully_aligned = 0 if args.random_order: random.shuffle(dataset) for cls in dataset: output_class_dir = os.path.join(output_dir, cls.name) if not os.path.exists(output_class_dir): os.makedirs(output_class_dir) if args.random_order: random.shuffle(cls.image_paths) for image_path in cls.image_paths: nrof_images_total += 1 filename = os.path.splitext(os.path.split(image_path)[1])[0] output_filename = os.path.join(output_class_dir, filename+'.png') print(image_path) if not os.path.exists(output_filename): try: img = misc.imread(image_path) except (IOError, ValueError, IndexError) as e: errorMessage = '{}: {}'.format(image_path, e) print(errorMessage) else: if img.ndim<2: print('Unable to align "%s"' % image_path) text_file.write('%s\n' % (output_filename)) continue if img.ndim == 2: img = facenet.to_rgb(img) img = img[:,:,0:3] bounding_boxes, landmarks = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor) nrof_faces = bounding_boxes.shape[0] # if nrof_faces>1: # print('landmarks') if nrof_faces>0: det = bounding_boxes[:,0:4] img_size = np.asarray(img.shape)[0:2] if nrof_faces>1: bounding_box_size = (det[:,2]-det[:,0])*(det[:,3]-det[:,1]) img_center = img_size / 2 offsets = np.vstack([ (det[:,0]+det[:,2])/2-img_center[1], (det[:,1]+det[:,3])/2-img_center[0] ]) offset_dist_squared = np.sum(np.power(offsets,2.0),0) index = np.argmax(bounding_box_size-offset_dist_squared*2.0) # some extra weight on the centering det = det[index,:] landmarks = landmarks[:,index] det = np.squeeze(det) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(det[0]-args.margin/2, 0) bb[1] = np.maximum(det[1]-args.margin/2, 0) bb[2] = np.minimum(det[2]+args.margin/2, img_size[1]) bb[3] = np.minimum(det[3]+args.margin/2, img_size[0]) cropped = img[bb[1]:bb[3],bb[0]:bb[2],:] scaled = misc.imresize(cropped, (args.image_size, args.image_size), interp='bilinear') nrof_successfully_aligned += 1 misc.imsave(output_filename, scaled) text_file.write('%s %d %d %d %d\n' % (output_filename, bb[0], bb[1], bb[2], bb[3])) text_file.write('%f %f %f %f %f %f %f %f %f %f\n' % (landmarks[0], landmarks[1], landmarks[2], landmarks[3], landmarks[4],landmarks[5],landmarks[6],landmarks[7],landmarks[8],landmarks[9])) else: print('Unable to align "%s"' % image_path) text_file.write('%s\n' % (output_filename)) print('Total number of images: %d' % nrof_images_total) print('Number of successfully aligned images: %d' % nrof_successfully_aligned) def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('--input_dir', type=str, help='Directory with unaligned images.') parser.add_argument('--output_dir', type=str, help='Directory with aligned face thumbnails.') parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=182) parser.add_argument('--margin', type=int, help='Margin for the crop around the bounding box (height, width) in pixels.', default=44) parser.add_argument('--random_order', help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true') parser.add_argument('--gpu_memory_fraction', type=float, help='Upper bound on the amount of GPU memory that will be used by the process.', default=0.5) return parser.parse_args(argv) if __name__ == '__main__': main(parse_arguments(sys.argv[1:]))
[ "numpy.maximum", "argparse.ArgumentParser", "numpy.argmax", "random.shuffle", "tensorflow.ConfigProto", "numpy.random.randint", "scipy.misc.imsave", "detect_face.detect_face", "tensorflow.GPUOptions", "os.path.join", "facenet.to_rgb", "numpy.power", "os.path.exists", "detect_face.create_mtcnn", "numpy.minimum", "os.path.realpath", "numpy.asarray", "tensorflow.Graph", "scipy.misc.imresize", "numpy.squeeze", "scipy.misc.imread", "numpy.vstack", "os.makedirs", "numpy.zeros", "sys.path.insert", "facenet.get_dataset", "os.path.split", "os.path.expanduser" ]
[((723, 766), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../lib/facenet/src"""'], {}), "(0, '../../lib/facenet/src')\n", (738, 766), False, 'import sys\n'), ((862, 897), 'os.path.expanduser', 'os.path.expanduser', (['args.output_dir'], {}), '(args.output_dir)\n', (880, 897), False, 'import os\n'), ((1187, 1222), 'facenet.get_dataset', 'facenet.get_dataset', (['args.input_dir'], {}), '(args.input_dir)\n', (1206, 1222), False, 'import facenet\n'), ((1867, 1899), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': '(99999)'}), '(0, high=99999)\n', (1884, 1899), True, 'import numpy as np\n'), ((1930, 1994), 'os.path.join', 'os.path.join', (['output_dir', "('bounding_boxes_%05d.txt' % random_key)"], {}), "(output_dir, 'bounding_boxes_%05d.txt' % random_key)\n", (1942, 1994), False, 'import os\n'), ((6012, 6037), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6035, 6037), False, 'import argparse\n'), ((909, 935), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (923, 935), False, 'import os\n'), ((945, 968), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (956, 968), False, 'import os\n'), ((1071, 1097), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1087, 1097), False, 'import os\n'), ((1343, 1414), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'args.gpu_memory_fraction'}), '(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n', (1356, 1414), True, 'import tensorflow as tf\n'), ((1580, 1625), 'detect_face.create_mtcnn', 'detect_face.create_mtcnn', (['sess', '"""../../data/"""'], {}), "(sess, '../../data/')\n", (1604, 1625), False, 'import detect_face\n'), ((2168, 2191), 'random.shuffle', 'random.shuffle', (['dataset'], {}), '(dataset)\n', (2182, 2191), False, 'import random\n'), ((2251, 2285), 'os.path.join', 'os.path.join', (['output_dir', 'cls.name'], {}), '(output_dir, cls.name)\n', (2263, 2285), False, 'import os\n'), ((1296, 1306), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1304, 1306), True, 'import tensorflow as tf\n'), ((1448, 1515), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'gpu_options': 'gpu_options', 'log_device_placement': '(False)'}), '(gpu_options=gpu_options, log_device_placement=False)\n', (1462, 1515), True, 'import tensorflow as tf\n'), ((2305, 2337), 'os.path.exists', 'os.path.exists', (['output_class_dir'], {}), '(output_class_dir)\n', (2319, 2337), False, 'import os\n'), ((2355, 2384), 'os.makedirs', 'os.makedirs', (['output_class_dir'], {}), '(output_class_dir)\n', (2366, 2384), False, 'import os\n'), ((2672, 2721), 'os.path.join', 'os.path.join', (['output_class_dir', "(filename + '.png')"], {}), "(output_class_dir, filename + '.png')\n", (2684, 2721), False, 'import os\n'), ((2443, 2474), 'random.shuffle', 'random.shuffle', (['cls.image_paths'], {}), '(cls.image_paths)\n', (2457, 2474), False, 'import random\n'), ((2777, 2808), 'os.path.exists', 'os.path.exists', (['output_filename'], {}), '(output_filename)\n', (2791, 2808), False, 'import os\n'), ((2865, 2888), 'scipy.misc.imread', 'misc.imread', (['image_path'], {}), '(image_path)\n', (2876, 2888), False, 'from scipy import misc\n'), ((3511, 3585), 'detect_face.detect_face', 'detect_face.detect_face', (['img', 'minsize', 'pnet', 'rnet', 'onet', 'threshold', 'factor'], {}), '(img, minsize, pnet, rnet, onet, threshold, factor)\n', (3534, 3585), False, 'import detect_face\n'), ((2605, 2630), 'os.path.split', 'os.path.split', (['image_path'], {}), '(image_path)\n', (2618, 2630), False, 'import os\n'), ((3391, 3410), 'facenet.to_rgb', 'facenet.to_rgb', (['img'], {}), '(img)\n', (3405, 3410), False, 'import facenet\n'), ((4591, 4606), 'numpy.squeeze', 'np.squeeze', (['det'], {}), '(det)\n', (4601, 4606), True, 'import numpy as np\n'), ((4640, 4667), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': 'np.int32'}), '(4, dtype=np.int32)\n', (4648, 4667), True, 'import numpy as np\n'), ((4704, 4743), 'numpy.maximum', 'np.maximum', (['(det[0] - args.margin / 2)', '(0)'], {}), '(det[0] - args.margin / 2, 0)\n', (4714, 4743), True, 'import numpy as np\n'), ((4776, 4815), 'numpy.maximum', 'np.maximum', (['(det[1] - args.margin / 2)', '(0)'], {}), '(det[1] - args.margin / 2, 0)\n', (4786, 4815), True, 'import numpy as np\n'), ((4848, 4897), 'numpy.minimum', 'np.minimum', (['(det[2] + args.margin / 2)', 'img_size[1]'], {}), '(det[2] + args.margin / 2, img_size[1])\n', (4858, 4897), True, 'import numpy as np\n'), ((4930, 4979), 'numpy.minimum', 'np.minimum', (['(det[3] + args.margin / 2)', 'img_size[0]'], {}), '(det[3] + args.margin / 2, img_size[0])\n', (4940, 4979), True, 'import numpy as np\n'), ((5082, 5159), 'scipy.misc.imresize', 'misc.imresize', (['cropped', '(args.image_size, args.image_size)'], {'interp': '"""bilinear"""'}), "(cropped, (args.image_size, args.image_size), interp='bilinear')\n", (5095, 5159), False, 'from scipy import misc\n'), ((5247, 5283), 'scipy.misc.imsave', 'misc.imsave', (['output_filename', 'scaled'], {}), '(output_filename, scaled)\n', (5258, 5283), False, 'from scipy import misc\n'), ((3875, 3896), 'numpy.asarray', 'np.asarray', (['img.shape'], {}), '(img.shape)\n', (3885, 3896), True, 'import numpy as np\n'), ((4139, 4244), 'numpy.vstack', 'np.vstack', (['[(det[:, 0] + det[:, 2]) / 2 - img_center[1], (det[:, 1] + det[:, 3]) / 2 -\n img_center[0]]'], {}), '([(det[:, 0] + det[:, 2]) / 2 - img_center[1], (det[:, 1] + det[:,\n 3]) / 2 - img_center[0]])\n', (4148, 4244), True, 'import numpy as np\n'), ((4353, 4409), 'numpy.argmax', 'np.argmax', (['(bounding_box_size - offset_dist_squared * 2.0)'], {}), '(bounding_box_size - offset_dist_squared * 2.0)\n', (4362, 4409), True, 'import numpy as np\n'), ((4288, 4310), 'numpy.power', 'np.power', (['offsets', '(2.0)'], {}), '(offsets, 2.0)\n', (4296, 4310), True, 'import numpy as np\n')]
import numpy as np import xml.dom.minidom from shapely.ops import cascaded_union from shapely.geometry import Polygon from itertools import combinations class EnvOpenx(): """根据OpenScenario文件进行测试,目前仅根据轨迹数据进行回放测试 """ def __init__(self): self.car_length = 4.924 self.car_width = 1.872 self.l = 3 # 车辆轴距,单位:m self.dt = 0.04 # 每秒25帧 self.metric = 'danger' self.vehicle_array = None #存储当前场景车辆信息 self.vehicle_list = None self.max_t = 0 #纪录场景持续的时间 def init(self, path=None): if not path: path = './test_scenario/follow1.xosc' else: assert(path.split('.')[-1] == "xosc") # 读取OpenScenario文件 self.data = xml.dom.minidom.parse(path).documentElement # 记录每辆车的轨迹,存在dic里面 self.traj = {} for act in self.data.getElementsByTagName('Act'): name = act.getAttribute('name') self.traj[name] = {} for point in act.getElementsByTagName('Vertex'): t = point.getAttribute('time') t = round(float(t), 2) if t > self.max_t: self.max_t = t loc = point.getElementsByTagName('WorldPosition')[0] self.traj[name][t] = {} self.traj[name][t]['x'] = loc.getAttribute('x') self.traj[name][t]['y'] = loc.getAttribute('y') # 计时器归0, 测试结果归0 self.t = round(0, 2) self.result = 0 self.vehicle_array = np.zeros((1, len(self.traj.keys()), 6)) self.vehicle_list = list(self.traj.keys()) self.vehicle_list[0] = 'ego' # 将所有车辆设置到0时刻位置 i = 0 for vehi in self.traj.keys(): if self.t in self.traj[vehi].keys(): self.vehicle_array[:,i,0] = self.traj[vehi][self.t]['x'] self.vehicle_array[:,i,1] = self.traj[vehi][self.t]['y'] self.vehicle_array[:,i,2] = 0 # speed 没有数值 self.vehicle_array[:,i,3] = 0 # 转向角 没有数值 self.vehicle_array[:,i,4] = self.car_length self.vehicle_array[:,i,5] = self.car_width i += 1 state = self.get_state() return state def update(self, action): # 根据前向欧拉更新,根据旧速度更新位置,然后更新速度 ##############更新时间步 # 前进一个时间步长 self.t += self.dt ###############更新本车信息 a, rot = action # 首先根据旧速度更新本车位置 # 更新X坐标 self.vehicle_array[:, 0, 0] += self.vehicle_array[:, 0, 2] * self.dt * np.cos( self.vehicle_array[:, 0, 3]) # *np.pi/180 # 更新Y坐标 self.vehicle_array[:, 0, 1] += self.vehicle_array[:, 0, 2] * self.dt * np.sin( self.vehicle_array[:, 0, 3]) # *np.pi/180 # 更新本车转向角 self.vehicle_array[:, 0, 3] += self.vehicle_array[:, 0, 2] / self.l * np.tan(rot) * self.dt # 更新本车速度 self.vehicle_array[:, 0, 2] += a * self.dt self.vehicle_array[:, 0, 2] = np.clip(self.vehicle_array[:, 0, 2], 0, 1e5) ##############更新背景车信息 t = round(float(self.t), 2) i = 1 for vehi in self.vehicle_list[1:]: #对于除本车以外的车辆,直接从字典中取数据 if t in self.traj[vehi].keys(): self.vehicle_array[:,i,0] = self.traj[vehi][t]['x'] self.vehicle_array[:,i,1] = self.traj[vehi][t]['y'] self.vehicle_array[:,i,2] = 0 # speed 暂时没有数值 self.vehicle_array[:,i,3] = 0 # 转向角 暂时没有数值 i += 1 judge_value,done = self.judge() # 如果此次更新完,时间已走完,则终止测试 if round(float(self.t), 2) >= self.max_t: done = 1 return judge_value,done def judge(self): if self.metric in ['danger','danger_union','danger_v','dqn','minimum_adjusted_TTC']: result = 0 done = 0 intersection = [] poly_zip = [self.get_poly(param)[0] for param in self.vehicle_list if self.vehicle_array[0, self.vehicle_list.index(param), 0]>5] intersection = cascaded_union( [a.intersection(b) for a, b in combinations(poly_zip, 2)] ).area # print(self.vehicle_array) # print(intersection) if self.metric == "danger": if intersection > 0: result = 1 done = 1 return result,done def get_state(self): '''返回所有数据 ''' state = self.vehicle_array.copy() return state def step(self,action): reward, done = self.update(action) obeservation = self.get_state() return obeservation, reward, done, None def get_poly(self, name): """根据车辆名字获取对应的,符合shapely库要求的矩形。 这是为了方便地使用shapely库判断场景中的车辆是否发生碰撞 :param name:车辆的名字 :return: 一列对应的shapely图形 """ ego = self.vehicle_array[:, self.vehicle_list.index(name), :].copy() alpha = np.arctan(ego[:, 5] / ego[:, 4]) diagonal = np.sqrt(ego[:, 5] ** 2 + ego[:, 4] ** 2) poly_list = [] x0 = ego[:, 0] + diagonal / 2 * np.cos(ego[:, 3] + alpha) y0 = ego[:, 1] + diagonal / 2 * np.sin(ego[:, 3] + alpha) x2 = ego[:, 0] - diagonal / 2 * np.cos(ego[:, 3] + alpha) y2 = ego[:, 1] - diagonal / 2 * np.sin(ego[:, 3] + alpha) x1 = ego[:, 0] + diagonal / 2 * np.cos(ego[:, 3] - alpha) y1 = ego[:, 1] + diagonal / 2 * np.sin(ego[:, 3] - alpha) x3 = ego[:, 0] - diagonal / 2 * np.cos(ego[:, 3] - alpha) y3 = ego[:, 1] - diagonal / 2 * np.sin(ego[:, 3] - alpha) for i in range(x0.shape[0]): poly_list += [Polygon(((x0[i], y0[i]), (x1[i], y1[i]), (x2[i], y2[i]), (x3[i], y3[i]), (x0[i], y0[i]))).convex_hull] return poly_list
[ "shapely.geometry.Polygon", "numpy.clip", "itertools.combinations", "numpy.sin", "numpy.tan", "numpy.cos", "numpy.arctan", "numpy.sqrt" ]
[((3125, 3174), 'numpy.clip', 'np.clip', (['self.vehicle_array[:, 0, 2]', '(0)', '(100000.0)'], {}), '(self.vehicle_array[:, 0, 2], 0, 100000.0)\n', (3132, 3174), True, 'import numpy as np\n'), ((5114, 5146), 'numpy.arctan', 'np.arctan', (['(ego[:, 5] / ego[:, 4])'], {}), '(ego[:, 5] / ego[:, 4])\n', (5123, 5146), True, 'import numpy as np\n'), ((5166, 5206), 'numpy.sqrt', 'np.sqrt', (['(ego[:, 5] ** 2 + ego[:, 4] ** 2)'], {}), '(ego[:, 5] ** 2 + ego[:, 4] ** 2)\n', (5173, 5206), True, 'import numpy as np\n'), ((2597, 2632), 'numpy.cos', 'np.cos', (['self.vehicle_array[:, 0, 3]'], {}), '(self.vehicle_array[:, 0, 3])\n', (2603, 2632), True, 'import numpy as np\n'), ((2799, 2834), 'numpy.sin', 'np.sin', (['self.vehicle_array[:, 0, 3]'], {}), '(self.vehicle_array[:, 0, 3])\n', (2805, 2834), True, 'import numpy as np\n'), ((2997, 3008), 'numpy.tan', 'np.tan', (['rot'], {}), '(rot)\n', (3003, 3008), True, 'import numpy as np\n'), ((5270, 5295), 'numpy.cos', 'np.cos', (['(ego[:, 3] + alpha)'], {}), '(ego[:, 3] + alpha)\n', (5276, 5295), True, 'import numpy as np\n'), ((5336, 5361), 'numpy.sin', 'np.sin', (['(ego[:, 3] + alpha)'], {}), '(ego[:, 3] + alpha)\n', (5342, 5361), True, 'import numpy as np\n'), ((5402, 5427), 'numpy.cos', 'np.cos', (['(ego[:, 3] + alpha)'], {}), '(ego[:, 3] + alpha)\n', (5408, 5427), True, 'import numpy as np\n'), ((5468, 5493), 'numpy.sin', 'np.sin', (['(ego[:, 3] + alpha)'], {}), '(ego[:, 3] + alpha)\n', (5474, 5493), True, 'import numpy as np\n'), ((5534, 5559), 'numpy.cos', 'np.cos', (['(ego[:, 3] - alpha)'], {}), '(ego[:, 3] - alpha)\n', (5540, 5559), True, 'import numpy as np\n'), ((5600, 5625), 'numpy.sin', 'np.sin', (['(ego[:, 3] - alpha)'], {}), '(ego[:, 3] - alpha)\n', (5606, 5625), True, 'import numpy as np\n'), ((5666, 5691), 'numpy.cos', 'np.cos', (['(ego[:, 3] - alpha)'], {}), '(ego[:, 3] - alpha)\n', (5672, 5691), True, 'import numpy as np\n'), ((5732, 5757), 'numpy.sin', 'np.sin', (['(ego[:, 3] - alpha)'], {}), '(ego[:, 3] - alpha)\n', (5738, 5757), True, 'import numpy as np\n'), ((5821, 5915), 'shapely.geometry.Polygon', 'Polygon', (['((x0[i], y0[i]), (x1[i], y1[i]), (x2[i], y2[i]), (x3[i], y3[i]), (x0[i], y0[i])\n )'], {}), '(((x0[i], y0[i]), (x1[i], y1[i]), (x2[i], y2[i]), (x3[i], y3[i]), (\n x0[i], y0[i])))\n', (5828, 5915), False, 'from shapely.geometry import Polygon\n'), ((4278, 4303), 'itertools.combinations', 'combinations', (['poly_zip', '(2)'], {}), '(poly_zip, 2)\n', (4290, 4303), False, 'from itertools import combinations\n')]
import numpy as np import sys import os import string import struct def converter_np2r(d, name, data_save): save_name='data'+name + ".bin" # create a binary file binfile = file(os.path.join(data_save,save_name), 'wb') # and write out two integers with the row and column dimension header = struct.pack('2I', d.shape[0], d.shape[1]) binfile.write(header) # then loop over columns and write each for i in range(d.shape[1]): data = struct.pack('%id' % d.shape[0], *d[:,i]) binfile.write(data) binfile.close() if __name__=="__main__": data_path=sys.argv[1] data_save=sys.argv[2] name=string.split(os.path.basename(data_path),'.npy' )[0] d=np.load(data_path) converter_np2r(d, name, data_save)
[ "numpy.load", "os.path.join", "struct.pack", "os.path.basename" ]
[((424, 465), 'struct.pack', 'struct.pack', (['"""2I"""', 'd.shape[0]', 'd.shape[1]'], {}), "('2I', d.shape[0], d.shape[1])\n", (435, 465), False, 'import struct\n'), ((825, 843), 'numpy.load', 'np.load', (['data_path'], {}), '(data_path)\n', (832, 843), True, 'import numpy as np\n'), ((261, 295), 'os.path.join', 'os.path.join', (['data_save', 'save_name'], {}), '(data_save, save_name)\n', (273, 295), False, 'import os\n'), ((583, 624), 'struct.pack', 'struct.pack', (["('%id' % d.shape[0])", '*d[:, i]'], {}), "('%id' % d.shape[0], *d[:, i])\n", (594, 624), False, 'import struct\n'), ((778, 805), 'os.path.basename', 'os.path.basename', (['data_path'], {}), '(data_path)\n', (794, 805), False, 'import os\n')]
from argparse import ArgumentParser from numpy import arange, array, atleast_2d, diag, hstack, ones, where from os import mkdir from os.path import isdir,isfile from pickle import load, dump from pandas import read_csv from scipy.integrate import solve_ivp from time import time from multiprocessing import Pool from model.preprocessing import ( estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector) from model.specs import SINGLE_AGE_UK_SPEC, SINGLE_AGE_SEIR_SPEC_FOR_FITTING from model.common import SEIRRateEquations from model.imports import NoImportModel from examples.temp_bubbles.common import ( build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged) '''If there is not already a results folder assigned to the outputs from this script, create one now.''' if isdir('outputs/temp_bubbles') is False: mkdir('outputs/temp_bubbles') SPEC = {**SINGLE_AGE_UK_SPEC, **SINGLE_AGE_SEIR_SPEC_FOR_FITTING} X0 = 3 * 1e-2 # Growth rate estimate for mid-December 2020 from ONS ATOL = 1e-16 # IVP solver tolerance NO_COMPARTMENTS = 4 # We use an SEIR model, hence 4 compartments MAX_MERGED_SIZE = 10 # We only allow merges where total individuals is at most 12 MAX_UNMERGED_SIZE = 4 # As usual, we model the chunk of the population in households of size 6 or fewer GUEST_TRANS_SCALING = 1 # This is strength of guest-host interactions relative to host-host interactions growth_rate = X0 prev = 1e-2 starting_immunity = 1e-1 comp_dist = read_csv( 'inputs/england_hh_size_dist.csv', header=0).to_numpy().squeeze() comp_dist = comp_dist[:MAX_UNMERGED_SIZE] comp_dist = comp_dist/sum(comp_dist) max_hh_size = len(comp_dist) composition_list = atleast_2d(arange(1, max_hh_size+1)).T if isfile('outputs/temp_bubbles/beta_ext.pkl') is True: with open('outputs/temp_bubbles/beta_ext.pkl', 'rb') as f: beta_ext = load(f) else: growth_rate = X0 model_input_to_fit = SEIRInput(SPEC, composition_list, comp_dist) household_population_to_fit = HouseholdPopulation( composition_list, comp_dist, model_input_to_fit) rhs_to_fit = SEIRRateEquations(model_input_to_fit, household_population_to_fit, NoImportModel(4,1)) beta_ext = estimate_beta_ext(household_population_to_fit, rhs_to_fit, growth_rate) with open('outputs/temp_bubbles/beta_ext.pkl', 'wb') as f: dump(beta_ext, f) def create_unmerged_context(p): return UnmergedContext(*p) class UnmergedContext: def __init__(self, i, density_exponent, t_start, t_end, merge_start): unmerged_input = SEIRInput(SPEC, composition_list, comp_dist) unmerged_input.density_expo = density_exponent unmerged_input.k_home = ( unmerged_input.ave_hh_size ** density_exponent) * unmerged_input.k_home unmerged_input.k_ext = beta_ext * unmerged_input.k_ext self.input = unmerged_input self.population = HouseholdPopulation( composition_list, comp_dist, unmerged_input, True) self.rhs = SEIRRateEquations( unmerged_input, self.population, NoImportModel(NO_COMPARTMENTS, 1)) self.recovered_states = where( ((self.rhs.states_sus_only + self.rhs.states_rec_only).sum(axis=1) == self.population.states.sum(axis=1)) & ((self.rhs.states_rec_only).sum(axis=1) > 0))[0] self.H0 = make_initial_condition_by_eigenvector(growth_rate, unmerged_input, self.population, self.rhs, prev, starting_immunity) self.tspan = (t_start, merge_start) solution = solve_ivp( self.rhs, self.tspan, self.H0, first_step=0.001, atol=ATOL) baseline_time = solution.t self.baseline_H = solution.y self.baseline_H0 = self.baseline_H[:, -1] tspan = (merge_start, t_end) solution = solve_ivp( self.rhs, tspan, self.baseline_H[:, -1], first_step=0.001, atol=ATOL) baseline_time = hstack((baseline_time, solution.t)) baseline_H = hstack((self.baseline_H, solution.y)) baseline_S = baseline_H.T.dot( self.population.states[:, 0])/unmerged_input.ave_hh_size baseline_E = baseline_H.T.dot( self.population.states[:, 1])/unmerged_input.ave_hh_size baseline_I = baseline_H.T.dot( self.population.states[:, 2])/unmerged_input.ave_hh_size baseline_R = baseline_H.T.dot( self.population.states[:, 3])/unmerged_input.ave_hh_size with open('baseline.pkl', 'wb') as f: dump( ( self.population, baseline_H, baseline_time, baseline_S, baseline_E, baseline_I, baseline_R ), f) def unpack_paramas_and_run_merge(p): '''This function enables multi-argument parallel run.''' return run_merge(*p) def create_merged_systems(p): return MergedSystems(*p) class MergedSystems: def __init__( self, merged_exp, merged_comp_list_2, merged_comp_dist_2, merged_comp_list_3, merged_comp_dist_3 ): merged_input2 = SEIRInput( SPEC, composition_list, comp_dist) merged_input2.composition_list = merged_comp_list_2 merged_input2.composition_distribution = merged_comp_dist_2 merged_input2 = merge_hh_inputs(merged_input2, 2, GUEST_TRANS_SCALING) merged_input2.density_expo = merged_exp self.merged_input2 = merged_input2 self.merged_population2 = HouseholdPopulation( merged_comp_list_2, merged_comp_dist_2, merged_input2, True) self.rhs_merged2 = SEIRRateEquations( merged_input2, self.merged_population2, NoImportModel(NO_COMPARTMENTS, 2)) merged_input3 = SEIRInput( SPEC, composition_list, comp_dist) merged_input3.composition_list = merged_comp_list_3 merged_input3.composition_distribution = merged_comp_dist_3 merged_input3 = merge_hh_inputs(merged_input3, 3, GUEST_TRANS_SCALING) merged_input3.density_expo = merged_exp self.merged_input3 = merged_input3 self.merged_population3 = HouseholdPopulation( merged_comp_list_3, merged_comp_dist_3, merged_input3, True) self.rhs_merged3 = SEIRRateEquations( merged_input3, self.merged_population3, NoImportModel(NO_COMPARTMENTS, 3)) def run_merge( i, j, pairings_2, pairings_3, hh_dimension, unmerged, merged, state_match_2, state_match_3, t_start, t_end, merge_start, merge_end ): '''This function runs a merge simulation for specified parameters.''' this_iteration_start = time() # STRATEGIES: 1 is form triangles for 2 days, 2 is form pair on # 25th and again on 26th, 3 is 1 plus pair on new year's, 4 is 2 # plus pair on new year's # Strategy 0 is the actual policy of a 2-household bubble on Christmas day only merged_population2 = merged.merged_population2 merged_population3 = merged.merged_population3 rhs_merged2 = merged.rhs_merged2 rhs_merged3 = merged.rhs_merged3 t_merge_0, \ H_merge_0, \ t_postmerge_0, \ H_postmerge_0 = \ simulate_merge2( unmerged.population, merged_population2, unmerged.rhs, rhs_merged2, hh_dimension, pairings_2, state_match_2, [1], 0, unmerged.baseline_H0, merge_start, merge_end) solution = solve_ivp( unmerged.rhs, (merge_start + 1, t_end), H_postmerge_0[:, -1], first_step=0.001, atol=ATOL) t_postmerge_0 = hstack( (t_postmerge_0, solution.t)) H_postmerge_0 = hstack( (H_postmerge_0, solution.y)) t_merge_1, \ H_merge_1, \ t_postmerge_1, \ H_postmerge_1 = \ simulate_merge3( unmerged.population, merged_population3, unmerged.rhs, rhs_merged3, hh_dimension, pairings_3, state_match_3, [2], 0, unmerged.baseline_H0, merge_start, merge_end) t_merge_3, \ H_merge_3, \ t_postmerge_3, \ H_postmerge_3 = \ simulate_merge2( unmerged.population, merged_population2, unmerged.rhs, rhs_merged2, hh_dimension, pairings_2, state_match_2, [1], 0, H_postmerge_1[:, -1], merge_end, t_end) solution = solve_ivp( unmerged.rhs, (merge_end, t_end), H_postmerge_1[:, -1], first_step=0.001, atol=ATOL) t_postmerge_1 = hstack( (t_postmerge_1, solution.t)) H_postmerge_1 = hstack( (H_postmerge_1, solution.y)) t_merge_2, \ H_merge_2, \ t_postmerge_2, \ H_postmerge_2 = \ simulate_merge2( unmerged.population, merged_population2, unmerged.rhs, rhs_merged2, hh_dimension, pairings_2, state_match_2, [1, 1], 1, unmerged.baseline_H0, merge_start, merge_end) t_merge_4, \ H_merge_4, \ t_postmerge_4, \ H_postmerge_4 = \ simulate_merge2( unmerged.population, merged_population2, unmerged.rhs, rhs_merged2, hh_dimension, pairings_2, state_match_2, [1], 0, H_postmerge_2[:, -1], merge_end, t_end) solution = solve_ivp( unmerged.rhs, (merge_end, t_end), H_postmerge_2[:, -1], first_step=0.001, atol=ATOL) t_postmerge_2 = hstack(( t_postmerge_2, solution.t)) H_postmerge_2 = hstack(( H_postmerge_2, solution.y)) merge_I_0 = (1/2) * H_merge_0.T.dot( merged_population2.states[:, 2] + merged_population2.states[:, 6])/unmerged.input.ave_hh_size postmerge_I_0 = H_postmerge_0.T.dot(unmerged.population.states[:, 2])/unmerged.input.ave_hh_size peaks_0 = max(hstack((merge_I_0, postmerge_I_0))) merge_R_0 = (1/2) * H_merge_0.T.dot( merged_population2.states[:, 3] + merged_population2.states[:, 7])/unmerged.input.ave_hh_size postmerge_R_0 = H_postmerge_0.T.dot(unmerged.population.states[:, 3])/unmerged.input.ave_hh_size R_end_0 = postmerge_R_0[-1] R_end_vec_0 = H_postmerge_0[:, -1] * \ unmerged.population.states[:, 3] ar_0 = (unmerged.population.state_to_comp_matrix.T.dot(R_end_vec_0)) ar_0 = unmerged.input.composition_distribution.dot( ar_0 / unmerged.input.hh_size_list) hh_prop_0 = H_postmerge_0[unmerged.recovered_states, -1].sum() merge_I_1 = (1/3) * H_merge_1.T.dot( merged_population3.states[:, 2] + merged_population3.states[:, 6] + merged_population3.states[:, 10])/unmerged.input.ave_hh_size postmerge_I_1 = H_postmerge_1.T.dot(unmerged.population.states[:, 2])/unmerged.input.ave_hh_size peaks_1 = max(hstack((merge_I_1, postmerge_I_1))) merge_R_1 = (1/3) * H_merge_1.T.dot( merged_population3.states[:, 3] + merged_population3.states[:, 7] + merged_population3.states[:,11])/unmerged.input.ave_hh_size postmerge_R_1 = H_postmerge_1.T.dot(unmerged.population.states[:, 3])/unmerged.input.ave_hh_size R_end_1 = postmerge_R_1[-1] R_end_vec_1 = H_postmerge_1[:, -1] * \ unmerged.population.states[:, 3] ar_1 = (unmerged.population.state_to_comp_matrix.T.dot(R_end_vec_1)) ar_1 = unmerged.input.composition_distribution.dot( ar_1 / unmerged.input.hh_size_list) hh_prop_1 = H_postmerge_1[unmerged.recovered_states, -1].sum() merge_I_2 = (1/2) * H_merge_2.T.dot( merged_population2.states[:, 2] + merged_population2.states[:, 6])/unmerged.input.ave_hh_size postmerge_I_2 = H_postmerge_2.T.dot(unmerged.population.states[:, 2])/unmerged.input.ave_hh_size peaks_2 = max(hstack((merge_I_2, postmerge_I_2))) merge_R_2 = (1/2) * H_merge_2.T.dot( merged_population2.states[:, 3] + merged_population2.states[:, 7])/unmerged.input.ave_hh_size postmerge_R_2 = H_postmerge_2.T.dot(unmerged.population.states[:, 3])/unmerged.input.ave_hh_size R_end_2 = postmerge_R_2[-1] R_end_vec_2 = H_postmerge_2[:, -1] * \ unmerged.population.states[:, 3] ar_2 = (unmerged.population.state_to_comp_matrix.T.dot(R_end_vec_2)) ar_2 = unmerged.input.composition_distribution.dot( ar_2 / unmerged.input.hh_size_list) hh_prop_2 = H_postmerge_2[unmerged.recovered_states, -1].sum() merge_I_3 = (1/2) * H_merge_3.T.dot( merged_population2.states[:, 2] + merged_population2.states[:, 6])/unmerged.input.ave_hh_size postmerge_I_3 = H_postmerge_3.T.dot(unmerged.population.states[:, 2])/unmerged.input.ave_hh_size peaks_3 = max(hstack((merge_I_3, postmerge_I_3))) merge_R_3 = (1/2) * H_merge_3.T.dot( merged_population2.states[:, 3] + merged_population2.states[:, 7])/unmerged.input.ave_hh_size postmerge_R_3 = H_postmerge_3.T.dot(unmerged.population.states[:, 3])/unmerged.input.ave_hh_size R_end_3 = postmerge_R_3[-1] R_end_vec_3 = H_postmerge_3[:, -1] * \ unmerged.population.states[:, 3] ar_3 = (unmerged.population.state_to_comp_matrix.T.dot(R_end_vec_3)) ar_3 = unmerged.input.composition_distribution.dot( ar_3 / unmerged.input.hh_size_list) hh_prop_3 = H_postmerge_3[unmerged.recovered_states, -1].sum() merge_I_4 = (1/2) * H_merge_4.T.dot( merged_population2.states[:, 2] + merged_population2.states[:, 6])/unmerged.input.ave_hh_size postmerge_I_4 = H_postmerge_4.T.dot(unmerged.population.states[:, 2])/unmerged.input.ave_hh_size peaks_4 = max(hstack((merge_I_4, postmerge_I_4))) merge_R_4 = (1/2) * H_merge_4.T.dot( merged_population2.states[:, 3] + merged_population2.states[:, 7])/unmerged.input.ave_hh_size postmerge_R_4 = H_postmerge_4.T.dot(unmerged.population.states[:, 3])/unmerged.input.ave_hh_size R_end_4 = postmerge_R_4[-1] R_end_vec_4 = H_postmerge_4[:, -1] * \ unmerged.population.states[:, 3] ar_4 = (unmerged.population.state_to_comp_matrix.T.dot(R_end_vec_4)) ar_4 = unmerged.input.composition_distribution.dot( ar_4 / unmerged.input.hh_size_list) hh_prop_4 = H_postmerge_4[unmerged.recovered_states, -1].sum() return [peaks_0, R_end_0, ar_0, hh_prop_0, peaks_1, R_end_1, ar_1, hh_prop_1, peaks_2, R_end_2, ar_2, hh_prop_2, peaks_3, R_end_3, ar_3, hh_prop_3, peaks_4, R_end_4, ar_4, hh_prop_4] def simulate_merge2( unmerged_population, merged_population, rhs_unmerged, rhs_merged, hh_dimension, pairings, state_match, duration_list, switches, premerge_H0, t0, t_end): hh_to_merge = 2 for switch in range(switches+1): # print('Initialising merge number',switch,'...') H0 = initialise_merged_system( premerge_H0, unmerged_population, merged_population, state_match) tspan = (t0, t0 + duration_list[switch]) # print('Integrating over merge period number',switch,'...') solution = solve_ivp( rhs_merged, tspan, H0/sum(H0), first_step=0.001, atol=ATOL) # print('Integration over merge period took',time()-t_mer,'seconds.') temp_time = solution.t temp_H = solution.y t0 = t0 + duration_list[switch] premerge_H0 = demerged_initial_condition( temp_H[:, -1], unmerged_population, merged_population, hh_dimension, pairings, hh_to_merge, 4) if switch == 0: merge_time = temp_time merge_H = temp_H else: merge_time = hstack((merge_time, temp_time)) merge_H = hstack((merge_H, temp_H)) # print('Initialising post-merge period...') H0 = demerged_initial_condition( merge_H[:, -1], unmerged_population, merged_population, hh_dimension, pairings, hh_to_merge, 4) tspan = (t0, t_end) # print('Integrating over post-merge period...') solution = solve_ivp( rhs_unmerged, tspan, H0, first_step=0.001, atol=ATOL) # print('Integration over post-merge period took',time()-t_post,'seconds.') postmerge_time = solution.t postmerge_H = solution.y return merge_time, merge_H, postmerge_time, postmerge_H def simulate_merge3( unmerged_population, merged_population, rhs_unmerged, rhs_merged, hh_dimension, pairings, state_match, duration_list, switches, premerge_H0, t0, t_end): hh_to_merge = 3 for switch in range(switches+1): # print('Initialising merge number',switch,'...') H0 = initialise_merged_system( premerge_H0, unmerged_population, merged_population, state_match) tspan = (t0, t0 + duration_list[switch]) # print('Integrating over merge period number',switch,'...') # t_mer = time() solution = solve_ivp( rhs_merged, tspan, H0/sum(H0), first_step=0.001, atol=ATOL) # print('Integration over merge period took',time()-t_mer,'seconds.') temp_time = solution.t temp_H = solution.y t0 = t0 + duration_list[switch] premerge_H0 = demerged_initial_condition( temp_H[:, -1], unmerged_population, merged_population, hh_dimension, pairings, hh_to_merge, 4) if switch == 0: merge_time = temp_time merge_H = temp_H else: merge_time = hstack(( merge_time, temp_time)) merge_H = hstack((merge_H, temp_H)) # print('Initialising post-merge period...') H0 = demerged_initial_condition( merge_H[:, -1], unmerged_population, merged_population, hh_dimension, pairings, hh_to_merge, 4) tspan = (t0, t_end) # print('Integrating over post-merge period...') # t_post = time() solution = solve_ivp( rhs_unmerged, tspan, H0, first_step=0.001, atol=ATOL) # print('Integration over post-merge period took',time()-t_post,'seconds.') postmerge_time = solution.t postmerge_H = solution.y return merge_time, merge_H, postmerge_time, postmerge_H def main(no_of_workers, unmerged_exponent_vals, merged_exponent_vals): unmerged_exponents = arange(unmerged_exponent_vals[0], unmerged_exponent_vals[1], unmerged_exponent_vals[2]) merged_exponents = arange(merged_exponent_vals[0], merged_exponent_vals[1], merged_exponent_vals[2]) if isfile('outputs/temp_bubbles/threewise_merge_comps.pkl') is True: with open('outputs/temp_bubbles/threewise_merge_comps.pkl', 'rb') as f: print('Loading merged composition distribution...') merged_comp_list_2, \ merged_comp_dist_2, \ pairings_2, \ merged_comp_list_3, \ merged_comp_dist_3, \ hh_dimension, \ pairings_3 = load(f) else: print('Building merged composition distribution...') merged_comp_list_2, \ merged_comp_dist_2, \ hh_dimension, \ pairings_2 = build_mixed_compositions_pairwise( composition_list, comp_dist) merged_comp_list_3, \ merged_comp_dist_3, \ hh_dimension, \ pairings_3 = build_mixed_compositions_threewise( composition_list, comp_dist, MAX_MERGED_SIZE) with open('outputs/temp_bubbles/threewise_merge_comps.pkl', 'wb') as f: dump( ( merged_comp_list_2, merged_comp_dist_2, pairings_2, merged_comp_list_3, merged_comp_dist_3, hh_dimension, pairings_3 ), f) # December 1st t0 = 335.0 # December 25th merge_start = 359.0 merge_end = 365.0 # Continue running projections to end of Jan t_end = 396 params = [] for i, e in enumerate(unmerged_exponents): params.append((i, e, t0, t_end, merge_start)) with Pool(no_of_workers) as pool: unmerged_results = pool.map(create_unmerged_context, params) params = [] for e in merged_exponents: params.append(( e, merged_comp_list_2, merged_comp_dist_2, merged_comp_list_3, merged_comp_dist_3 )) with Pool(no_of_workers) as pool: merged_populations = pool.map(create_merged_systems, params) state_match_2 = match_merged_states_to_unmerged( unmerged_results[0].population, merged_populations[0].merged_population2, pairings_2, 2, NO_COMPARTMENTS) state_match_3 = match_merged_states_to_unmerged( unmerged_results[0].population, merged_populations[0].merged_population3, pairings_3, 3, NO_COMPARTMENTS) params = [] for i, ei in enumerate(unmerged_exponents): for j, ej in enumerate(merged_exponents): params.append(( i, j, pairings_2, pairings_3, hh_dimension, unmerged_results[i], merged_populations[j], state_match_2, state_match_3, t0, t_end, merge_start, merge_end)) with Pool(no_of_workers) as pool: results = pool.map(unpack_paramas_and_run_merge, params) peak_data0 = array([r[0] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) end_data0 = array([r[1] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) ar_data0 = array([r[2] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) hh_prop_data0 = array([r[3] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) peak_data1= array([r[4] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) end_data1 = array([r[5] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) ar_data1 = array([r[6] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) hh_prop_data1 = array([r[7] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) peak_data2 = array([r[8] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) end_data2 = array([r[9] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) ar_data2 = array([r[10] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) hh_prop_data2 = array([r[11] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) peak_data3 = array([r[12] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) end_data3 = array([r[13] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) ar_data3 = array([r[14] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) hh_prop_data3 = array([r[15] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) peak_data4 = array([r[16] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) end_data4 = array([r[17] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) ar_data4 = array([r[18] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) hh_prop_data4 = array([r[19] for r in results]).reshape( len(unmerged_exponents), len(merged_exponents)) fname = 'outputs/temp_bubbles/results.pkl' with open(fname, 'wb') as f: dump( (peak_data0, end_data0, ar_data0, hh_prop_data0, peak_data1, end_data1, ar_data1, hh_prop_data1, peak_data2, end_data2, ar_data2, hh_prop_data2, peak_data3, end_data3, ar_data3, hh_prop_data3, peak_data4, end_data4, ar_data4, hh_prop_data4, unmerged_exponents, merged_exponents), f) if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--no_of_workers', type=int, default=8) parser.add_argument('--unmerged_exponent_vals', type=float, default=[0.0, 1.1, 0.1]) parser.add_argument('--merged_exponent_vals', type=float, default=[0.0, 1.1, 0.1]) args = parser.parse_args() start = time() main(args.no_of_workers, args.unmerged_exponent_vals, args.merged_exponent_vals) print('Execution took',time() - start,'seconds.')
[ "os.mkdir", "pickle.dump", "argparse.ArgumentParser", "pandas.read_csv", "os.path.isfile", "pickle.load", "numpy.arange", "examples.temp_bubbles.common.build_mixed_compositions_pairwise", "model.preprocessing.make_initial_condition_by_eigenvector", "model.preprocessing.HouseholdPopulation", "scipy.integrate.solve_ivp", "model.preprocessing.estimate_beta_ext", "examples.temp_bubbles.common.demerged_initial_condition", "model.preprocessing.SEIRInput", "examples.temp_bubbles.common.build_mixed_compositions_threewise", "numpy.hstack", "multiprocessing.Pool", "model.imports.NoImportModel", "examples.temp_bubbles.common.match_merged_states_to_unmerged", "os.path.isdir", "examples.temp_bubbles.common.initialise_merged_system", "time.time", "numpy.array", "model.preprocessing.merge_hh_inputs" ]
[((971, 1000), 'os.path.isdir', 'isdir', (['"""outputs/temp_bubbles"""'], {}), "('outputs/temp_bubbles')\n", (976, 1000), False, 'from os.path import isdir, isfile\n'), ((1015, 1044), 'os.mkdir', 'mkdir', (['"""outputs/temp_bubbles"""'], {}), "('outputs/temp_bubbles')\n", (1020, 1044), False, 'from os import mkdir\n'), ((1894, 1937), 'os.path.isfile', 'isfile', (['"""outputs/temp_bubbles/beta_ext.pkl"""'], {}), "('outputs/temp_bubbles/beta_ext.pkl')\n", (1900, 1937), False, 'from os.path import isdir, isfile\n'), ((2089, 2133), 'model.preprocessing.SEIRInput', 'SEIRInput', (['SPEC', 'composition_list', 'comp_dist'], {}), '(SPEC, composition_list, comp_dist)\n', (2098, 2133), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((2168, 2236), 'model.preprocessing.HouseholdPopulation', 'HouseholdPopulation', (['composition_list', 'comp_dist', 'model_input_to_fit'], {}), '(composition_list, comp_dist, model_input_to_fit)\n', (2187, 2236), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((2365, 2436), 'model.preprocessing.estimate_beta_ext', 'estimate_beta_ext', (['household_population_to_fit', 'rhs_to_fit', 'growth_rate'], {}), '(household_population_to_fit, rhs_to_fit, growth_rate)\n', (2382, 2436), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((7573, 7579), 'time.time', 'time', ([], {}), '()\n', (7577, 7579), False, 'from time import time\n'), ((8446, 8550), 'scipy.integrate.solve_ivp', 'solve_ivp', (['unmerged.rhs', '(merge_start + 1, t_end)', 'H_postmerge_0[:, -1]'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(unmerged.rhs, (merge_start + 1, t_end), H_postmerge_0[:, -1],\n first_step=0.001, atol=ATOL)\n', (8455, 8550), False, 'from scipy.integrate import solve_ivp\n'), ((8608, 8643), 'numpy.hstack', 'hstack', (['(t_postmerge_0, solution.t)'], {}), '((t_postmerge_0, solution.t))\n', (8614, 8643), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((8673, 8708), 'numpy.hstack', 'hstack', (['(H_postmerge_0, solution.y)'], {}), '((H_postmerge_0, solution.y))\n', (8679, 8708), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((9571, 9669), 'scipy.integrate.solve_ivp', 'solve_ivp', (['unmerged.rhs', '(merge_end, t_end)', 'H_postmerge_1[:, -1]'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(unmerged.rhs, (merge_end, t_end), H_postmerge_1[:, -1],\n first_step=0.001, atol=ATOL)\n', (9580, 9669), False, 'from scipy.integrate import solve_ivp\n'), ((9727, 9762), 'numpy.hstack', 'hstack', (['(t_postmerge_1, solution.t)'], {}), '((t_postmerge_1, solution.t))\n', (9733, 9762), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((9792, 9827), 'numpy.hstack', 'hstack', (['(H_postmerge_1, solution.y)'], {}), '((H_postmerge_1, solution.y))\n', (9798, 9827), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((10693, 10791), 'scipy.integrate.solve_ivp', 'solve_ivp', (['unmerged.rhs', '(merge_end, t_end)', 'H_postmerge_2[:, -1]'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(unmerged.rhs, (merge_end, t_end), H_postmerge_2[:, -1],\n first_step=0.001, atol=ATOL)\n', (10702, 10791), False, 'from scipy.integrate import solve_ivp\n'), ((10849, 10884), 'numpy.hstack', 'hstack', (['(t_postmerge_2, solution.t)'], {}), '((t_postmerge_2, solution.t))\n', (10855, 10884), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((10914, 10949), 'numpy.hstack', 'hstack', (['(H_postmerge_2, solution.y)'], {}), '((H_postmerge_2, solution.y))\n', (10920, 10949), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((17638, 17764), 'examples.temp_bubbles.common.demerged_initial_condition', 'demerged_initial_condition', (['merge_H[:, -1]', 'unmerged_population', 'merged_population', 'hh_dimension', 'pairings', 'hh_to_merge', '(4)'], {}), '(merge_H[:, -1], unmerged_population,\n merged_population, hh_dimension, pairings, hh_to_merge, 4)\n', (17664, 17764), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((17910, 17973), 'scipy.integrate.solve_ivp', 'solve_ivp', (['rhs_unmerged', 'tspan', 'H0'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(rhs_unmerged, tspan, H0, first_step=0.001, atol=ATOL)\n', (17919, 17973), False, 'from scipy.integrate import solve_ivp\n'), ((19757, 19883), 'examples.temp_bubbles.common.demerged_initial_condition', 'demerged_initial_condition', (['merge_H[:, -1]', 'unmerged_population', 'merged_population', 'hh_dimension', 'pairings', 'hh_to_merge', '(4)'], {}), '(merge_H[:, -1], unmerged_population,\n merged_population, hh_dimension, pairings, hh_to_merge, 4)\n', (19783, 19883), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((20051, 20114), 'scipy.integrate.solve_ivp', 'solve_ivp', (['rhs_unmerged', 'tspan', 'H0'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(rhs_unmerged, tspan, H0, first_step=0.001, atol=ATOL)\n', (20060, 20114), False, 'from scipy.integrate import solve_ivp\n'), ((20475, 20566), 'numpy.arange', 'arange', (['unmerged_exponent_vals[0]', 'unmerged_exponent_vals[1]', 'unmerged_exponent_vals[2]'], {}), '(unmerged_exponent_vals[0], unmerged_exponent_vals[1],\n unmerged_exponent_vals[2])\n', (20481, 20566), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((20650, 20735), 'numpy.arange', 'arange', (['merged_exponent_vals[0]', 'merged_exponent_vals[1]', 'merged_exponent_vals[2]'], {}), '(merged_exponent_vals[0], merged_exponent_vals[1],\n merged_exponent_vals[2])\n', (20656, 20735), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((22902, 23043), 'examples.temp_bubbles.common.match_merged_states_to_unmerged', 'match_merged_states_to_unmerged', (['unmerged_results[0].population', 'merged_populations[0].merged_population2', 'pairings_2', '(2)', 'NO_COMPARTMENTS'], {}), '(unmerged_results[0].population,\n merged_populations[0].merged_population2, pairings_2, 2, NO_COMPARTMENTS)\n', (22933, 23043), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((23101, 23242), 'examples.temp_bubbles.common.match_merged_states_to_unmerged', 'match_merged_states_to_unmerged', (['unmerged_results[0].population', 'merged_populations[0].merged_population3', 'pairings_3', '(3)', 'NO_COMPARTMENTS'], {}), '(unmerged_results[0].population,\n merged_populations[0].merged_population3, pairings_3, 3, NO_COMPARTMENTS)\n', (23132, 23242), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((26939, 26955), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (26953, 26955), False, 'from argparse import ArgumentParser\n'), ((27239, 27245), 'time.time', 'time', ([], {}), '()\n', (27243, 27245), False, 'from time import time\n'), ((1862, 1888), 'numpy.arange', 'arange', (['(1)', '(max_hh_size + 1)'], {}), '(1, max_hh_size + 1)\n', (1868, 1888), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((2029, 2036), 'pickle.load', 'load', (['f'], {}), '(f)\n', (2033, 2036), False, 'from pickle import load, dump\n'), ((2330, 2349), 'model.imports.NoImportModel', 'NoImportModel', (['(4)', '(1)'], {}), '(4, 1)\n', (2343, 2349), False, 'from model.imports import NoImportModel\n'), ((2508, 2525), 'pickle.dump', 'dump', (['beta_ext', 'f'], {}), '(beta_ext, f)\n', (2512, 2525), False, 'from pickle import load, dump\n'), ((2715, 2759), 'model.preprocessing.SEIRInput', 'SEIRInput', (['SPEC', 'composition_list', 'comp_dist'], {}), '(SPEC, composition_list, comp_dist)\n', (2724, 2759), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((3059, 3129), 'model.preprocessing.HouseholdPopulation', 'HouseholdPopulation', (['composition_list', 'comp_dist', 'unmerged_input', '(True)'], {}), '(composition_list, comp_dist, unmerged_input, True)\n', (3078, 3129), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((3578, 3701), 'model.preprocessing.make_initial_condition_by_eigenvector', 'make_initial_condition_by_eigenvector', (['growth_rate', 'unmerged_input', 'self.population', 'self.rhs', 'prev', 'starting_immunity'], {}), '(growth_rate, unmerged_input, self.\n population, self.rhs, prev, starting_immunity)\n', (3615, 3701), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((4015, 4084), 'scipy.integrate.solve_ivp', 'solve_ivp', (['self.rhs', 'self.tspan', 'self.H0'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(self.rhs, self.tspan, self.H0, first_step=0.001, atol=ATOL)\n', (4024, 4084), False, 'from scipy.integrate import solve_ivp\n'), ((4326, 4405), 'scipy.integrate.solve_ivp', 'solve_ivp', (['self.rhs', 'tspan', 'self.baseline_H[:, -1]'], {'first_step': '(0.001)', 'atol': 'ATOL'}), '(self.rhs, tspan, self.baseline_H[:, -1], first_step=0.001, atol=ATOL)\n', (4335, 4405), False, 'from scipy.integrate import solve_ivp\n'), ((4491, 4526), 'numpy.hstack', 'hstack', (['(baseline_time, solution.t)'], {}), '((baseline_time, solution.t))\n', (4497, 4526), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((4548, 4585), 'numpy.hstack', 'hstack', (['(self.baseline_H, solution.y)'], {}), '((self.baseline_H, solution.y))\n', (4554, 4585), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((5805, 5849), 'model.preprocessing.SEIRInput', 'SEIRInput', (['SPEC', 'composition_list', 'comp_dist'], {}), '(SPEC, composition_list, comp_dist)\n', (5814, 5849), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((6027, 6081), 'model.preprocessing.merge_hh_inputs', 'merge_hh_inputs', (['merged_input2', '(2)', 'GUEST_TRANS_SCALING'], {}), '(merged_input2, 2, GUEST_TRANS_SCALING)\n', (6042, 6081), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((6207, 6292), 'model.preprocessing.HouseholdPopulation', 'HouseholdPopulation', (['merged_comp_list_2', 'merged_comp_dist_2', 'merged_input2', '(True)'], {}), '(merged_comp_list_2, merged_comp_dist_2, merged_input2, True\n )\n', (6226, 6292), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((6519, 6563), 'model.preprocessing.SEIRInput', 'SEIRInput', (['SPEC', 'composition_list', 'comp_dist'], {}), '(SPEC, composition_list, comp_dist)\n', (6528, 6563), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((6741, 6795), 'model.preprocessing.merge_hh_inputs', 'merge_hh_inputs', (['merged_input3', '(3)', 'GUEST_TRANS_SCALING'], {}), '(merged_input3, 3, GUEST_TRANS_SCALING)\n', (6756, 6795), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((6921, 7006), 'model.preprocessing.HouseholdPopulation', 'HouseholdPopulation', (['merged_comp_list_3', 'merged_comp_dist_3', 'merged_input3', '(True)'], {}), '(merged_comp_list_3, merged_comp_dist_3, merged_input3, True\n )\n', (6940, 7006), False, 'from model.preprocessing import estimate_beta_ext, merge_hh_inputs, SEIRInput, HouseholdPopulation, make_initial_condition_by_eigenvector\n'), ((11222, 11256), 'numpy.hstack', 'hstack', (['(merge_I_0, postmerge_I_0)'], {}), '((merge_I_0, postmerge_I_0))\n', (11228, 11256), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((12204, 12238), 'numpy.hstack', 'hstack', (['(merge_I_1, postmerge_I_1)'], {}), '((merge_I_1, postmerge_I_1))\n', (12210, 12238), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((13185, 13219), 'numpy.hstack', 'hstack', (['(merge_I_2, postmerge_I_2)'], {}), '((merge_I_2, postmerge_I_2))\n', (13191, 13219), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((14124, 14158), 'numpy.hstack', 'hstack', (['(merge_I_3, postmerge_I_3)'], {}), '((merge_I_3, postmerge_I_3))\n', (14130, 14158), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((15063, 15097), 'numpy.hstack', 'hstack', (['(merge_I_4, postmerge_I_4)'], {}), '((merge_I_4, postmerge_I_4))\n', (15069, 15097), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((16558, 16652), 'examples.temp_bubbles.common.initialise_merged_system', 'initialise_merged_system', (['premerge_H0', 'unmerged_population', 'merged_population', 'state_match'], {}), '(premerge_H0, unmerged_population,\n merged_population, state_match)\n', (16582, 16652), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((17165, 17290), 'examples.temp_bubbles.common.demerged_initial_condition', 'demerged_initial_condition', (['temp_H[:, -1]', 'unmerged_population', 'merged_population', 'hh_dimension', 'pairings', 'hh_to_merge', '(4)'], {}), '(temp_H[:, -1], unmerged_population,\n merged_population, hh_dimension, pairings, hh_to_merge, 4)\n', (17191, 17290), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((18619, 18713), 'examples.temp_bubbles.common.initialise_merged_system', 'initialise_merged_system', (['premerge_H0', 'unmerged_population', 'merged_population', 'state_match'], {}), '(premerge_H0, unmerged_population,\n merged_population, state_match)\n', (18643, 18713), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((19251, 19376), 'examples.temp_bubbles.common.demerged_initial_condition', 'demerged_initial_condition', (['temp_H[:, -1]', 'unmerged_population', 'merged_population', 'hh_dimension', 'pairings', 'hh_to_merge', '(4)'], {}), '(temp_H[:, -1], unmerged_population,\n merged_population, hh_dimension, pairings, hh_to_merge, 4)\n', (19277, 19376), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((20804, 20860), 'os.path.isfile', 'isfile', (['"""outputs/temp_bubbles/threewise_merge_comps.pkl"""'], {}), "('outputs/temp_bubbles/threewise_merge_comps.pkl')\n", (20810, 20860), False, 'from os.path import isdir, isfile\n'), ((21449, 21511), 'examples.temp_bubbles.common.build_mixed_compositions_pairwise', 'build_mixed_compositions_pairwise', (['composition_list', 'comp_dist'], {}), '(composition_list, comp_dist)\n', (21482, 21511), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((21646, 21731), 'examples.temp_bubbles.common.build_mixed_compositions_threewise', 'build_mixed_compositions_threewise', (['composition_list', 'comp_dist', 'MAX_MERGED_SIZE'], {}), '(composition_list, comp_dist, MAX_MERGED_SIZE\n )\n', (21680, 21731), False, 'from examples.temp_bubbles.common import build_mixed_compositions_pairwise, build_mixed_compositions_threewise, demerged_initial_condition, initialise_merged_system, match_merged_states_to_unmerged\n'), ((22448, 22467), 'multiprocessing.Pool', 'Pool', (['no_of_workers'], {}), '(no_of_workers)\n', (22452, 22467), False, 'from multiprocessing import Pool\n'), ((22783, 22802), 'multiprocessing.Pool', 'Pool', (['no_of_workers'], {}), '(no_of_workers)\n', (22787, 22802), False, 'from multiprocessing import Pool\n'), ((23698, 23717), 'multiprocessing.Pool', 'Pool', (['no_of_workers'], {}), '(no_of_workers)\n', (23702, 23717), False, 'from multiprocessing import Pool\n'), ((26311, 26610), 'pickle.dump', 'dump', (['(peak_data0, end_data0, ar_data0, hh_prop_data0, peak_data1, end_data1,\n ar_data1, hh_prop_data1, peak_data2, end_data2, ar_data2, hh_prop_data2,\n peak_data3, end_data3, ar_data3, hh_prop_data3, peak_data4, end_data4,\n ar_data4, hh_prop_data4, unmerged_exponents, merged_exponents)', 'f'], {}), '((peak_data0, end_data0, ar_data0, hh_prop_data0, peak_data1, end_data1,\n ar_data1, hh_prop_data1, peak_data2, end_data2, ar_data2, hh_prop_data2,\n peak_data3, end_data3, ar_data3, hh_prop_data3, peak_data4, end_data4,\n ar_data4, hh_prop_data4, unmerged_exponents, merged_exponents), f)\n', (26315, 26610), False, 'from pickle import load, dump\n'), ((3283, 3316), 'model.imports.NoImportModel', 'NoImportModel', (['NO_COMPARTMENTS', '(1)'], {}), '(NO_COMPARTMENTS, 1)\n', (3296, 3316), False, 'from model.imports import NoImportModel\n'), ((5078, 5183), 'pickle.dump', 'dump', (['(self.population, baseline_H, baseline_time, baseline_S, baseline_E,\n baseline_I, baseline_R)', 'f'], {}), '((self.population, baseline_H, baseline_time, baseline_S, baseline_E,\n baseline_I, baseline_R), f)\n', (5082, 5183), False, 'from pickle import load, dump\n'), ((6459, 6492), 'model.imports.NoImportModel', 'NoImportModel', (['NO_COMPARTMENTS', '(2)'], {}), '(NO_COMPARTMENTS, 2)\n', (6472, 6492), False, 'from model.imports import NoImportModel\n'), ((7173, 7206), 'model.imports.NoImportModel', 'NoImportModel', (['NO_COMPARTMENTS', '(3)'], {}), '(NO_COMPARTMENTS, 3)\n', (7186, 7206), False, 'from model.imports import NoImportModel\n'), ((17499, 17530), 'numpy.hstack', 'hstack', (['(merge_time, temp_time)'], {}), '((merge_time, temp_time))\n', (17505, 17530), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((17553, 17578), 'numpy.hstack', 'hstack', (['(merge_H, temp_H)'], {}), '((merge_H, temp_H))\n', (17559, 17578), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((19585, 19616), 'numpy.hstack', 'hstack', (['(merge_time, temp_time)'], {}), '((merge_time, temp_time))\n', (19591, 19616), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((19672, 19697), 'numpy.hstack', 'hstack', (['(merge_H, temp_H)'], {}), '((merge_H, temp_H))\n', (19678, 19697), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((21253, 21260), 'pickle.load', 'load', (['f'], {}), '(f)\n', (21257, 21260), False, 'from pickle import load, dump\n'), ((21837, 21968), 'pickle.dump', 'dump', (['(merged_comp_list_2, merged_comp_dist_2, pairings_2, merged_comp_list_3,\n merged_comp_dist_3, hh_dimension, pairings_3)', 'f'], {}), '((merged_comp_list_2, merged_comp_dist_2, pairings_2,\n merged_comp_list_3, merged_comp_dist_3, hh_dimension, pairings_3), f)\n', (21841, 21968), False, 'from pickle import load, dump\n'), ((23810, 23840), 'numpy.array', 'array', (['[r[0] for r in results]'], {}), '([r[0] for r in results])\n', (23815, 23840), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((23930, 23960), 'numpy.array', 'array', (['[r[1] for r in results]'], {}), '([r[1] for r in results])\n', (23935, 23960), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24049, 24079), 'numpy.array', 'array', (['[r[2] for r in results]'], {}), '([r[2] for r in results])\n', (24054, 24079), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24173, 24203), 'numpy.array', 'array', (['[r[3] for r in results]'], {}), '([r[3] for r in results])\n', (24178, 24203), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24293, 24323), 'numpy.array', 'array', (['[r[4] for r in results]'], {}), '([r[4] for r in results])\n', (24298, 24323), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24413, 24443), 'numpy.array', 'array', (['[r[5] for r in results]'], {}), '([r[5] for r in results])\n', (24418, 24443), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24532, 24562), 'numpy.array', 'array', (['[r[6] for r in results]'], {}), '([r[6] for r in results])\n', (24537, 24562), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24656, 24686), 'numpy.array', 'array', (['[r[7] for r in results]'], {}), '([r[7] for r in results])\n', (24661, 24686), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24777, 24807), 'numpy.array', 'array', (['[r[8] for r in results]'], {}), '([r[8] for r in results])\n', (24782, 24807), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((24897, 24927), 'numpy.array', 'array', (['[r[9] for r in results]'], {}), '([r[9] for r in results])\n', (24902, 24927), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25016, 25047), 'numpy.array', 'array', (['[r[10] for r in results]'], {}), '([r[10] for r in results])\n', (25021, 25047), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25141, 25172), 'numpy.array', 'array', (['[r[11] for r in results]'], {}), '([r[11] for r in results])\n', (25146, 25172), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25263, 25294), 'numpy.array', 'array', (['[r[12] for r in results]'], {}), '([r[12] for r in results])\n', (25268, 25294), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25384, 25415), 'numpy.array', 'array', (['[r[13] for r in results]'], {}), '([r[13] for r in results])\n', (25389, 25415), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25504, 25535), 'numpy.array', 'array', (['[r[14] for r in results]'], {}), '([r[14] for r in results])\n', (25509, 25535), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25629, 25660), 'numpy.array', 'array', (['[r[15] for r in results]'], {}), '([r[15] for r in results])\n', (25634, 25660), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25751, 25782), 'numpy.array', 'array', (['[r[16] for r in results]'], {}), '([r[16] for r in results])\n', (25756, 25782), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25872, 25903), 'numpy.array', 'array', (['[r[17] for r in results]'], {}), '([r[17] for r in results])\n', (25877, 25903), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((25992, 26023), 'numpy.array', 'array', (['[r[18] for r in results]'], {}), '([r[18] for r in results])\n', (25997, 26023), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((26117, 26148), 'numpy.array', 'array', (['[r[19] for r in results]'], {}), '([r[19] for r in results])\n', (26122, 26148), False, 'from numpy import arange, array, atleast_2d, diag, hstack, ones, where\n'), ((27376, 27382), 'time.time', 'time', ([], {}), '()\n', (27380, 27382), False, 'from time import time\n'), ((1640, 1693), 'pandas.read_csv', 'read_csv', (['"""inputs/england_hh_size_dist.csv"""'], {'header': '(0)'}), "('inputs/england_hh_size_dist.csv', header=0)\n", (1648, 1693), False, 'from pandas import read_csv\n')]
# -*- coding: utf-8 -*- """ Read MODIS and VIIRS NPP SST data during the SPURS-1 deployment cruise. Created on Mon Jul 13 23:21:16 2020 Initially followed Intro_06_Xarray-basics.py tutorial obtained from <NAME> @author: jtomf """ # import sys # sys.path.append('C:/Users/jtomf/Documents/Python/Tom_tools/') import numpy as np import matplotlib.pyplot as plt import xarray as xr import pandas as pd import datetime as dt import Tom_tools_v1 as tt # from scipy import signal # import Utils ################################ # plt.close("all") __figdir__ = "../Figz" savefig_args = {'bbox_inches':'tight', 'pad_inches':0} ########################### # Load MODIS SST data #url = 'https://opendap.jpl.nasa.gov/opendap/OceanTemperature/modis/L3/aqua/11um/v2014.0/4km/daily/2012/274/A2012274.L3m_DAY_NSST_sst_4km.nc' #url = 'https://opendap.jpl.nasa.gov/opendap/OceanTemperature/modis/L3/aqua/11um/v2014.0/4km/daily/2012/273/A2012273.L3m_DAY_NSST_sst_4km.nc' #url = 'https://opendap.jpl.nasa.gov/opendap/OceanTemperature/modis/L3/aqua/11um/v2014.0/4km/daily/2012/275/A2012275.L3m_DAY_NSST_sst_4km.nc' daystr = '274' # 274N is good; also looked at 270-280 Nstr = 'N' # '' or 'N' for day or night url = 'https://opendap.jpl.nasa.gov/opendap/OceanTemperature/modis/L3/aqua/11um/v2014.0/4km/daily/2012/' + daystr + '/A2012' + daystr + '.L3m_DAY_' + Nstr + 'SST_sst_4km.nc' ds_sst = xr.open_dataset(url) ################## # from http://xarray.pydata.org/en/stable/plotting.html # xarray plotting functionality is a thin wrapper around the popular matplotlib library. # Matplotlib syntax and function names were copied as much as possible, which makes for an easy # transition between the two. Matplotlib must be installed before xarray can plot. SPURSlon = -(38+00.0017/60) SPURSlat = 24+35.0247/60 fig = plt.figure(figsize=(8, 4)) ds_sst.sst.sel(lat=slice(28,23),lon=slice(-42,-34)).plot(cmap='coolwarm',levels=np.linspace(26,28,15)) plt.axis('tight') plt.plot(SPURSlon, SPURSlat, 'o', color='k') plt.title(ds_sst.time_coverage_start) #Same as above, but zoomed in on the axes used for VIIRS NPP below fig = plt.figure(figsize=(8, 4)) foo = ds_sst.sst.sel(lat=slice(28, 23), lon=slice(-42, -34)).plot.contourf(cmap='coolwarm', levels=np.linspace(27.15,27.85,20)) plt.axis('tight') plt.plot(SPURSlon, SPURSlat, 'o', color='k') plt.title(ds_sst.time_coverage_start) plt.axis([-38.708669, -37.26713, 24.23951, 25.3261]) plt.axis('scaled') fig = plt.figure(figsize=(8, 4)) ds_sst.sst.sel(lat=slice(28,23),lon=slice(-42,-34)).plot.contourf(cmap='coolwarm',levels=np.linspace(26,28,15)) plt.axis('tight') plt.plot(SPURSlon,SPURSlat,'o',color='k') plt.title(ds_sst.time_coverage_start) plt.savefig(__figdir__ + "/Figure1a.png", **savefig_args, dpi=600) ##################################### # This is AVHRR from VIIRS NPP, not MODIS # This takes a long time: url = 'https://thredds.jpl.nasa.gov/thredds/dodsC/OceanTemperature/VIIRS_NPP-OSPO-L3U-v2.61.nc' ds_npp = xr.open_dataset(url) ds_sub = ds_npp.sea_surface_temperature.sel(time=slice('20120929','20120930'),lat=slice(28,23),lon=slice(-42,-34))-273.15 ff = ~np.isnan(ds_sub.sel(lat=slice(24.55, 24.45), lon=slice(-38.05, -37.95)).mean('lon').mean('lat')) ff2 = np.where(ff) fig = plt.figure(figsize=(8, 4)) plt.plot(ff) plt.title('Indices of subset with non-nan data') fig = plt.figure(figsize=(8, 4)) #ds_sub.mean(['time']).plot(cmap='coolwarm',levels=np.linspace(26,28,15)) ds_sub.isel(time=ff2[0][1]).plot(cmap='coolwarm',levels=np.linspace(26,28,15)) plt.plot(SPURSlon,SPURSlat,'o',color='k') fig= plt.figure(figsize=(8,4)) ds_sub.isel(time=ff2[0][0]).plot(cmap='coolwarm',levels=np.linspace(26,28,15)) plt.plot(SPURSlon,SPURSlat,'o',color='k') fig= plt.figure(figsize=(8,4)) ds_sub.isel(time=ff2[0][2]).plot(cmap='coolwarm',levels=np.linspace(26,28,15)) plt.plot(SPURSlon,SPURSlat,'o',color='k') sst_im = ds_sub.isel(time=ff2[0][1]) ############################################## fig= plt.figure(figsize=(8,4)) ds_sub.isel(time=ff2[0][1]).plot(cmap='coolwarm',levels=np.linspace(27.15,27.9,15)) #plt.plot(SPURSlon,SPURSlat,'o',color='k') plt.axis([-38.708669354838705, -37.26713709677419, 24.239516041550388, 25.32612009257010]) gpsdata = pd.read_csv('../buoy_and_glider_lat_lon.csv') gpsdata['date_time'] = [tt.matlab2datetime(tval) for tval in gpsdata['mday']] gpssub = gpsdata.loc[gpsdata['date_time'] >= '201209300000'] gpssub = gpssub.loc[gpssub['date_time'] <= '201209300600'] plt.plot(gpssub['buoy-lon'], gpssub['buoy-lat'], color='k') plt.plot(gpssub['gldr-lon'], gpssub['gldr-lat'], color='m') plt.plot(gpssub.iloc[-1]['buoy-lon'], gpssub.iloc[-1]['buoy-lat'], 'o', color='k') plt.plot(gpssub.iloc[-1]['gldr-lon'], gpssub.iloc[-1]['gldr-lat'], 'o', color='m') plt.axis('scaled') plt.savefig(__figdir__ + "/VIIRS_NPP_SST.png",**savefig_args,dpi=600) ########################################## # Make a smoothed version of SST (ds_sub) ds = ds_sub.isel(time=ff2[0][1]) sst = np.reshape(ds.data, (len(ds.lat), len(ds.lon))) N = 3 sst_smooth = tt.run_avg2d(sst, N, 1) sst_smooth = tt.run_avg2d(sst_smooth, N, 2) fig = plt.figure(figsize=(6, 4)) plt.contourf(ds.lon, ds.lat, sst_smooth, cmap='coolwarm', levels=np.linspace(27.3,27.8,26)) #plt.plot(SPURSlon,SPURSlat,'o',color='k') plt.axis('scaled') plt.colorbar(label='SST ($^\circ$C)') plt.axis([-38.708669354838705, -37.26713709677419, 24.239516041550388, 25.32612009257010]) #fig = plt.figure(figsize=(8, 4)) plt.plot(gpssub['buoy-lon'], gpssub['buoy-lat'], color='k') plt.plot(gpssub['gldr-lon'], gpssub['gldr-lat'], color='m') h1 = plt.plot(gpssub.iloc[-1]['buoy-lon'], gpssub.iloc[-1]['buoy-lat'], 'o', color='k', label='Buoy positions') h2 = plt.plot(gpssub.iloc[-1]['gldr-lon'], gpssub.iloc[-1]['gldr-lat'], 'o', color='m', label='Glider positions') plt.axis('scaled') plt.axis([-38.113580307811965, -37.89454310774521, 24.479272006279203, 24.70908152766072]) plt.xlabel('Longitude ($^\circ$W)') plt.ylabel('Latitude ($^\circ$N)') locs, labels = plt.xticks() labels2 = [] # Generate an empty list for n in np.arange(len(locs)): labels2.append(str(-round(locs[n],3))) # generate list of x axis coords, w/o minus sign plt.xticks(locs,labels=labels2) plt.legend() plt.savefig(__figdir__ + "/VIIRS_NPP_SST_zoom.png",**savefig_args,dpi=600)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "pandas.read_csv", "matplotlib.pyplot.close", "matplotlib.pyplot.legend", "xarray.open_dataset", "matplotlib.pyplot.axis", "matplotlib.pyplot.colorbar", "Tom_tools_v1.matlab2datetime", "matplotlib.pyplot.figure", "numpy.where", "Tom_tools_v1.run_avg2d", "matplotlib.pyplot.xticks", "numpy.linspace", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((530, 546), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (539, 546), True, 'import matplotlib.pyplot as plt\n'), ((1382, 1402), 'xarray.open_dataset', 'xr.open_dataset', (['url'], {}), '(url)\n', (1397, 1402), True, 'import xarray as xr\n'), ((1810, 1836), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (1820, 1836), True, 'import matplotlib.pyplot as plt\n'), ((1940, 1957), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (1948, 1957), True, 'import matplotlib.pyplot as plt\n'), ((1958, 2002), 'matplotlib.pyplot.plot', 'plt.plot', (['SPURSlon', 'SPURSlat', '"""o"""'], {'color': '"""k"""'}), "(SPURSlon, SPURSlat, 'o', color='k')\n", (1966, 2002), True, 'import matplotlib.pyplot as plt\n'), ((2003, 2040), 'matplotlib.pyplot.title', 'plt.title', (['ds_sst.time_coverage_start'], {}), '(ds_sst.time_coverage_start)\n', (2012, 2040), True, 'import matplotlib.pyplot as plt\n'), ((2115, 2141), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (2125, 2141), True, 'import matplotlib.pyplot as plt\n'), ((2270, 2287), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (2278, 2287), True, 'import matplotlib.pyplot as plt\n'), ((2288, 2332), 'matplotlib.pyplot.plot', 'plt.plot', (['SPURSlon', 'SPURSlat', '"""o"""'], {'color': '"""k"""'}), "(SPURSlon, SPURSlat, 'o', color='k')\n", (2296, 2332), True, 'import matplotlib.pyplot as plt\n'), ((2333, 2370), 'matplotlib.pyplot.title', 'plt.title', (['ds_sst.time_coverage_start'], {}), '(ds_sst.time_coverage_start)\n', (2342, 2370), True, 'import matplotlib.pyplot as plt\n'), ((2371, 2423), 'matplotlib.pyplot.axis', 'plt.axis', (['[-38.708669, -37.26713, 24.23951, 25.3261]'], {}), '([-38.708669, -37.26713, 24.23951, 25.3261])\n', (2379, 2423), True, 'import matplotlib.pyplot as plt\n'), ((2427, 2445), 'matplotlib.pyplot.axis', 'plt.axis', (['"""scaled"""'], {}), "('scaled')\n", (2435, 2445), True, 'import matplotlib.pyplot as plt\n'), ((2454, 2480), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (2464, 2480), True, 'import matplotlib.pyplot as plt\n'), ((2593, 2610), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (2601, 2610), True, 'import matplotlib.pyplot as plt\n'), ((2611, 2655), 'matplotlib.pyplot.plot', 'plt.plot', (['SPURSlon', 'SPURSlat', '"""o"""'], {'color': '"""k"""'}), "(SPURSlon, SPURSlat, 'o', color='k')\n", (2619, 2655), True, 'import matplotlib.pyplot as plt\n'), ((2653, 2690), 'matplotlib.pyplot.title', 'plt.title', (['ds_sst.time_coverage_start'], {}), '(ds_sst.time_coverage_start)\n', (2662, 2690), True, 'import matplotlib.pyplot as plt\n'), ((2692, 2758), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(__figdir__ + '/Figure1a.png')"], {'dpi': '(600)'}), "(__figdir__ + '/Figure1a.png', **savefig_args, dpi=600)\n", (2703, 2758), True, 'import matplotlib.pyplot as plt\n'), ((2972, 2992), 'xarray.open_dataset', 'xr.open_dataset', (['url'], {}), '(url)\n', (2987, 2992), True, 'import xarray as xr\n'), ((3225, 3237), 'numpy.where', 'np.where', (['ff'], {}), '(ff)\n', (3233, 3237), True, 'import numpy as np\n'), ((3244, 3270), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (3254, 3270), True, 'import matplotlib.pyplot as plt\n'), ((3271, 3283), 'matplotlib.pyplot.plot', 'plt.plot', (['ff'], {}), '(ff)\n', (3279, 3283), True, 'import matplotlib.pyplot as plt\n'), ((3284, 3332), 'matplotlib.pyplot.title', 'plt.title', (['"""Indices of subset with non-nan data"""'], {}), "('Indices of subset with non-nan data')\n", (3293, 3332), True, 'import matplotlib.pyplot as plt\n'), ((3340, 3366), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (3350, 3366), True, 'import matplotlib.pyplot as plt\n'), ((3520, 3564), 'matplotlib.pyplot.plot', 'plt.plot', (['SPURSlon', 'SPURSlat', '"""o"""'], {'color': '"""k"""'}), "(SPURSlon, SPURSlat, 'o', color='k')\n", (3528, 3564), True, 'import matplotlib.pyplot as plt\n'), ((3568, 3594), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (3578, 3594), True, 'import matplotlib.pyplot as plt\n'), ((3673, 3717), 'matplotlib.pyplot.plot', 'plt.plot', (['SPURSlon', 'SPURSlat', '"""o"""'], {'color': '"""k"""'}), "(SPURSlon, SPURSlat, 'o', color='k')\n", (3681, 3717), True, 'import matplotlib.pyplot as plt\n'), ((3721, 3747), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (3731, 3747), True, 'import matplotlib.pyplot as plt\n'), ((3826, 3870), 'matplotlib.pyplot.plot', 'plt.plot', (['SPURSlon', 'SPURSlat', '"""o"""'], {'color': '"""k"""'}), "(SPURSlon, SPURSlat, 'o', color='k')\n", (3834, 3870), True, 'import matplotlib.pyplot as plt\n'), ((3960, 3986), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (3970, 3986), True, 'import matplotlib.pyplot as plt\n'), ((4113, 4207), 'matplotlib.pyplot.axis', 'plt.axis', (['[-38.708669354838705, -37.26713709677419, 24.239516041550388, 25.3261200925701]'], {}), '([-38.708669354838705, -37.26713709677419, 24.239516041550388, \n 25.3261200925701])\n', (4121, 4207), True, 'import matplotlib.pyplot as plt\n'), ((4217, 4262), 'pandas.read_csv', 'pd.read_csv', (['"""../buoy_and_glider_lat_lon.csv"""'], {}), "('../buoy_and_glider_lat_lon.csv')\n", (4228, 4262), True, 'import pandas as pd\n'), ((4461, 4520), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub['buoy-lon']", "gpssub['buoy-lat']"], {'color': '"""k"""'}), "(gpssub['buoy-lon'], gpssub['buoy-lat'], color='k')\n", (4469, 4520), True, 'import matplotlib.pyplot as plt\n'), ((4521, 4580), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub['gldr-lon']", "gpssub['gldr-lat']"], {'color': '"""m"""'}), "(gpssub['gldr-lon'], gpssub['gldr-lat'], color='m')\n", (4529, 4580), True, 'import matplotlib.pyplot as plt\n'), ((4581, 4667), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub.iloc[-1]['buoy-lon']", "gpssub.iloc[-1]['buoy-lat']", '"""o"""'], {'color': '"""k"""'}), "(gpssub.iloc[-1]['buoy-lon'], gpssub.iloc[-1]['buoy-lat'], 'o',\n color='k')\n", (4589, 4667), True, 'import matplotlib.pyplot as plt\n'), ((4664, 4750), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub.iloc[-1]['gldr-lon']", "gpssub.iloc[-1]['gldr-lat']", '"""o"""'], {'color': '"""m"""'}), "(gpssub.iloc[-1]['gldr-lon'], gpssub.iloc[-1]['gldr-lat'], 'o',\n color='m')\n", (4672, 4750), True, 'import matplotlib.pyplot as plt\n'), ((4747, 4765), 'matplotlib.pyplot.axis', 'plt.axis', (['"""scaled"""'], {}), "('scaled')\n", (4755, 4765), True, 'import matplotlib.pyplot as plt\n'), ((4767, 4838), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(__figdir__ + '/VIIRS_NPP_SST.png')"], {'dpi': '(600)'}), "(__figdir__ + '/VIIRS_NPP_SST.png', **savefig_args, dpi=600)\n", (4778, 4838), True, 'import matplotlib.pyplot as plt\n'), ((5030, 5053), 'Tom_tools_v1.run_avg2d', 'tt.run_avg2d', (['sst', 'N', '(1)'], {}), '(sst, N, 1)\n', (5042, 5053), True, 'import Tom_tools_v1 as tt\n'), ((5067, 5097), 'Tom_tools_v1.run_avg2d', 'tt.run_avg2d', (['sst_smooth', 'N', '(2)'], {}), '(sst_smooth, N, 2)\n', (5079, 5097), True, 'import Tom_tools_v1 as tt\n'), ((5106, 5132), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (5116, 5132), True, 'import matplotlib.pyplot as plt\n'), ((5268, 5286), 'matplotlib.pyplot.axis', 'plt.axis', (['"""scaled"""'], {}), "('scaled')\n", (5276, 5286), True, 'import matplotlib.pyplot as plt\n'), ((5287, 5325), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'label': '"""SST ($^\\\\circ$C)"""'}), "(label='SST ($^\\\\circ$C)')\n", (5299, 5325), True, 'import matplotlib.pyplot as plt\n'), ((5325, 5419), 'matplotlib.pyplot.axis', 'plt.axis', (['[-38.708669354838705, -37.26713709677419, 24.239516041550388, 25.3261200925701]'], {}), '([-38.708669354838705, -37.26713709677419, 24.239516041550388, \n 25.3261200925701])\n', (5333, 5419), True, 'import matplotlib.pyplot as plt\n'), ((5456, 5515), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub['buoy-lon']", "gpssub['buoy-lat']"], {'color': '"""k"""'}), "(gpssub['buoy-lon'], gpssub['buoy-lat'], color='k')\n", (5464, 5515), True, 'import matplotlib.pyplot as plt\n'), ((5516, 5575), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub['gldr-lon']", "gpssub['gldr-lat']"], {'color': '"""m"""'}), "(gpssub['gldr-lon'], gpssub['gldr-lat'], color='m')\n", (5524, 5575), True, 'import matplotlib.pyplot as plt\n'), ((5581, 5691), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub.iloc[-1]['buoy-lon']", "gpssub.iloc[-1]['buoy-lat']", '"""o"""'], {'color': '"""k"""', 'label': '"""Buoy positions"""'}), "(gpssub.iloc[-1]['buoy-lon'], gpssub.iloc[-1]['buoy-lat'], 'o',\n color='k', label='Buoy positions')\n", (5589, 5691), True, 'import matplotlib.pyplot as plt\n'), ((5693, 5805), 'matplotlib.pyplot.plot', 'plt.plot', (["gpssub.iloc[-1]['gldr-lon']", "gpssub.iloc[-1]['gldr-lat']", '"""o"""'], {'color': '"""m"""', 'label': '"""Glider positions"""'}), "(gpssub.iloc[-1]['gldr-lon'], gpssub.iloc[-1]['gldr-lat'], 'o',\n color='m', label='Glider positions')\n", (5701, 5805), True, 'import matplotlib.pyplot as plt\n'), ((5802, 5820), 'matplotlib.pyplot.axis', 'plt.axis', (['"""scaled"""'], {}), "('scaled')\n", (5810, 5820), True, 'import matplotlib.pyplot as plt\n'), ((5821, 5916), 'matplotlib.pyplot.axis', 'plt.axis', (['[-38.113580307811965, -37.89454310774521, 24.479272006279203, 24.70908152766072\n ]'], {}), '([-38.113580307811965, -37.89454310774521, 24.479272006279203, \n 24.70908152766072])\n', (5829, 5916), True, 'import matplotlib.pyplot as plt\n'), ((5912, 5948), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Longitude ($^\\\\circ$W)"""'], {}), "('Longitude ($^\\\\circ$W)')\n", (5922, 5948), True, 'import matplotlib.pyplot as plt\n'), ((5948, 5983), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Latitude ($^\\\\circ$N)"""'], {}), "('Latitude ($^\\\\circ$N)')\n", (5958, 5983), True, 'import matplotlib.pyplot as plt\n'), ((5999, 6011), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {}), '()\n', (6009, 6011), True, 'import matplotlib.pyplot as plt\n'), ((6175, 6207), 'matplotlib.pyplot.xticks', 'plt.xticks', (['locs'], {'labels': 'labels2'}), '(locs, labels=labels2)\n', (6185, 6207), True, 'import matplotlib.pyplot as plt\n'), ((6207, 6219), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6217, 6219), True, 'import matplotlib.pyplot as plt\n'), ((6220, 6296), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(__figdir__ + '/VIIRS_NPP_SST_zoom.png')"], {'dpi': '(600)'}), "(__figdir__ + '/VIIRS_NPP_SST_zoom.png', **savefig_args, dpi=600)\n", (6231, 6296), True, 'import matplotlib.pyplot as plt\n'), ((4287, 4311), 'Tom_tools_v1.matlab2datetime', 'tt.matlab2datetime', (['tval'], {}), '(tval)\n', (4305, 4311), True, 'import Tom_tools_v1 as tt\n'), ((1917, 1940), 'numpy.linspace', 'np.linspace', (['(26)', '(28)', '(15)'], {}), '(26, 28, 15)\n', (1928, 1940), True, 'import numpy as np\n'), ((2241, 2270), 'numpy.linspace', 'np.linspace', (['(27.15)', '(27.85)', '(20)'], {}), '(27.15, 27.85, 20)\n', (2252, 2270), True, 'import numpy as np\n'), ((2570, 2593), 'numpy.linspace', 'np.linspace', (['(26)', '(28)', '(15)'], {}), '(26, 28, 15)\n', (2581, 2593), True, 'import numpy as np\n'), ((3497, 3520), 'numpy.linspace', 'np.linspace', (['(26)', '(28)', '(15)'], {}), '(26, 28, 15)\n', (3508, 3520), True, 'import numpy as np\n'), ((3650, 3673), 'numpy.linspace', 'np.linspace', (['(26)', '(28)', '(15)'], {}), '(26, 28, 15)\n', (3661, 3673), True, 'import numpy as np\n'), ((3803, 3826), 'numpy.linspace', 'np.linspace', (['(26)', '(28)', '(15)'], {}), '(26, 28, 15)\n', (3814, 3826), True, 'import numpy as np\n'), ((4042, 4070), 'numpy.linspace', 'np.linspace', (['(27.15)', '(27.9)', '(15)'], {}), '(27.15, 27.9, 15)\n', (4053, 4070), True, 'import numpy as np\n'), ((5198, 5225), 'numpy.linspace', 'np.linspace', (['(27.3)', '(27.8)', '(26)'], {}), '(27.3, 27.8, 26)\n', (5209, 5225), True, 'import numpy as np\n')]
import json import numpy as np from matplotlib import pyplot as plt from matplotlib.markers import MarkerStyle from sklearn.decomposition import PCA from sklearn.manifold import TSNE def plot_embeddings(reduced_data, phoneme_list, title): consonants = ['w', 'b', 'ɡ', 'n', 'ʒ', 'ʃ', 'd', 'l', 'θ', 'ŋ', 'f', 'ɾ', 's', 'm', 't', 'h', 'z', 'p', 'ʔ', 'v', 'ɹ', 'j', 'ð', 'k'] vowels = ['o', 'ɛ', 'ᵻ', 'ɔ', 'æ', 'i', 'ɐ', 'ɜ', 'ə', 'ɑ', 'e', 'ʌ', 'ɚ', 'a', 'ɪ', 'ʊ', 'u'] special_symbols = ['?', '.', '!', '~'] plt.clf() plt.scatter(x=[x[0] for x in reduced_data], y=[x[1] for x in reduced_data], marker=MarkerStyle()) plt.tight_layout() plt.axis('off') for index, phoneme in enumerate(reduced_data): x_position = phoneme[0] y_position = phoneme[1] label = phoneme_list[index] if label in special_symbols: color = "red" elif label in consonants: color = "blue" elif label in vowels: color = "green" else: color = "violet" plt.text(x=x_position, y=y_position, s=label, color=color) plt.subplots_adjust(top=0.85) plt.title(title) plt.show() if __name__ == '__main__': with open("embedding_table_512dim.json", 'r', encoding="utf8") as fp: datapoints = json.load(fp) key_list = list() # no matter where you get it from, this needs to be a list of the phonemes you want to visualize as string embedding_list = list() # in the same order as the phonemes in the list above, this list needs to be filled with their embedding vectors for key in datapoints: key_list.append(key) embedding_list += datapoints[key] embeddings_as_array = np.array(embedding_list) tsne = TSNE(verbose=1, learning_rate=4, perplexity=30, n_iter=200000, n_iter_without_progress=8000, init='pca') pca = PCA(n_components=2) reduced_data_tsne = tsne.fit_transform(embeddings_as_array) reduced_data_pca = pca.fit_transform(embeddings_as_array) plot_embeddings(reduced_data_tsne, key_list, title="Trained Embeddings t-SNE") plot_embeddings(reduced_data_pca, key_list, title="Trained Embeddings PCA")
[ "matplotlib.pyplot.title", "json.load", "matplotlib.pyplot.show", "sklearn.manifold.TSNE", "matplotlib.pyplot.clf", "matplotlib.pyplot.axis", "matplotlib.pyplot.text", "numpy.array", "sklearn.decomposition.PCA", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.tight_layout", "matplotlib.markers.MarkerStyle" ]
[((527, 536), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (534, 536), True, 'from matplotlib import pyplot as plt\n'), ((643, 661), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (659, 661), True, 'from matplotlib import pyplot as plt\n'), ((666, 681), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (674, 681), True, 'from matplotlib import pyplot as plt\n'), ((1129, 1158), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(0.85)'}), '(top=0.85)\n', (1148, 1158), True, 'from matplotlib import pyplot as plt\n'), ((1163, 1179), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1172, 1179), True, 'from matplotlib import pyplot as plt\n'), ((1184, 1194), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1192, 1194), True, 'from matplotlib import pyplot as plt\n'), ((1732, 1756), 'numpy.array', 'np.array', (['embedding_list'], {}), '(embedding_list)\n', (1740, 1756), True, 'import numpy as np\n'), ((1769, 1877), 'sklearn.manifold.TSNE', 'TSNE', ([], {'verbose': '(1)', 'learning_rate': '(4)', 'perplexity': '(30)', 'n_iter': '(200000)', 'n_iter_without_progress': '(8000)', 'init': '"""pca"""'}), "(verbose=1, learning_rate=4, perplexity=30, n_iter=200000,\n n_iter_without_progress=8000, init='pca')\n", (1773, 1877), False, 'from sklearn.manifold import TSNE\n'), ((1884, 1903), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (1887, 1903), False, 'from sklearn.decomposition import PCA\n'), ((1066, 1124), 'matplotlib.pyplot.text', 'plt.text', ([], {'x': 'x_position', 'y': 'y_position', 's': 'label', 'color': 'color'}), '(x=x_position, y=y_position, s=label, color=color)\n', (1074, 1124), True, 'from matplotlib import pyplot as plt\n'), ((1319, 1332), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (1328, 1332), False, 'import json\n'), ((624, 637), 'matplotlib.markers.MarkerStyle', 'MarkerStyle', ([], {}), '()\n', (635, 637), False, 'from matplotlib.markers import MarkerStyle\n')]
"""Script to create PCA plot to compare similarity of binned CpG methylation.""" import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from scipy.special import logit from functools import reduce KIT = { 'FtubeAkapaBC' : 'Kapa', 'FtubeAkapaBCrep2' : 'Kapa', 'FtubeAneb' : 'NEB', 'FtubeAnebRep2' : 'NEB', 'FtubeApbat' : 'PBAT', 'FtubeAswift' : 'Swift', 'FtubeAswiftRep2' : 'Swift', 'FtubeAneb10ng' : 'NEB', 'FtubeAneb10ngRep2' : 'NEB', 'FtubeAswift10ng' : 'Swift', 'FtubeAswift10ngRep2': 'Swift', 'FtubeBkapaBC' : 'Kapa', 'FtubeBkapaBCrep2' : 'Kapa', 'FtubeBneb' : 'NEB', 'FtubeBnebRep2' : 'NEB', 'FtubeBpbat' : 'PBAT', 'FtubeBswift' : 'Swift', 'FtubeBswiftRep2' : 'Swift', 'FtubeBneb10ng' : 'NEB', 'FtubeBneb10ngRep2' : 'NEB', 'FtubeBswift10ng' : 'Swift', 'FtubeBswift10ngRep2': 'Swift' } SAM = { 'FtubeAkapaBC' : 'A', 'FtubeAkapaBCrep2' : 'A', 'FtubeAneb' : 'A', 'FtubeAnebRep2' : 'A', 'FtubeApbat' : 'A', 'FtubeAswift' : 'A', 'FtubeAswiftRep2' : 'A', 'FtubeAneb10ng' : 'A', 'FtubeAneb10ngRep2' : 'A', 'FtubeAswift10ng' : 'A', 'FtubeAswift10ngRep2': 'A', 'FtubeBkapaBC' : 'B', 'FtubeBkapaBCrep2' : 'B', 'FtubeBneb' : 'B', 'FtubeBnebRep2' : 'B', 'FtubeBpbat' : 'B', 'FtubeBswift' : 'B', 'FtubeBswiftRep2' : 'B', 'FtubeBneb10ng' : 'B', 'FtubeBneb10ngRep2' : 'B', 'FtubeBswift10ng' : 'B', 'FtubeBswift10ngRep2': 'B' } REP = { 'FtubeAkapaBC' : '1', 'FtubeAkapaBCrep2' : '2', 'FtubeAneb' : '1', 'FtubeAnebRep2' : '2', 'FtubeApbat' : '1', 'FtubeAswift' : '1', 'FtubeAswiftRep2' : '2', 'FtubeAneb10ng' : '1', 'FtubeAneb10ngRep2' : '2', 'FtubeAswift10ng' : '1', 'FtubeAswift10ngRep2': '2', 'FtubeBkapaBC' : '1', 'FtubeBkapaBCrep2' : '2', 'FtubeBneb' : '1', 'FtubeBnebRep2' : '2', 'FtubeBpbat' : '1', 'FtubeBswift' : '1', 'FtubeBswiftRep2' : '2', 'FtubeBneb10ng' : '1', 'FtubeBneb10ngRep2' : '2', 'FtubeBswift10ng' : '1', 'FtubeBswift10ngRep2': '2' } def beta_to_m(betas, covgs, k): """Transform beta values into m values. Inputs - betas - pd.Series of beta values covgs - pd.Series of covg values k - number of pseudoreads for smoothing Returns pd.Series of m values """ b = list(betas) c = list(covgs) s = [] for i in range(len(c)): m = (c[i] * b[i]) u = (c[i] - m) s.append((m+k) / ((m+k) + (u+k))) out = logit(s) return pd.Series(out) def make_plot(data, var, keys, cols, title, xlab, ylab, figname): """Create plot for principal components of PCA. Inputs - data - DataFrame with columns pc1, pc2, var var - column name of variable to keep keys - keys from var column that correspond to colors in cols list cols - colors to match with keys list title - title of figure xlab - x-axis label ylab - y-axis label figname - name of output file Returns - Nothing, plot is saved to disk """ fig, ax = plt.subplots(figsize=(5,5)) plt.tight_layout() if len(keys) != len(cols): print('[make_plot] ERROR: Mismatch in number of keys and colors.') return None # Add scatter plot to figure for each set of data in keys for key, col in zip(keys, cols): to_keep = data[var] == key if True not in list(to_keep): continue ax.scatter(data.loc[to_keep, 'pc1'], data.loc[to_keep, 'pc2'], c=col, s=25) ax.legend(keys, ncol=1, loc='upper right', fontsize=13) plt.xlim(-250, 250) plt.ylim(-175, 175) plt.xticks([i for i in np.arange(-200, 300, 100)], ['{:.0f}'.format(i) for i in np.arange(-200, 300, 100)], fontsize=14) plt.yticks([i for i in np.arange(-150, 200, 50)], ['{:.0f}'.format(i) for i in np.arange(-150, 200, 50)], fontsize=14) plt.title(title, fontsize=24) plt.xlabel(xlab, fontsize=20) plt.ylabel(ylab, fontsize=20) plt.savefig(figname, bbox_inches='tight') plt.close('all') def make_combined_plot(data, title, xlab, ylab, figname): """Create plot for principal components of PCA with all variables shown. Inputs - data - DataFrame with columns pc1, pc2, kit, sample, and replicate title - title of figure xlab - x-axis label ylab - y-axis label figname - name of output file Returns - Nothing, plot is saved to disk """ keys = { 1: ('A', '1', 'Kapa'), 2: ('A', '2', 'Kapa'), 3: ('B', '1', 'Kapa'), 4: ('B', '2', 'Kapa'), 5: ('A', '1', 'NEB'), 6: ('A', '2', 'NEB'), 7: ('B', '1', 'NEB'), 8: ('B', '2', 'NEB'), 9: ('A', '1', 'PBAT'), 10: ('B', '1', 'PBAT'), 11: ('A', '1', 'Swift'), 12: ('A', '2', 'Swift'), 13: ('B', '1', 'Swift'), 14: ('B', '2', 'Swift'), } cols = { 1: ('o', 'none', '#D81B60'), 2: ('o', '#D81B60', '#D81B60'), 3: ('s', 'none', '#D81B60'), 4: ('s', '#D81B60', '#D81B60'), 5: ('o', 'none', '#1E88E5'), 6: ('o', '#1E88E5', '#1E88E5'), 7: ('s', 'none', '#1E88E5'), 8: ('s', '#1E88E5', '#1E88E5'), 9: ('o', 'none', '#A0522D'), 10: ('s', 'none' , '#A0522D'), 11: ('o', 'none', '#004D40'), 12: ('o', '#004D40', '#004D40'), 13: ('s', 'none', '#004D40'), 14: ('s', '#004D40', '#004D40'), } fig, ax = plt.subplots(figsize=(5,5)) plt.tight_layout() # Create legend plt.plot(-300, 300, 'o', color='black', markersize=8, label='Samp. A') plt.plot(-300, 300, 's', color='black', markersize=8, label='Samp. B') plt.plot(-300, 300, 'D', color='black', fillstyle='none', markersize=8, label='Rep. 1') plt.plot(-300, 300, 'D', color='black', markersize=8, label='Rep. 2') plt.plot(-300, 300, 'D', color='#D81B60', markersize=8, label='Kapa') plt.plot(-300, 300, 'D', color='#1E88E5', markersize=8, label='NEB') plt.plot(-300, 300, 'D', color='#A0522D', markersize=8, label='PBAT') plt.plot(-300, 300, 'D', color='#004D40', markersize=8, label='Swift') # Add scatter plot to figure for each set of data in keys for key, col in zip(keys.values(), cols.values()): to_keep = (data['sample'] == key[0]) & (data['replicate'] == key[1]) & (data['kit'] == key[2]) if True not in list(to_keep): continue ax.scatter(data.loc[to_keep, 'pc1'], data.loc[to_keep, 'pc2'], marker=col[0], facecolors=col[1], edgecolors=col[2], s=25) ax.legend(ncol=4, bbox_to_anchor=(0.5, 0.98), frameon=False, loc='lower center', fontsize=14) plt.xlim(-250, 250) plt.ylim(-175, 175) plt.xticks([i for i in np.arange(-200, 300, 100)], ['{:.0f}'.format(i) for i in np.arange(-200, 300, 100)], fontsize=14) plt.yticks([i for i in np.arange(-150, 200, 50)], ['{:.0f}'.format(i) for i in np.arange(-150, 200, 50)], fontsize=14) plt.title(title, pad=50, fontsize=24) plt.xlabel(xlab, fontsize=20) plt.ylabel(ylab, fontsize=20) plt.savefig(figname, bbox_inches='tight') plt.close('all') def main(): """Do the bulk of the PCA generation.""" dirloc = '../../subsampling/' filtag = '.subsampled.cg.sorted.mergecg.100kb_meth_avg.bed.gz' samps = [ 'FtubeAkapaBC' , 'FtubeAkapaBCrep2' , 'FtubeAneb' , 'FtubeAnebRep2' , 'FtubeApbat' , 'FtubeAswift' , 'FtubeAswiftRep2' , 'FtubeAneb10ng' , 'FtubeAneb10ngRep2' , 'FtubeAswift10ng' , 'FtubeAswift10ngRep2', 'FtubeBkapaBC' , 'FtubeBkapaBCrep2' , 'FtubeBneb' , 'FtubeBnebRep2' , 'FtubeBpbat' , 'FtubeBswift' , 'FtubeBswiftRep2' , 'FtubeBneb10ng' , 'FtubeBneb10ngRep2' , 'FtubeBswift10ng' , 'FtubeBswift10ngRep2' ] dfs = [] for samp in samps: cols = ['chr', 'start', 'end', 'beta', 'covg'] df = pd.read_csv(dirloc+samp+filtag, sep='\t', names=cols, na_values='.') # Transform beta values into m-values uses logit transform # Makes beta distribution of values into a more gaussian distribution df[samp] = beta_to_m(df['beta'], df['covg'], 0.1) dfs.append(df.drop(['beta', 'covg'], axis=1)) df_na = reduce(lambda x, y: pd.merge(x, y, on=['chr', 'start', 'end']), dfs) df_al = df_na.dropna(axis=0, how='any') df = df_al.drop(['chr', 'start', 'end'], axis=1).transpose() kits = [KIT[i] for i in list(df.index)] sams = [SAM[i] for i in list(df.index)] reps = [REP[i] for i in list(df.index)] # Standardize values x = StandardScaler().fit_transform(df) std = pd.DataFrame(data=x, columns=list(df.columns)) # Create PCA pca = PCA(n_components=2) principals = pca.fit_transform(x) print(pca.explained_variance_ratio_) pcs = pd.DataFrame(data=principals, columns=['pc1', 'pc2']) pcs['kit'] = kits pcs['sample'] = sams pcs['replicate'] = reps # Make figures make_plot( pcs, 'kit', ['Kapa', 'NEB', 'PBAT', 'Swift'], ['#D81B60', '#1E88E5', '#A0522D', '#004D40'], '2-component PCA: Protocol', 'Principal Component 1', 'Principal Component 2', 'pca_protocol.pdf' ) make_plot( pcs, 'sample', ['A', 'B'], ['#981e32', '#5e6a71'], '2-component PCA: Sample', 'Principal Component 1', 'Principal Component 2', 'pca_sample.pdf' ) make_plot( pcs, 'replicate', ['1', '2'], ['#005596', '#3fa294'], '2-component PCA: Tech. Rep.', 'Principal Component 1', 'Principal Component 2', 'pca_replicate.pdf' ) make_combined_plot( pcs, '2-component PCA', 'Principal Component 1', 'Principal Component 2', 'pca_combined.pdf' ) if __name__ == '__main__': main()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "pandas.DataFrame", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "pandas.read_csv", "matplotlib.pyplot.close", "pandas.merge", "matplotlib.pyplot.subplots", "scipy.special.logit", "sklearn.decomposition.PCA", "pandas.Series", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.savefig" ]
[((2844, 2852), 'scipy.special.logit', 'logit', (['s'], {}), '(s)\n', (2849, 2852), False, 'from scipy.special import logit\n'), ((2865, 2879), 'pandas.Series', 'pd.Series', (['out'], {}), '(out)\n', (2874, 2879), True, 'import pandas as pd\n'), ((3454, 3482), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (3466, 3482), True, 'import matplotlib.pyplot as plt\n'), ((3486, 3504), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3502, 3504), True, 'import matplotlib.pyplot as plt\n'), ((4003, 4022), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-250)', '(250)'], {}), '(-250, 250)\n', (4011, 4022), True, 'import matplotlib.pyplot as plt\n'), ((4027, 4046), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-175)', '(175)'], {}), '(-175, 175)\n', (4035, 4046), True, 'import matplotlib.pyplot as plt\n'), ((4303, 4332), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': '(24)'}), '(title, fontsize=24)\n', (4312, 4332), True, 'import matplotlib.pyplot as plt\n'), ((4337, 4366), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlab'], {'fontsize': '(20)'}), '(xlab, fontsize=20)\n', (4347, 4366), True, 'import matplotlib.pyplot as plt\n'), ((4371, 4400), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylab'], {'fontsize': '(20)'}), '(ylab, fontsize=20)\n', (4381, 4400), True, 'import matplotlib.pyplot as plt\n'), ((4406, 4447), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figname'], {'bbox_inches': '"""tight"""'}), "(figname, bbox_inches='tight')\n", (4417, 4447), True, 'import matplotlib.pyplot as plt\n'), ((4452, 4468), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (4461, 4468), True, 'import matplotlib.pyplot as plt\n'), ((5840, 5868), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (5852, 5868), True, 'import matplotlib.pyplot as plt\n'), ((5872, 5890), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5888, 5890), True, 'import matplotlib.pyplot as plt\n'), ((5916, 5986), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""o"""'], {'color': '"""black"""', 'markersize': '(8)', 'label': '"""Samp. A"""'}), "(-300, 300, 'o', color='black', markersize=8, label='Samp. A')\n", (5924, 5986), True, 'import matplotlib.pyplot as plt\n'), ((5991, 6061), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""s"""'], {'color': '"""black"""', 'markersize': '(8)', 'label': '"""Samp. B"""'}), "(-300, 300, 's', color='black', markersize=8, label='Samp. B')\n", (5999, 6061), True, 'import matplotlib.pyplot as plt\n'), ((6066, 6157), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""D"""'], {'color': '"""black"""', 'fillstyle': '"""none"""', 'markersize': '(8)', 'label': '"""Rep. 1"""'}), "(-300, 300, 'D', color='black', fillstyle='none', markersize=8,\n label='Rep. 1')\n", (6074, 6157), True, 'import matplotlib.pyplot as plt\n'), ((6158, 6227), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""D"""'], {'color': '"""black"""', 'markersize': '(8)', 'label': '"""Rep. 2"""'}), "(-300, 300, 'D', color='black', markersize=8, label='Rep. 2')\n", (6166, 6227), True, 'import matplotlib.pyplot as plt\n'), ((6232, 6301), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""D"""'], {'color': '"""#D81B60"""', 'markersize': '(8)', 'label': '"""Kapa"""'}), "(-300, 300, 'D', color='#D81B60', markersize=8, label='Kapa')\n", (6240, 6301), True, 'import matplotlib.pyplot as plt\n'), ((6306, 6374), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""D"""'], {'color': '"""#1E88E5"""', 'markersize': '(8)', 'label': '"""NEB"""'}), "(-300, 300, 'D', color='#1E88E5', markersize=8, label='NEB')\n", (6314, 6374), True, 'import matplotlib.pyplot as plt\n'), ((6379, 6448), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""D"""'], {'color': '"""#A0522D"""', 'markersize': '(8)', 'label': '"""PBAT"""'}), "(-300, 300, 'D', color='#A0522D', markersize=8, label='PBAT')\n", (6387, 6448), True, 'import matplotlib.pyplot as plt\n'), ((6453, 6523), 'matplotlib.pyplot.plot', 'plt.plot', (['(-300)', '(300)', '"""D"""'], {'color': '"""#004D40"""', 'markersize': '(8)', 'label': '"""Swift"""'}), "(-300, 300, 'D', color='#004D40', markersize=8, label='Swift')\n", (6461, 6523), True, 'import matplotlib.pyplot as plt\n'), ((7080, 7099), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-250)', '(250)'], {}), '(-250, 250)\n', (7088, 7099), True, 'import matplotlib.pyplot as plt\n'), ((7104, 7123), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-175)', '(175)'], {}), '(-175, 175)\n', (7112, 7123), True, 'import matplotlib.pyplot as plt\n'), ((7380, 7417), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'pad': '(50)', 'fontsize': '(24)'}), '(title, pad=50, fontsize=24)\n', (7389, 7417), True, 'import matplotlib.pyplot as plt\n'), ((7422, 7451), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlab'], {'fontsize': '(20)'}), '(xlab, fontsize=20)\n', (7432, 7451), True, 'import matplotlib.pyplot as plt\n'), ((7456, 7485), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylab'], {'fontsize': '(20)'}), '(ylab, fontsize=20)\n', (7466, 7485), True, 'import matplotlib.pyplot as plt\n'), ((7491, 7532), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figname'], {'bbox_inches': '"""tight"""'}), "(figname, bbox_inches='tight')\n", (7502, 7532), True, 'import matplotlib.pyplot as plt\n'), ((7537, 7553), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (7546, 7553), True, 'import matplotlib.pyplot as plt\n'), ((9245, 9264), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (9248, 9264), False, 'from sklearn.decomposition import PCA\n'), ((9354, 9407), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'principals', 'columns': "['pc1', 'pc2']"}), "(data=principals, columns=['pc1', 'pc2'])\n", (9366, 9407), True, 'import pandas as pd\n'), ((8440, 8512), 'pandas.read_csv', 'pd.read_csv', (['(dirloc + samp + filtag)'], {'sep': '"""\t"""', 'names': 'cols', 'na_values': '"""."""'}), "(dirloc + samp + filtag, sep='\\t', names=cols, na_values='.')\n", (8451, 8512), True, 'import pandas as pd\n'), ((8800, 8842), 'pandas.merge', 'pd.merge', (['x', 'y'], {'on': "['chr', 'start', 'end']"}), "(x, y, on=['chr', 'start', 'end'])\n", (8808, 8842), True, 'import pandas as pd\n'), ((9125, 9141), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (9139, 9141), False, 'from sklearn.preprocessing import StandardScaler\n'), ((4075, 4100), 'numpy.arange', 'np.arange', (['(-200)', '(300)', '(100)'], {}), '(-200, 300, 100)\n', (4084, 4100), True, 'import numpy as np\n'), ((4132, 4157), 'numpy.arange', 'np.arange', (['(-200)', '(300)', '(100)'], {}), '(-200, 300, 100)\n', (4141, 4157), True, 'import numpy as np\n'), ((4200, 4224), 'numpy.arange', 'np.arange', (['(-150)', '(200)', '(50)'], {}), '(-150, 200, 50)\n', (4209, 4224), True, 'import numpy as np\n'), ((4257, 4281), 'numpy.arange', 'np.arange', (['(-150)', '(200)', '(50)'], {}), '(-150, 200, 50)\n', (4266, 4281), True, 'import numpy as np\n'), ((7152, 7177), 'numpy.arange', 'np.arange', (['(-200)', '(300)', '(100)'], {}), '(-200, 300, 100)\n', (7161, 7177), True, 'import numpy as np\n'), ((7209, 7234), 'numpy.arange', 'np.arange', (['(-200)', '(300)', '(100)'], {}), '(-200, 300, 100)\n', (7218, 7234), True, 'import numpy as np\n'), ((7277, 7301), 'numpy.arange', 'np.arange', (['(-150)', '(200)', '(50)'], {}), '(-150, 200, 50)\n', (7286, 7301), True, 'import numpy as np\n'), ((7334, 7358), 'numpy.arange', 'np.arange', (['(-150)', '(200)', '(50)'], {}), '(-150, 200, 50)\n', (7343, 7358), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Author: <NAME> # Copyright © 2020 <NAME> # License: MIT # ----------------------------------------------------------------------------- """ Profile experiment ====================== The code is completely deterministic. We have verified that multiple runs give identical results (see e.g. the md5 hashes of predictions that are logged) """ import os import logging import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from .helpers import ROOT_DIR, DATA_DIR, RESULTS_DIR from .helpers import GENRES, SUBSETS from .helpers import start_experiment_log from .helpers import relpath from .classification import train_model from .classification import get_scores np.random.seed(0) # Globals # ————————————————————————————————————————————————————————————————————————————— PITCH_FEATURES = [f'freq_MIDI_{i}' for i in range(53, 87)] PITCH_CLASS_FEATURES = [f'freq_pitch_class_{i}' for i in range(12)] REPETITION_FEATURES = [f'repetition_score_MIDI_{i}' for i in range(53, 87)] PROFILES = { 'pitch': PITCH_FEATURES, 'pitch_class': PITCH_CLASS_FEATURES, 'repetition': REPETITION_FEATURES } # Helpers # ————————————————————————————————————————————————————————————————————————————— def get_conditions(genres='all', subsets='all', profiles='all'): """Get a list of experimental conditions Parameters ---------- genres : str or list, optional Genres to include, by default 'all' subsets : str or list, optional Subsets to include, by default 'all' profile : str or list, optional Profiles to include, by default 'all' Returns ------- (list, dict) A list with all conditions, and a dictionary with keys 'genres', 'subsets' and 'profiles' containing those values. """ subsets = SUBSETS if subsets == 'all' else subsets genres = GENRES if genres == 'all' else genres profiles = list(PROFILES.keys()) if profiles == 'all' else profiles conditions = [] for genre in genres: for subset in subsets: for profile in profiles: conditions.append( dict(genre=genre, subset=subset, profile=profile)) parts = dict(subsets=subsets, genres=genres, profiles=profiles) return conditions, parts def load_dataset(genre, subset, profile, split, data_dir=DATA_DIR): """Load a dataset for training the classifier. Returns a dataframe of features and an array of corresponding targets (modes)""" feature_names = PROFILES[profile] features_fn = os.path.join(data_dir, genre, subset, f'{split}-features.csv') data = pd.read_csv(features_fn, index_col=0)[feature_names] chants_fn = os.path.join(data_dir, genre, subset, f'{split}-chants.csv') targets = pd.read_csv(chants_fn, index_col=0)['mode'] assert len(targets) == len(data) return data, targets # Experiment # ————————————————————————————————————————————————————————————————————————————— def run_condition(genre, subset, profile, data_dir, results_dir, n_iter, n_splits): """Runs a single experimental condition: trains the classifier, stores all the model, cross-validation results, and evaluation scores.""" # Start experiment logging.info(f'Training model...') logging.info(f'* profile={profile}') logging.info(f'* genre={genre}') logging.info(f'* subset={subset}') # Set up directories output_dir = os.path.join(results_dir, genre, subset) if not os.path.exists(output_dir): os.makedirs(output_dir) # Load training and testing data kwargs = dict(genre=genre, subset=subset, profile=profile, data_dir=data_dir) train_data, train_targets = load_dataset(split='train', **kwargs) test_data, test_targets = load_dataset(split='test', **kwargs) logging.info(f'* Training/test size: {len(train_data)}/{len(test_data)}') logging.info(f'* Num. features: {train_data.shape[1]}') # Model parameters and param grid for tuning fixed_params = { 'n_jobs': -1, 'p': 2, 'metric': 'minkowski' } tuned_params = { 'n_neighbors': np.arange(1, 50), 'weights': ['uniform', 'distance'], 'algorithm': ['ball_tree', 'kd_tree', 'brute'], 'leaf_size': np.arange(10, 100) } # Tune and train model model = KNeighborsClassifier(**fixed_params) train_model( model = model, train_data=train_data, train_targets=train_targets, test_data=test_data, test_targets=test_targets, param_grid=tuned_params, n_splits=n_splits, n_iter=n_iter, basepath=os.path.join(output_dir, profile) ) def run(experiment_name, description=None, genres='all', subsets='all', profiles='all', n_iter=100, n_splits=5, data_dir = DATA_DIR, results_dir = RESULTS_DIR): """Run a 'profile' mode classification experiment using pitch, pitch_class and repetition profiles.""" # Set up directories results_dir = os.path.join(results_dir, experiment_name) if not os.path.exists(results_dir): os.makedirs(results_dir) # Get all conditions conditions, parts = get_conditions(genres, subsets, profiles) # Start log and log experiment settings start_experiment_log( name=experiment_name, description=description, data_dir=data_dir, results_dir=results_dir, n_iter=n_iter, n_splits=n_splits, num_conditions=len(conditions), **parts) # Train all models for condition in conditions: run_condition( data_dir=data_dir, results_dir=results_dir, n_iter=n_iter, n_splits=n_splits, **condition) def evaluate(experiment_name, genres='all', subsets='all', profiles='all', data_dir = DATA_DIR, results_dir = RESULTS_DIR, **kwargs): """Evaluate an experiment and store accuracy and retrieval scores in a single CSV file that can be used to e.g. generate tables and figures.""" logging.info('Evaluating experiment...') results_dir = os.path.join(results_dir, experiment_name) scores = [] conditions, _ = get_conditions(genres, subsets, profiles) for condition in conditions: profile = condition['profile'] output_dir = os.path.join( results_dir, condition['genre'], condition['subset']) condition_scores = get_scores( test_pred_fn = os.path.join(output_dir, f'{profile}-test-pred.txt'), train_pred_fn = os.path.join(output_dir, f'{profile}-train-pred.txt'), genre=condition['genre'], subset=condition['subset'], data_dir=data_dir) condition_scores.update(condition) scores.append(condition_scores) scores_fn = os.path.join(results_dir, f'{experiment_name}-scores.csv') pd.DataFrame(scores).to_csv(scores_fn) logging.info(f'> Stored scores to {relpath(scores_fn)}')
[ "pandas.DataFrame", "numpy.random.seed", "os.makedirs", "pandas.read_csv", "os.path.exists", "logging.info", "sklearn.neighbors.KNeighborsClassifier", "numpy.arange", "os.path.join" ]
[((804, 821), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (818, 821), True, 'import numpy as np\n'), ((2663, 2725), 'os.path.join', 'os.path.join', (['data_dir', 'genre', 'subset', 'f"""{split}-features.csv"""'], {}), "(data_dir, genre, subset, f'{split}-features.csv')\n", (2675, 2725), False, 'import os\n'), ((2806, 2866), 'os.path.join', 'os.path.join', (['data_dir', 'genre', 'subset', 'f"""{split}-chants.csv"""'], {}), "(data_dir, genre, subset, f'{split}-chants.csv')\n", (2818, 2866), False, 'import os\n'), ((3377, 3411), 'logging.info', 'logging.info', (['f"""Training model..."""'], {}), "(f'Training model...')\n", (3389, 3411), False, 'import logging\n'), ((3416, 3452), 'logging.info', 'logging.info', (['f"""* profile={profile}"""'], {}), "(f'* profile={profile}')\n", (3428, 3452), False, 'import logging\n'), ((3457, 3489), 'logging.info', 'logging.info', (['f"""* genre={genre}"""'], {}), "(f'* genre={genre}')\n", (3469, 3489), False, 'import logging\n'), ((3494, 3528), 'logging.info', 'logging.info', (['f"""* subset={subset}"""'], {}), "(f'* subset={subset}')\n", (3506, 3528), False, 'import logging\n'), ((3572, 3612), 'os.path.join', 'os.path.join', (['results_dir', 'genre', 'subset'], {}), '(results_dir, genre, subset)\n', (3584, 3612), False, 'import os\n'), ((4023, 4078), 'logging.info', 'logging.info', (['f"""* Num. features: {train_data.shape[1]}"""'], {}), "(f'* Num. features: {train_data.shape[1]}')\n", (4035, 4078), False, 'import logging\n'), ((4476, 4512), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {}), '(**fixed_params)\n', (4496, 4512), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((5167, 5209), 'os.path.join', 'os.path.join', (['results_dir', 'experiment_name'], {}), '(results_dir, experiment_name)\n', (5179, 5209), False, 'import os\n'), ((6198, 6238), 'logging.info', 'logging.info', (['"""Evaluating experiment..."""'], {}), "('Evaluating experiment...')\n", (6210, 6238), False, 'import logging\n'), ((6257, 6299), 'os.path.join', 'os.path.join', (['results_dir', 'experiment_name'], {}), '(results_dir, experiment_name)\n', (6269, 6299), False, 'import os\n'), ((6971, 7029), 'os.path.join', 'os.path.join', (['results_dir', 'f"""{experiment_name}-scores.csv"""'], {}), "(results_dir, f'{experiment_name}-scores.csv')\n", (6983, 7029), False, 'import os\n'), ((2737, 2774), 'pandas.read_csv', 'pd.read_csv', (['features_fn'], {'index_col': '(0)'}), '(features_fn, index_col=0)\n', (2748, 2774), True, 'import pandas as pd\n'), ((2881, 2916), 'pandas.read_csv', 'pd.read_csv', (['chants_fn'], {'index_col': '(0)'}), '(chants_fn, index_col=0)\n', (2892, 2916), True, 'import pandas as pd\n'), ((3624, 3650), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (3638, 3650), False, 'import os\n'), ((3660, 3683), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (3671, 3683), False, 'import os\n'), ((4272, 4288), 'numpy.arange', 'np.arange', (['(1)', '(50)'], {}), '(1, 50)\n', (4281, 4288), True, 'import numpy as np\n'), ((4411, 4429), 'numpy.arange', 'np.arange', (['(10)', '(100)'], {}), '(10, 100)\n', (4420, 4429), True, 'import numpy as np\n'), ((5221, 5248), 'os.path.exists', 'os.path.exists', (['results_dir'], {}), '(results_dir)\n', (5235, 5248), False, 'import os\n'), ((5258, 5282), 'os.makedirs', 'os.makedirs', (['results_dir'], {}), '(results_dir)\n', (5269, 5282), False, 'import os\n'), ((6471, 6537), 'os.path.join', 'os.path.join', (['results_dir', "condition['genre']", "condition['subset']"], {}), "(results_dir, condition['genre'], condition['subset'])\n", (6483, 6537), False, 'import os\n'), ((4785, 4818), 'os.path.join', 'os.path.join', (['output_dir', 'profile'], {}), '(output_dir, profile)\n', (4797, 4818), False, 'import os\n'), ((7034, 7054), 'pandas.DataFrame', 'pd.DataFrame', (['scores'], {}), '(scores)\n', (7046, 7054), True, 'import pandas as pd\n'), ((6617, 6669), 'os.path.join', 'os.path.join', (['output_dir', 'f"""{profile}-test-pred.txt"""'], {}), "(output_dir, f'{profile}-test-pred.txt')\n", (6629, 6669), False, 'import os\n'), ((6699, 6752), 'os.path.join', 'os.path.join', (['output_dir', 'f"""{profile}-train-pred.txt"""'], {}), "(output_dir, f'{profile}-train-pred.txt')\n", (6711, 6752), False, 'import os\n')]
# -*- coding: utf-8 -*- # ------------------------------------------------------------------ # Filename: nlloc.py # Purpose: plugin for reading and writing GridData object into various format # Author: uquake development team # Email: <EMAIL> # # Copyright (C) 2016 uquake development team # -------------------------------------------------------------------- """ plugin for reading and writing GridData object into various format :copyright: uquake development team (<EMAIL>) :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ import numpy as np from pathlib import Path from uuid import uuid4 from ...grid.nlloc import (valid_float_types, VelocityGrid3D, TTGrid, AngleGrid, NLLocGrid, __default_float_type__) import os def read_pickle(filename, protocol=-1, **kwargs): """ read grid saved in PICKLE format into a GridData object :param filename: full path to the filename :type filename: str :rtype: ~uquake.core.data.grid.Grid """ import pickle return pickle.load(open(filename, 'rb')) def write_pickle(grid, filename, protocol=-1, **kwargs): """ write a GridData object to disk in pickle (.pickle or .npy extension) format using the pickle module :param grid: grid to be saved :type grid: ~uquake.core.data.grid.GridData :param filename: full path to file with extension :type filename: str :param protocol: pickling protocol level :type protocol: int """ import pickle with open(filename, 'wb') as of: pickle.dump(grid, of, protocol=protocol) return True def read_hdf5(filename, **kwargs): """ read a grid file in hdf5 into a uquake.core.data.grid.GridCollection object :param filename: filename :param kwargs: additional keyword argument passed from wrapper. :return: uquake.core.data.grid.GridCollection """ pass def write_csv(grid, filename, **kwargs): """ Write a GridData object to disk in uquake csv format :param grid: grid to be saved :param filename: full path to file with extension :return: """ data = grid.data shape = grid.shape origin = grid.origin spacing = grid.spacing v = grid.get_grid_point_coordinates() flat_data = data.reshape(np.product(shape)) with open(filename, 'w') as f_out: if data.ndim == 3: f_out.write('uquake grid\n') f_out.write(f'spacing: {spacing}') f_out.write(f'origin: {origin}') f_out.write(f'shape: {shape}') f_out.write('x,y,z,value\n') for k in range(grid.shape[2]): for j in range(grid.shape[1]): for i in range(grid.shape[0]): f_out.write(f'{v[0][i]},{v[1][j]},{v[2][k]},' f'{grid.data[i, j, k]}\n') elif data.ndim == 2: f_out.write('uquake grid\n') f_out.write(f'spacing: {spacing}') f_out.write(f'origin: {origin}') f_out.write(f'shape: {shape}') f_out.write('x,y,value\n') for j in range(grid.shape[1]): for i in range(grid.shape[0]): f_out.write(f'{v[0][i]},{v[0][j]},' f'{grid.data[i, j]}\n') return True def read_csv(filename, *args, **kwargs): """ Read a grid save in uquake CSV format :param filename: path to file :param args: :param kwargs: :return: """ pass def write_vtk(grid, filename, **kwargs): """ write a GridData object to disk in VTK format (Paraview, MayaVi2, etc.) using the pyevtk module. param filename: full path to file with the extension. Note that the extension for vtk image data (grid data) is usually .vti. :type filename; str :param grid: grid to be saved :type grid: ~uquake.core.data.grid.GridData .. NOTE: see the imageToVTK function from the pyevtk.hl module for more information on possible additional paramter. """ import vtk if filename[-4:] in ['.vti', '.vtk']: filename = filename[:-4] image_data = vtk.vtkImageData() image_data.SetDimensions(grid.shape) image_data.SetSpacing(grid.spacing) image_data.SetOrigin(grid.origin) image_data.AllocateScalars(vtk.VTK_FLOAT, 1) if grid.ndim == 3: for z in range(grid.shape[2]): for y in range(grid.shape[1]): for x in range(grid.shape[0]): image_data.SetScalarComponentFromFloat(x, y, z, 0, grid.data[x, y, z]) if grid.ndim == 2: for y in range(grid.shape[1]): for x in range(grid.shape[0]): image_data.SetScalarComponentFromFloat(x, y, 0, grid.data[x, y]) writer = vtk.vtkXMLImageDataWriter() writer.SetFileName(f'{filename}.vti') writer.SetInputData(image_data) writer.Write() return True def read_vtk(filename, *args, **kwargs): pass def read_nlloc(filename, float_type=__default_float_type__): """ read two parts NLLoc files :param filename: filename :param float_type: float type as defined in NLLoc grid documentation """ if filename.split('.')[-1] in ['hdr', 'buf', 'mid']: filename = filename[:-4] header_file = Path(f'{filename}.hdr') # header_file = Path(path) / f'{base_name}.hdr' with open(header_file, 'r') as in_file: line = in_file.readline() line = line.split() shape = tuple([int(line[0]), int(line[1]), int(line[2])]) origin = np.array([float(line[3]), float(line[4]), float(line[5])]) * 1000 spacing = np.array([float(line[6]), float(line[7]), float(line[8])]) * 1000 grid_type = line[9] grid_unit = 'METER' line = in_file.readline() if grid_type in ['ANGLE', 'ANGLE2D', 'TIME', 'TIME2D']: line = line.split() seed_label = line[0] seed = (float(line[1]) * 1000, float(line[2]) * 1000, float(line[3]) * 1000) else: seed_label = None seed = None buf_file = Path(f'{filename}.buf') # buf_file = Path(path) / f'{base_name}.buf' if float_type == 'FLOAT': data = np.fromfile(buf_file, dtype=np.float32) elif float_type == 'DOUBLE': data = np.fromfile(buf_file, dtype=np.float64) else: msg = f'float_type = {float_type} is not valid\n' \ f'float_type should be one of the following valid float ' \ f'types:\n' for valid_float_type in valid_float_types: msg += f'{valid_float_type}\n' raise ValueError(msg) data = data.reshape(shape) if '.P.' in filename: phase = 'P' else: phase = 'S' # reading the model id file mid_file = Path(f'{filename}.mid') if mid_file.exists(): with open(mid_file, 'r') as mf: model_id = mf.readline().strip() else: model_id = str(uuid4()) # (self, base_name, data_or_dims, origin, spacing, phase, # seed=None, seed_label=None, value=0, # grid_type='VELOCITY_METERS', grid_units='METER', # float_type="FLOAT", model_id=None): network_code = filename.split(os.path.sep)[-1].split('.')[0] if grid_type in ['VELOCITY', 'VELOCITY_METERS']: return VelocityGrid3D(network_code, data, origin, spacing, phase=phase, model_id=model_id) elif grid_type == 'TIME': return TTGrid(network_code, data, origin, spacing, seed, seed_label, phase=phase, model_id=model_id) elif grid_type == 'ANGLE': return AngleGrid(network_code, data, origin, spacing, seed, seed_label, angle_type='AZIMUTH', phase=phase, model_id=model_id) else: grid = NLLocGrid(data, origin, spacing, phase, grid_type=grid_type, model_id=model_id, grid_units=grid_unit) if grid_type == 'SLOW_LEN': return VelocityGrid3D.from_slow_len(grid, network_code) return grid
[ "pickle.dump", "uuid.uuid4", "vtk.vtkXMLImageDataWriter", "numpy.fromfile", "pathlib.Path", "numpy.product", "vtk.vtkImageData" ]
[((4231, 4249), 'vtk.vtkImageData', 'vtk.vtkImageData', ([], {}), '()\n', (4247, 4249), False, 'import vtk\n'), ((4977, 5004), 'vtk.vtkXMLImageDataWriter', 'vtk.vtkXMLImageDataWriter', ([], {}), '()\n', (5002, 5004), False, 'import vtk\n'), ((5493, 5516), 'pathlib.Path', 'Path', (['f"""{filename}.hdr"""'], {}), "(f'{filename}.hdr')\n", (5497, 5516), False, 'from pathlib import Path\n'), ((6399, 6422), 'pathlib.Path', 'Path', (['f"""{filename}.buf"""'], {}), "(f'{filename}.buf')\n", (6403, 6422), False, 'from pathlib import Path\n'), ((7150, 7173), 'pathlib.Path', 'Path', (['f"""{filename}.mid"""'], {}), "(f'{filename}.mid')\n", (7154, 7173), False, 'from pathlib import Path\n'), ((1603, 1643), 'pickle.dump', 'pickle.dump', (['grid', 'of'], {'protocol': 'protocol'}), '(grid, of, protocol=protocol)\n', (1614, 1643), False, 'import pickle\n'), ((2341, 2358), 'numpy.product', 'np.product', (['shape'], {}), '(shape)\n', (2351, 2358), True, 'import numpy as np\n'), ((6517, 6556), 'numpy.fromfile', 'np.fromfile', (['buf_file'], {'dtype': 'np.float32'}), '(buf_file, dtype=np.float32)\n', (6528, 6556), True, 'import numpy as np\n'), ((6632, 6671), 'numpy.fromfile', 'np.fromfile', (['buf_file'], {'dtype': 'np.float64'}), '(buf_file, dtype=np.float64)\n', (6643, 6671), True, 'import numpy as np\n'), ((7319, 7326), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (7324, 7326), False, 'from uuid import uuid4\n')]
# Example from http://pandas.pydata.org/pandas-docs/stable/visualization.html#visualization import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from numpy.random import randn from pandas import Series, date_range, DataFrame ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() plt.savefig("test.png") df = DataFrame(randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot() plt.savefig("test.png")
[ "matplotlib.use", "pandas.date_range", "matplotlib.pyplot.savefig", "numpy.random.randn" ]
[((111, 132), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (125, 132), False, 'import matplotlib\n'), ((343, 366), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""test.png"""'], {}), "('test.png')\n", (354, 366), True, 'import matplotlib.pyplot as plt\n'), ((464, 487), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""test.png"""'], {}), "('test.png')\n", (475, 487), True, 'import matplotlib.pyplot as plt\n'), ((259, 270), 'numpy.random.randn', 'randn', (['(1000)'], {}), '(1000)\n', (264, 270), False, 'from numpy.random import randn\n'), ((383, 397), 'numpy.random.randn', 'randn', (['(1000)', '(4)'], {}), '(1000, 4)\n', (388, 397), False, 'from numpy.random import randn\n'), ((278, 314), 'pandas.date_range', 'date_range', (['"""1/1/2000"""'], {'periods': '(1000)'}), "('1/1/2000', periods=1000)\n", (288, 314), False, 'from pandas import Series, date_range, DataFrame\n')]
"""This module contains PlainFrame and PlainColumn tests. """ import collections import datetime import pytest import numpy as np import pandas as pd from numpy.testing import assert_equal as np_assert_equal from pywrangler.util.testing.plainframe import ( NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame ) @pytest.fixture def plainframe_standard(): cols = ["int", "float", "bool", "str", "datetime"] data = [[1, 1.1, True, "string", "2019-01-01 10:00:00"], [2, 2, False, "string2", "2019-02-01 10:00:00"]] return PlainFrame.from_plain(data=data, dtypes=cols, columns=cols) @pytest.fixture def plainframe_missings(): cols = ["int", "float", "bool", "str", "datetime"] data = [[1, 1.1, True, "string", "2019-01-01 10:00:00"], [2, NaN, False, "string2", "2019-02-01 10:00:00"], [NULL, NULL, NULL, NULL, NULL]] return PlainFrame.from_plain(data=data, dtypes=cols, columns=cols) @pytest.fixture def df_from_pandas(): df = pd.DataFrame( {"int": [1, 2], "int_na": [1, np.NaN], "bool": [True, False], "bool_na": [True, np.NaN], "float": [1.2, 1.3], "float_na": [1.2, np.NaN], "str": ["foo", "bar"], "str_na": ["foo", np.NaN], "datetime": [pd.Timestamp("2019-01-01"), pd.Timestamp("2019-01-02")], "datetime_na": [pd.Timestamp("2019-01-01"), pd.NaT]}) return df @pytest.fixture def df_from_spark(spark): from pyspark.sql import types values = collections.OrderedDict( {"int": [1, 2, None], "smallint": [1, 2, None], "bigint": [1, 2, None], "bool": [True, False, None], "single": [1.0, NaN, None], "double": [1.0, NaN, None], "str": ["foo", "bar", None], "datetime": [datetime.datetime(2019, 1, 1), datetime.datetime(2019, 1, 2), None], "date": [datetime.date(2019, 1, 1), datetime.date(2019, 1, 2), None], "map": [{"foo": "bar"}, {"bar": "foo"}, None], "array": [[1, 2, 3], [3, 4, 5], None]} ) data = list(zip(*values.values())) c = types.StructField columns = [c("int", types.IntegerType()), c("smallint", types.ShortType()), c("bigint", types.LongType()), c("bool", types.BooleanType()), c("single", types.FloatType()), c("double", types.DoubleType()), c("str", types.StringType()), c("datetime", types.TimestampType()), c("date", types.DateType()), c("map", types.MapType(types.StringType(), types.StringType())), c("array", types.ArrayType(types.IntegerType()))] schema = types.StructType(columns) return spark.createDataFrame(data, schema=schema) def create_plain_frame(cols, rows, reverse_cols=False, reverse_rows=False): """Helper function to automatically create instances of PlainFrame. `cols` contains typed column annotations like "col1:int". """ if reverse_cols: cols = cols[::-1] columns, dtypes = zip(*[col.split(":") for col in cols]) values = list(range(1, rows + 1)) mapping = {"str": list(map(str, values)), "int": values, "float": list(map(float, values)), "bool": list([x % 2 == 0 for x in values]), "datetime": ["2019-01-{:02} 10:00:00".format(x) for x in values]} data = [mapping[dtype] for dtype in dtypes] data = list(zip(*data)) if reverse_rows: data = data[::-1] return PlainFrame.from_plain(data=data, dtypes=dtypes, columns=columns) def create_plainframe_single(values, dtype): """Create some special scenarios more easily. Always assumes a single column with identical name. Only values and dtype varies. """ data = [[x] for x in values] dtypes = [dtype] columns = ["name"] return PlainFrame.from_plain(data=data, dtypes=dtypes, columns=columns) def test_plainframe(): # incorrect instantiation with non tuples with non factory method plain_column = PlainColumn.from_plain(name="int", dtype="int", values=[1, 2, 3]) # correct instantiation PlainFrame(plaincolumns=(plain_column,)) with pytest.raises(ValueError): PlainFrame(plaincolumns=[plain_column]) with pytest.raises(ValueError): PlainFrame(plaincolumns=[1]) def test_plainframe_from_plain_pandas_empty(): # tests GH#29 df = PlainFrame.from_plain(data=[], columns=["col1:int", "col2:str"]) col_values = lambda x: df.get_column(x).values assert df.n_rows == 0 assert df.columns == ["col1", "col2"] assert df.dtypes == ["int", "str"] assert col_values("col1") == tuple() assert col_values("col2") == tuple() dfp = pd.DataFrame(columns=["col1", "col2"], dtype=int) df = PlainFrame.from_pandas(dfp) col_values = lambda x: df.get_column(x).values assert df.n_rows == 0 assert df.columns == ["col1", "col2"] assert df.dtypes == ["int", "int"] assert col_values("col1") == tuple() assert col_values("col2") == tuple() def test_plainframe_attributes(plainframe_missings): df = plainframe_missings col_values = lambda x: df.get_column(x).values assert df.columns == ["int", "float", "bool", "str", "datetime"] assert df.dtypes == ["int", "float", "bool", "str", "datetime"] assert col_values("int") == (1, 2, NULL) assert col_values("str") == ("string", "string2", NULL) assert col_values("datetime")[0] == datetime.datetime(2019, 1, 1, 10) def test_plainframe_modify(): # change single value df_origin = create_plainframe_single([1, 2], "int") df_target = create_plainframe_single([1, 1], "int") assert df_origin.modify({"name": {1: 1}}) == df_target # change multiple values df_origin = create_plainframe_single([1, 2], "int") df_target = create_plainframe_single([3, 3], "int") assert df_origin.modify({"name": {0: 3, 1: 3}}) == df_target # change multiple columns df_origin = PlainFrame.from_plain(data=[[1, 2], ["a", "b"]], dtypes=["int", "str"], columns=["int", "str"], row_wise=False) df_target = PlainFrame.from_plain(data=[[1, 1], ["a", "a"]], dtypes=["int", "str"], columns=["int", "str"], row_wise=False) assert df_origin.modify({"int": {1: 1}, "str": {1: "a"}}) == df_target def test_plainframe_modify_assertions(): # check incorrect type conversion df = create_plainframe_single([1, 2], "int") with pytest.raises(TypeError): df.modify({"name": {0: "asd"}}) def test_plainframe_getitem_subset(): df = create_plain_frame(["col1:str", "col2:int", "col3:int"], 2) df_sub = create_plain_frame(["col1:str", "col2:int"], 2) cmp_kwargs = dict(assert_column_order=True, assert_row_order=True) # test list of strings, slice and string df["col1", "col2"].assert_equal(df_sub, **cmp_kwargs) df["col1":"col2"].assert_equal(df_sub, **cmp_kwargs) df["col1"].assert_equal(df_sub["col1"], **cmp_kwargs) # test incorrect type with pytest.raises(ValueError): df[{"col1"}] # test invalid column name with pytest.raises(ValueError): df["non_existant"] def test_plainframe_get_column(): df = create_plain_frame(["col1:str", "col2:int"], 2) assert df.get_column("col1") is df.plaincolumns[0] # check value error for non existent column with pytest.raises(ValueError): df.get_column("does_not_exist") def test_plainframe_parse_typed_columns(): parse = PlainFrame._parse_typed_columns # invalid splits cols = ["col1:int", "col2"] with pytest.raises(ValueError): parse(cols) # invalid types cols = ["col1:asd"] with pytest.raises(ValueError): parse(cols) # invalid abbreviations cols = ["col1:a"] with pytest.raises(ValueError): parse(cols) # correct types and columns cols = ["col1:str", "col2:s", "col3:int", "col4:i", "col5:float", "col6:f", "col7:bool", "col8:b", "col9:datetime", "col10:d"] names = ["col{}".format(x) for x in range(1, 11)] dtypes = ["str", "str", "int", "int", "float", "float", "bool", "bool", "datetime", "datetime"] result = (names, dtypes) np_assert_equal(parse(cols), result) def test_plainframe_from_plain(): # unequal elements per row with pytest.raises(ValueError): PlainFrame.from_plain(data=[[1, 2], [1]], columns=["a", "b"], dtypes=["int", "int"]) # mismatch between number of columns and entries per row with pytest.raises(ValueError): PlainFrame.from_plain(data=[[1, 2], [1, 2]], columns=["a"], dtypes=["int", "int"]) # mismatch between number of dtypes and entries per row with pytest.raises(ValueError): PlainFrame.from_plain(data=[[1, 2], [1, 2]], columns=["a", "b"], dtypes=["int"]) # incorrect dtypes with pytest.raises(ValueError): PlainFrame.from_plain(data=[[1, 2], [1, 2]], columns=["a", "b"], dtypes=["int", "bad_type"]) # type errors conversion with pytest.raises(TypeError): PlainFrame.from_plain(data=[[1, 2], [1, 2]], columns=["a", "b"], dtypes=["int", "str"]) with pytest.raises(TypeError): PlainFrame.from_plain(data=[[1, 2], [1, 2]], columns=["a", "b"], dtypes=["int", "bool"]) with pytest.raises(TypeError): PlainFrame.from_plain(data=[["1", 2], ["1", 2]], columns=["a", "b"], dtypes=["float", "int"]) with pytest.raises(TypeError): PlainFrame.from_plain(data=[["1", 2], ["1", 2]], columns=["a", "b"], dtypes=["str", "str"]) with pytest.raises(TypeError): PlainFrame.from_plain(data=[[True, 2], [False, 2]], columns=["a", "b"], dtypes=["datetime", "int"]) # correct implementation should not raise PlainFrame.from_plain(data=[[1, 2], [1, 2]], columns=["a", "b"], dtypes=["int", "int"]) def test_plainframe_to_plain(): columns = dtypes = ["int", "float", "bool", "str"] data = [[1, 1.1, True, "string"], [2, 2, False, "string2"]] pf = PlainFrame.from_plain(data=data, columns=columns, dtypes=dtypes) expected = (data, columns, dtypes) assert pf.to_plain() == expected def test_plainframe_from_dict(): data = collections.OrderedDict( [("col1:int", [1, 2, 3]), ("col2:s", ["a", "b", "c"])] ) df = PlainFrame.from_dict(data) # check correct column order and dtypes np_assert_equal(df.columns, ("col1", "col2")) np_assert_equal(df.dtypes, ["int", "str"]) # check correct values np_assert_equal(df.get_column("col1").values, (1, 2, 3)) np_assert_equal(df.get_column("col2").values, ("a", "b", "c")) def test_plainframe_to_dict(): df = create_plain_frame(["col2:str", "col1:int"], 2) to_dict = df.to_dict() keys = list(to_dict.keys()) values = list(to_dict.values()) # check column order and dtypes np_assert_equal(keys, ["col2:str", "col1:int"]) # check values np_assert_equal(values[0], ["1", "2"]) np_assert_equal(values[1], [1, 2]) def test_plainframe_from_pandas(df_from_pandas): df = df_from_pandas df_conv = PlainFrame.from_pandas(df) # check int to int assert df_conv.get_column("int").dtype == "int" assert df_conv.get_column("int").values == (1, 2) # check bool to bool assert df_conv.get_column("bool").dtype == "bool" assert df_conv.get_column("bool").values == (True, False) # check bool (object) to bool with nan assert df_conv.get_column("bool_na").dtype == "bool" assert df_conv.get_column("bool_na").values == (True, NULL) # check float to float assert df_conv.get_column("float").dtype == "float" assert df_conv.get_column("float").values == (1.2, 1.3) # check float to float with nan assert df_conv.get_column("float_na").dtype == "float" np_assert_equal(df_conv.get_column("float_na").values, (1.2, NaN)) # check str to str assert df_conv.get_column("str").dtype == "str" assert df_conv.get_column("str").values == ("foo", "bar") # check str to str with nan assert df_conv.get_column("str_na").dtype == "str" assert df_conv.get_column("str_na").values == ("foo", NULL) # check datetime to datetime assert df_conv.get_column("datetime").dtype == "datetime" assert df_conv.get_column("datetime").values == \ (datetime.datetime(2019, 1, 1), datetime.datetime(2019, 1, 2)) # check datetime to datetime with nan assert df_conv.get_column("datetime_na").dtype == "datetime" assert df_conv.get_column("datetime_na").values == ( datetime.datetime(2019, 1, 1), NULL) def test_plainframe_from_pandas_assertions_missings_cast(): # check mixed dtype raise df = pd.DataFrame({"mixed": [1, "foo bar"]}) with pytest.raises(TypeError): PlainFrame.from_pandas(df) # check assertion for incorrect forces # too many types provided with pytest.raises(ValueError): PlainFrame.from_pandas(df, dtypes=["int", "str"]) with pytest.raises(ValueError): PlainFrame.from_pandas(df, dtypes={"mixed": "str", "dummy": "int"}) # invalid dtypes provided with pytest.raises(ValueError): PlainFrame.from_pandas(df, dtypes=["not existant type"]) with pytest.raises(ValueError): PlainFrame.from_pandas(df, dtypes={"mixed": "not existant type"}) # invalid column names provided with pytest.raises(ValueError): PlainFrame.from_pandas(df, dtypes={"dummy": "str"}) # check int to forced int with nan df = pd.DataFrame({"int": [1, np.NaN]}) df_conv = PlainFrame.from_pandas(df, dtypes=["int"]) assert df_conv.get_column("int").dtype == "int" assert df_conv.get_column("int").values == (1, NULL) # check force int to float df = pd.DataFrame({"int": [1, 2]}) df_conv = PlainFrame.from_pandas(df, dtypes=["float"]) assert df_conv.get_column("int").dtype == "float" assert df_conv.get_column("int").values == (1.0, 2.0) # check force float to int df = pd.DataFrame({"float": [1.0, 2.0]}) df_conv = PlainFrame.from_pandas(df, dtypes=["int"]) assert df_conv.get_column("float").dtype == "int" assert df_conv.get_column("float").values == (1, 2) # check force str to datetime df = pd.DataFrame({"datetime": ["2019-01-01", "2019-01-02"]}) df_conv = PlainFrame.from_pandas(df, dtypes=["datetime"]) assert df_conv.get_column("datetime").dtype == "datetime" assert df_conv.get_column("datetime").values == \ (datetime.datetime(2019, 1, 1), datetime.datetime(2019, 1, 2)) # dtype object with strings and nan should pass correctly df = pd.DataFrame({"str": ["foo", "bar", NaN]}, dtype=object) df_conv = PlainFrame.from_pandas(df) assert df_conv.get_column("str").dtype == "str" assert df_conv.get_column("str").values == ("foo", "bar", NULL) def test_plainframe_from_pandas_inspect_dtype(): inspect = ConverterFromPandas.inspect_dtype # raise if incorrect type ser = pd.Series("asd", dtype=object) with pytest.raises(TypeError): inspect(ser) def test_plainframe_from_pandas_inspect_dtype_object(): inspect = ConverterFromPandas.inspect_dtype_object # ensure string with missings df = pd.DataFrame({"dummy": ["asd", NaN]}) conv = ConverterFromPandas(df) assert conv.inspect_dtype_object("dummy") == "str" # check incorrect dtype df = pd.DataFrame({"dummy": ["asd", tuple([1, 2])]}) conv = ConverterFromPandas(df) with pytest.raises(TypeError): conv.inspect_dtype_object("dummy") def test_plainframe_to_pandas(plainframe_standard): from pandas.api import types df = plainframe_standard.to_pandas() assert types.is_integer_dtype(df["int"]) assert df["int"][0] == 1 assert df["int"].isnull().sum() == 0 assert types.is_float_dtype(df["float"]) assert df["float"].isnull().sum() == 0 assert df["float"][1] == 2.0 assert types.is_bool_dtype(df["bool"]) np_assert_equal(df["bool"][0], True) assert df["bool"].isnull().sum() == 0 assert types.is_object_dtype(df["str"]) assert df["str"].isnull().sum() == 0 assert df["str"][0] == "string" assert types.is_datetime64_dtype(df["datetime"]) assert df["datetime"].isnull().sum() == 0 assert df["datetime"][0] == pd.Timestamp("2019-01-01 10:00:00") def test_plainframe_to_pandas_missings(plainframe_missings): from pandas.api import types df = plainframe_missings.to_pandas() assert types.is_float_dtype(df["int"]) assert df["int"][0] == 1.0 assert pd.isnull(df["int"][2]) assert df["int"].isnull().sum() == 1 assert df["float"].isnull().sum() == 2 assert df["float"][0] == 1.1 assert pd.isnull(df["float"][2]) assert types.is_float_dtype(df["bool"]) assert df["bool"][0] == 1.0 assert df["bool"].isnull().sum() == 1 assert types.is_object_dtype(df["str"]) assert df["str"].isnull().sum() == 1 assert df["str"][0] == "string" assert types.is_datetime64_dtype(df["datetime"]) assert df["datetime"].isnull().sum() == 1 assert df["datetime"][0] == pd.Timestamp("2019-01-01 10:00:00") assert df["datetime"][2] is pd.NaT def test_plainframe_from_pyspark(df_from_spark): def select(x): from_pyspark = PlainFrame.from_pyspark return from_pyspark(df_from_spark.select(x)) # int columns int_columns = ["int", "smallint", "bigint"] df = select(int_columns) for int_column in int_columns: assert df.get_column(int_column).dtype == "int" assert df.get_column(int_column).values == (1, 2, NULL) # bool column df = select("bool") assert df.get_column("bool").dtype == "bool" assert df.get_column("bool").values == (True, False, NULL) # float columns float_columns = ["single", "double"] df = select(float_columns) for float_column in float_columns: assert df.get_column(float_column).dtype == "float" np_assert_equal(df.get_column(float_column).values, (1.0, NaN, NULL)) # string column df = select("str") assert df.get_column("str").dtype == "str" assert df.get_column("str").values == ("foo", "bar", NULL) # datetime columns datetime_columns = ["datetime", "date"] df = select(datetime_columns) for datetime_column in datetime_columns: col = df.get_column(datetime_column) assert col.dtype == "datetime" assert col.values == (datetime.datetime(2019, 1, 1), datetime.datetime(2019, 1, 2), NULL) # unsupported columns unsupported_columns = ["map", "array"] for unsupported_column in unsupported_columns: with pytest.raises(ValueError): df = select(unsupported_column) def test_plainframe_to_pyspark(plainframe_missings): df = plainframe_missings.to_pyspark() dtypes = dict(df.dtypes) assert dtypes["int"] == "int" assert dtypes["float"] == "double" assert dtypes["bool"] == "boolean" assert dtypes["str"] == "string" assert dtypes["datetime"] == "timestamp" res = df.collect() assert res[0].int == 1 assert res[2].int is None assert res[0].float == 1.1 assert pd.isnull(res[1].float) assert res[2].float is None assert res[0].bool is True assert res[2].bool is None assert res[0].str == "string" assert res[2].str is None assert res[0].datetime == datetime.datetime(2019, 1, 1, 10) assert res[2].datetime is None def test_plainframe_from_any(plainframe_standard): conv = PlainFrame.from_any # test plainframe assert conv(plainframe_standard) == plainframe_standard # test dict assert conv(plainframe_standard.to_dict()) == plainframe_standard # test tuple assert conv(plainframe_standard.to_plain()) == plainframe_standard # test pandas assert conv(plainframe_standard.to_pandas()) == plainframe_standard # test pyspark assert conv(plainframe_standard.to_pyspark()) == plainframe_standard # test wrong type with pytest.raises(ValueError): conv("string") def test_plainframe_assert_equal(): # equal values should be equal left = create_plain_frame(["a:int", "b:int"], 10) right = create_plain_frame(["a:int", "b:int"], 10) left.assert_equal(right) # different values should not be equal left = create_plainframe_single([1, 2], "int") right = create_plainframe_single([2, 3], "int") with pytest.raises(AssertionError): left.assert_equal(right) # incorrect number of rows with pytest.raises(AssertionError): left = create_plain_frame(["a:int", "b:int"], 10) right = create_plain_frame(["a:int", "b:int"], 5) left.assert_equal(right) # incorrect number of columns with pytest.raises(AssertionError): left = create_plain_frame(["a:int"], 10) right = create_plain_frame(["a:int", "b:int"], 10) left.assert_equal(right) # incorrect column_names with pytest.raises(AssertionError): left = create_plain_frame(["a:int", "c:int"], 10) right = create_plain_frame(["a:int", "b:int"], 10) left.assert_equal(right) # incorrect dtypes with pytest.raises(AssertionError): left = create_plain_frame(["a:int", "b:str"], 10) right = create_plain_frame(["a:int", "b:int"], 10) left.assert_equal(right) # check column order left = create_plain_frame(["a:int", "b:int"], 10, reverse_cols=True) right = create_plain_frame(["a:int", "b:int"], 10) left.assert_equal(right, assert_column_order=False) with pytest.raises(AssertionError): left.assert_equal(right, assert_column_order=True) # check row order left = create_plain_frame(["a:int", "b:int"], 10, reverse_rows=True) right = create_plain_frame(["a:int", "b:int"], 10) left.assert_equal(right, assert_row_order=False) with pytest.raises(AssertionError): left.assert_equal(right, assert_row_order=True) def test_plainframe_assert_equal_missings(): # nan should be equal left = create_plainframe_single([NaN, 1], "float") right = create_plainframe_single([NaN, 1], "float") left.assert_equal(right) # Null should be equal left = create_plainframe_single([NULL, 1], "float") right = create_plainframe_single([NULL, 1], "float") left.assert_equal(right) # null should be different from other values with pytest.raises(AssertionError): left = create_plainframe_single(["2019-01-01"], "datetime") right = create_plainframe_single([NULL], "datetime") left.assert_equal(right) # nan should be different from other values with pytest.raises(AssertionError): left = create_plainframe_single([1.1], "float") right = create_plainframe_single([NaN], "float") left.assert_equal(right)
[ "pandas.api.types.is_float_dtype", "pywrangler.util.testing.plainframe.ConverterFromPandas", "pandas.api.types.LongType", "pandas.api.types.is_object_dtype", "pandas.api.types.is_datetime64_dtype", "pandas.api.types.is_bool_dtype", "pywrangler.util.testing.plainframe.PlainFrame.from_pandas", "pandas.DataFrame", "pandas.api.types.is_integer_dtype", "pytest.raises", "pywrangler.util.testing.plainframe.PlainFrame", "pandas.api.types.DoubleType", "numpy.testing.assert_equal", "pandas.api.types.BooleanType", "pywrangler.util.testing.plainframe.PlainColumn.from_plain", "pywrangler.util.testing.plainframe.PlainFrame.from_plain", "pandas.api.types.TimestampType", "pandas.api.types.StringType", "datetime.date", "datetime.datetime", "pandas.api.types.ShortType", "pandas.Series", "pandas.api.types.IntegerType", "pandas.Timestamp", "pywrangler.util.testing.plainframe.PlainFrame.from_dict", "pandas.api.types.FloatType", "pandas.api.types.DateType", "pandas.isnull", "pandas.api.types.StructType", "collections.OrderedDict" ]
[((573, 632), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': 'data', 'dtypes': 'cols', 'columns': 'cols'}), '(data=data, dtypes=cols, columns=cols)\n', (594, 632), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((913, 972), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': 'data', 'dtypes': 'cols', 'columns': 'cols'}), '(data=data, dtypes=cols, columns=cols)\n', (934, 972), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((2827, 2852), 'pandas.api.types.StructType', 'types.StructType', (['columns'], {}), '(columns)\n', (2843, 2852), False, 'from pandas.api import types\n'), ((3709, 3773), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': 'data', 'dtypes': 'dtypes', 'columns': 'columns'}), '(data=data, dtypes=dtypes, columns=columns)\n', (3730, 3773), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((4122, 4186), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': 'data', 'dtypes': 'dtypes', 'columns': 'columns'}), '(data=data, dtypes=dtypes, columns=columns)\n', (4143, 4186), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((4301, 4366), 'pywrangler.util.testing.plainframe.PlainColumn.from_plain', 'PlainColumn.from_plain', ([], {'name': '"""int"""', 'dtype': '"""int"""', 'values': '[1, 2, 3]'}), "(name='int', dtype='int', values=[1, 2, 3])\n", (4323, 4366), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((4484, 4524), 'pywrangler.util.testing.plainframe.PlainFrame', 'PlainFrame', ([], {'plaincolumns': '(plain_column,)'}), '(plaincolumns=(plain_column,))\n', (4494, 4524), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((4760, 4824), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[]', 'columns': "['col1:int', 'col2:str']"}), "(data=[], columns=['col1:int', 'col2:str'])\n", (4781, 4824), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((5077, 5126), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['col1', 'col2']", 'dtype': 'int'}), "(columns=['col1', 'col2'], dtype=int)\n", (5089, 5126), True, 'import pandas as pd\n'), ((5136, 5163), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['dfp'], {}), '(dfp)\n', (5158, 5163), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((6340, 6455), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': "[[1, 2], ['a', 'b']]", 'dtypes': "['int', 'str']", 'columns': "['int', 'str']", 'row_wise': '(False)'}), "(data=[[1, 2], ['a', 'b']], dtypes=['int', 'str'],\n columns=['int', 'str'], row_wise=False)\n", (6361, 6455), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((6583, 6698), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': "[[1, 1], ['a', 'a']]", 'dtypes': "['int', 'str']", 'columns': "['int', 'str']", 'row_wise': '(False)'}), "(data=[[1, 1], ['a', 'a']], dtypes=['int', 'str'],\n columns=['int', 'str'], row_wise=False)\n", (6604, 6698), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((11285, 11377), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1, 2]]', 'columns': "['a', 'b']", 'dtypes': "['int', 'int']"}), "(data=[[1, 2], [1, 2]], columns=['a', 'b'], dtypes=[\n 'int', 'int'])\n", (11306, 11377), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((11632, 11696), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': 'data', 'columns': 'columns', 'dtypes': 'dtypes'}), '(data=data, columns=columns, dtypes=dtypes)\n', (11653, 11696), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((11820, 11899), 'collections.OrderedDict', 'collections.OrderedDict', (["[('col1:int', [1, 2, 3]), ('col2:s', ['a', 'b', 'c'])]"], {}), "([('col1:int', [1, 2, 3]), ('col2:s', ['a', 'b', 'c'])])\n", (11843, 11899), False, 'import collections\n'), ((11933, 11959), 'pywrangler.util.testing.plainframe.PlainFrame.from_dict', 'PlainFrame.from_dict', (['data'], {}), '(data)\n', (11953, 11959), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((12009, 12054), 'numpy.testing.assert_equal', 'np_assert_equal', (['df.columns', "('col1', 'col2')"], {}), "(df.columns, ('col1', 'col2'))\n", (12024, 12054), True, 'from numpy.testing import assert_equal as np_assert_equal\n'), ((12059, 12101), 'numpy.testing.assert_equal', 'np_assert_equal', (['df.dtypes', "['int', 'str']"], {}), "(df.dtypes, ['int', 'str'])\n", (12074, 12101), True, 'from numpy.testing import assert_equal as np_assert_equal\n'), ((12485, 12532), 'numpy.testing.assert_equal', 'np_assert_equal', (['keys', "['col2:str', 'col1:int']"], {}), "(keys, ['col2:str', 'col1:int'])\n", (12500, 12532), True, 'from numpy.testing import assert_equal as np_assert_equal\n'), ((12557, 12595), 'numpy.testing.assert_equal', 'np_assert_equal', (['values[0]', "['1', '2']"], {}), "(values[0], ['1', '2'])\n", (12572, 12595), True, 'from numpy.testing import assert_equal as np_assert_equal\n'), ((12600, 12634), 'numpy.testing.assert_equal', 'np_assert_equal', (['values[1]', '[1, 2]'], {}), '(values[1], [1, 2])\n', (12615, 12634), True, 'from numpy.testing import assert_equal as np_assert_equal\n'), ((12724, 12750), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {}), '(df)\n', (12746, 12750), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((14323, 14362), 'pandas.DataFrame', 'pd.DataFrame', (["{'mixed': [1, 'foo bar']}"], {}), "({'mixed': [1, 'foo bar']})\n", (14335, 14362), True, 'import pandas as pd\n'), ((15182, 15216), 'pandas.DataFrame', 'pd.DataFrame', (["{'int': [1, np.NaN]}"], {}), "({'int': [1, np.NaN]})\n", (15194, 15216), True, 'import pandas as pd\n'), ((15231, 15273), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "['int']"}), "(df, dtypes=['int'])\n", (15253, 15273), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((15424, 15453), 'pandas.DataFrame', 'pd.DataFrame', (["{'int': [1, 2]}"], {}), "({'int': [1, 2]})\n", (15436, 15453), True, 'import pandas as pd\n'), ((15468, 15512), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "['float']"}), "(df, dtypes=['float'])\n", (15490, 15512), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((15666, 15701), 'pandas.DataFrame', 'pd.DataFrame', (["{'float': [1.0, 2.0]}"], {}), "({'float': [1.0, 2.0]})\n", (15678, 15701), True, 'import pandas as pd\n'), ((15716, 15758), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "['int']"}), "(df, dtypes=['int'])\n", (15738, 15758), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((15913, 15969), 'pandas.DataFrame', 'pd.DataFrame', (["{'datetime': ['2019-01-01', '2019-01-02']}"], {}), "({'datetime': ['2019-01-01', '2019-01-02']})\n", (15925, 15969), True, 'import pandas as pd\n'), ((15984, 16031), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "['datetime']"}), "(df, dtypes=['datetime'])\n", (16006, 16031), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((16294, 16350), 'pandas.DataFrame', 'pd.DataFrame', (["{'str': ['foo', 'bar', NaN]}"], {'dtype': 'object'}), "({'str': ['foo', 'bar', NaN]}, dtype=object)\n", (16306, 16350), True, 'import pandas as pd\n'), ((16365, 16391), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {}), '(df)\n', (16387, 16391), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((16652, 16682), 'pandas.Series', 'pd.Series', (['"""asd"""'], {'dtype': 'object'}), "('asd', dtype=object)\n", (16661, 16682), True, 'import pandas as pd\n'), ((16896, 16933), 'pandas.DataFrame', 'pd.DataFrame', (["{'dummy': ['asd', NaN]}"], {}), "({'dummy': ['asd', NaN]})\n", (16908, 16933), True, 'import pandas as pd\n'), ((16945, 16968), 'pywrangler.util.testing.plainframe.ConverterFromPandas', 'ConverterFromPandas', (['df'], {}), '(df)\n', (16964, 16968), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((17121, 17144), 'pywrangler.util.testing.plainframe.ConverterFromPandas', 'ConverterFromPandas', (['df'], {}), '(df)\n', (17140, 17144), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((17363, 17396), 'pandas.api.types.is_integer_dtype', 'types.is_integer_dtype', (["df['int']"], {}), "(df['int'])\n", (17385, 17396), False, 'from pandas.api import types\n'), ((17479, 17512), 'pandas.api.types.is_float_dtype', 'types.is_float_dtype', (["df['float']"], {}), "(df['float'])\n", (17499, 17512), False, 'from pandas.api import types\n'), ((17601, 17632), 'pandas.api.types.is_bool_dtype', 'types.is_bool_dtype', (["df['bool']"], {}), "(df['bool'])\n", (17620, 17632), False, 'from pandas.api import types\n'), ((17637, 17673), 'numpy.testing.assert_equal', 'np_assert_equal', (["df['bool'][0]", '(True)'], {}), "(df['bool'][0], True)\n", (17652, 17673), True, 'from numpy.testing import assert_equal as np_assert_equal\n'), ((17728, 17760), 'pandas.api.types.is_object_dtype', 'types.is_object_dtype', (["df['str']"], {}), "(df['str'])\n", (17749, 17760), False, 'from pandas.api import types\n'), ((17850, 17891), 'pandas.api.types.is_datetime64_dtype', 'types.is_datetime64_dtype', (["df['datetime']"], {}), "(df['datetime'])\n", (17875, 17891), False, 'from pandas.api import types\n'), ((18156, 18187), 'pandas.api.types.is_float_dtype', 'types.is_float_dtype', (["df['int']"], {}), "(df['int'])\n", (18176, 18187), False, 'from pandas.api import types\n'), ((18230, 18253), 'pandas.isnull', 'pd.isnull', (["df['int'][2]"], {}), "(df['int'][2])\n", (18239, 18253), True, 'import pandas as pd\n'), ((18383, 18408), 'pandas.isnull', 'pd.isnull', (["df['float'][2]"], {}), "(df['float'][2])\n", (18392, 18408), True, 'import pandas as pd\n'), ((18421, 18453), 'pandas.api.types.is_float_dtype', 'types.is_float_dtype', (["df['bool']"], {}), "(df['bool'])\n", (18441, 18453), False, 'from pandas.api import types\n'), ((18540, 18572), 'pandas.api.types.is_object_dtype', 'types.is_object_dtype', (["df['str']"], {}), "(df['str'])\n", (18561, 18572), False, 'from pandas.api import types\n'), ((18662, 18703), 'pandas.api.types.is_datetime64_dtype', 'types.is_datetime64_dtype', (["df['datetime']"], {}), "(df['datetime'])\n", (18687, 18703), False, 'from pandas.api import types\n'), ((20896, 20919), 'pandas.isnull', 'pd.isnull', (['res[1].float'], {}), '(res[1].float)\n', (20905, 20919), True, 'import pandas as pd\n'), ((4535, 4560), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4548, 4560), False, 'import pytest\n'), ((4570, 4609), 'pywrangler.util.testing.plainframe.PlainFrame', 'PlainFrame', ([], {'plaincolumns': '[plain_column]'}), '(plaincolumns=[plain_column])\n', (4580, 4609), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((4620, 4645), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4633, 4645), False, 'import pytest\n'), ((4655, 4683), 'pywrangler.util.testing.plainframe.PlainFrame', 'PlainFrame', ([], {'plaincolumns': '[1]'}), '(plaincolumns=[1])\n', (4665, 4683), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((5823, 5856), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)', '(10)'], {}), '(2019, 1, 1, 10)\n', (5840, 5856), False, 'import datetime\n'), ((7024, 7048), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7037, 7048), False, 'import pytest\n'), ((7609, 7634), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7622, 7634), False, 'import pytest\n'), ((7698, 7723), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7711, 7723), False, 'import pytest\n'), ((7958, 7983), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7971, 7983), False, 'import pytest\n'), ((8177, 8202), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8190, 8202), False, 'import pytest\n'), ((8278, 8303), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8291, 8303), False, 'import pytest\n'), ((8385, 8410), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8398, 8410), False, 'import pytest\n'), ((9002, 9027), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9015, 9027), False, 'import pytest\n'), ((9037, 9125), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1]]', 'columns': "['a', 'b']", 'dtypes': "['int', 'int']"}), "(data=[[1, 2], [1]], columns=['a', 'b'], dtypes=['int',\n 'int'])\n", (9058, 9125), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((9289, 9314), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9302, 9314), False, 'import pytest\n'), ((9324, 9410), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1, 2]]', 'columns': "['a']", 'dtypes': "['int', 'int']"}), "(data=[[1, 2], [1, 2]], columns=['a'], dtypes=['int',\n 'int'])\n", (9345, 9410), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((9573, 9598), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9586, 9598), False, 'import pytest\n'), ((9608, 9693), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1, 2]]', 'columns': "['a', 'b']", 'dtypes': "['int']"}), "(data=[[1, 2], [1, 2]], columns=['a', 'b'], dtypes=['int']\n )\n", (9629, 9693), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((9818, 9843), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9831, 9843), False, 'import pytest\n'), ((9853, 9950), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1, 2]]', 'columns': "['a', 'b']", 'dtypes': "['int', 'bad_type']"}), "(data=[[1, 2], [1, 2]], columns=['a', 'b'], dtypes=[\n 'int', 'bad_type'])\n", (9874, 9950), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((10081, 10105), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10094, 10105), False, 'import pytest\n'), ((10115, 10207), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1, 2]]', 'columns': "['a', 'b']", 'dtypes': "['int', 'str']"}), "(data=[[1, 2], [1, 2]], columns=['a', 'b'], dtypes=[\n 'int', 'str'])\n", (10136, 10207), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((10309, 10333), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10322, 10333), False, 'import pytest\n'), ((10343, 10436), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[1, 2], [1, 2]]', 'columns': "['a', 'b']", 'dtypes': "['int', 'bool']"}), "(data=[[1, 2], [1, 2]], columns=['a', 'b'], dtypes=[\n 'int', 'bool'])\n", (10364, 10436), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((10538, 10562), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10551, 10562), False, 'import pytest\n'), ((10572, 10670), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': "[['1', 2], ['1', 2]]", 'columns': "['a', 'b']", 'dtypes': "['float', 'int']"}), "(data=[['1', 2], ['1', 2]], columns=['a', 'b'], dtypes\n =['float', 'int'])\n", (10593, 10670), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((10772, 10796), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10785, 10796), False, 'import pytest\n'), ((10806, 10902), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': "[['1', 2], ['1', 2]]", 'columns': "['a', 'b']", 'dtypes': "['str', 'str']"}), "(data=[['1', 2], ['1', 2]], columns=['a', 'b'], dtypes\n =['str', 'str'])\n", (10827, 10902), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((11004, 11028), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (11017, 11028), False, 'import pytest\n'), ((11038, 11141), 'pywrangler.util.testing.plainframe.PlainFrame.from_plain', 'PlainFrame.from_plain', ([], {'data': '[[True, 2], [False, 2]]', 'columns': "['a', 'b']", 'dtypes': "['datetime', 'int']"}), "(data=[[True, 2], [False, 2]], columns=['a', 'b'],\n dtypes=['datetime', 'int'])\n", (11059, 11141), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((14372, 14396), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (14385, 14396), False, 'import pytest\n'), ((14406, 14432), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {}), '(df)\n', (14428, 14432), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((14516, 14541), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14529, 14541), False, 'import pytest\n'), ((14551, 14600), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "['int', 'str']"}), "(df, dtypes=['int', 'str'])\n", (14573, 14600), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((14611, 14636), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14624, 14636), False, 'import pytest\n'), ((14646, 14713), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "{'mixed': 'str', 'dummy': 'int'}"}), "(df, dtypes={'mixed': 'str', 'dummy': 'int'})\n", (14668, 14713), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((14797, 14822), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14810, 14822), False, 'import pytest\n'), ((14832, 14888), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "['not existant type']"}), "(df, dtypes=['not existant type'])\n", (14854, 14888), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((14899, 14924), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (14912, 14924), False, 'import pytest\n'), ((14934, 14999), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "{'mixed': 'not existant type'}"}), "(df, dtypes={'mixed': 'not existant type'})\n", (14956, 14999), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((15046, 15071), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (15059, 15071), False, 'import pytest\n'), ((15081, 15132), 'pywrangler.util.testing.plainframe.PlainFrame.from_pandas', 'PlainFrame.from_pandas', (['df'], {'dtypes': "{'dummy': 'str'}"}), "(df, dtypes={'dummy': 'str'})\n", (15103, 15132), False, 'from pywrangler.util.testing.plainframe import NULL, ConverterFromPandas, NaN, PlainColumn, PlainFrame\n'), ((16692, 16716), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (16705, 16716), False, 'import pytest\n'), ((17154, 17178), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (17167, 17178), False, 'import pytest\n'), ((17970, 18005), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01 10:00:00"""'], {}), "('2019-01-01 10:00:00')\n", (17982, 18005), True, 'import pandas as pd\n'), ((18782, 18817), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01 10:00:00"""'], {}), "('2019-01-01 10:00:00')\n", (18794, 18817), True, 'import pandas as pd\n'), ((21111, 21144), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)', '(10)'], {}), '(2019, 1, 1, 10)\n', (21128, 21144), False, 'import datetime\n'), ((21738, 21763), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (21751, 21763), False, 'import pytest\n'), ((22155, 22184), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (22168, 22184), False, 'import pytest\n'), ((22260, 22289), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (22273, 22289), False, 'import pytest\n'), ((22484, 22513), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (22497, 22513), False, 'import pytest\n'), ((22695, 22724), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (22708, 22724), False, 'import pytest\n'), ((22909, 22938), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (22922, 22938), False, 'import pytest\n'), ((23310, 23339), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (23323, 23339), False, 'import pytest\n'), ((23614, 23643), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (23627, 23643), False, 'import pytest\n'), ((24143, 24172), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (24156, 24172), False, 'import pytest\n'), ((24394, 24423), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (24407, 24423), False, 'import pytest\n'), ((2267, 2286), 'pandas.api.types.IntegerType', 'types.IntegerType', ([], {}), '()\n', (2284, 2286), False, 'from pandas.api import types\n'), ((2318, 2335), 'pandas.api.types.ShortType', 'types.ShortType', ([], {}), '()\n', (2333, 2335), False, 'from pandas.api import types\n'), ((2365, 2381), 'pandas.api.types.LongType', 'types.LongType', ([], {}), '()\n', (2379, 2381), False, 'from pandas.api import types\n'), ((2409, 2428), 'pandas.api.types.BooleanType', 'types.BooleanType', ([], {}), '()\n', (2426, 2428), False, 'from pandas.api import types\n'), ((2458, 2475), 'pandas.api.types.FloatType', 'types.FloatType', ([], {}), '()\n', (2473, 2475), False, 'from pandas.api import types\n'), ((2505, 2523), 'pandas.api.types.DoubleType', 'types.DoubleType', ([], {}), '()\n', (2521, 2523), False, 'from pandas.api import types\n'), ((2550, 2568), 'pandas.api.types.StringType', 'types.StringType', ([], {}), '()\n', (2566, 2568), False, 'from pandas.api import types\n'), ((2600, 2621), 'pandas.api.types.TimestampType', 'types.TimestampType', ([], {}), '()\n', (2619, 2621), False, 'from pandas.api import types\n'), ((2649, 2665), 'pandas.api.types.DateType', 'types.DateType', ([], {}), '()\n', (2663, 2665), False, 'from pandas.api import types\n'), ((13951, 13980), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (13968, 13980), False, 'import datetime\n'), ((13982, 14011), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(2)'], {}), '(2019, 1, 2)\n', (13999, 14011), False, 'import datetime\n'), ((14185, 14214), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (14202, 14214), False, 'import datetime\n'), ((16160, 16189), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (16177, 16189), False, 'import datetime\n'), ((16191, 16220), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(2)'], {}), '(2019, 1, 2)\n', (16208, 16220), False, 'import datetime\n'), ((20380, 20405), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (20393, 20405), False, 'import pytest\n'), ((1316, 1342), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01"""'], {}), "('2019-01-01')\n", (1328, 1342), True, 'import pandas as pd\n'), ((1344, 1370), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-02"""'], {}), "('2019-01-02')\n", (1356, 1370), True, 'import pandas as pd\n'), ((1398, 1424), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01"""'], {}), "('2019-01-01')\n", (1410, 1424), True, 'import pandas as pd\n'), ((1838, 1867), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (1855, 1867), False, 'import datetime\n'), ((1891, 1920), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(2)'], {}), '(2019, 1, 2)\n', (1908, 1920), False, 'import datetime\n'), ((1969, 1994), 'datetime.date', 'datetime.date', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (1982, 1994), False, 'import datetime\n'), ((2014, 2039), 'datetime.date', 'datetime.date', (['(2019)', '(1)', '(2)'], {}), '(2019, 1, 2)\n', (2027, 2039), False, 'import datetime\n'), ((2706, 2724), 'pandas.api.types.StringType', 'types.StringType', ([], {}), '()\n', (2722, 2724), False, 'from pandas.api import types\n'), ((2726, 2744), 'pandas.api.types.StringType', 'types.StringType', ([], {}), '()\n', (2742, 2744), False, 'from pandas.api import types\n'), ((2790, 2809), 'pandas.api.types.IntegerType', 'types.IntegerType', ([], {}), '()\n', (2807, 2809), False, 'from pandas.api import types\n'), ((20118, 20147), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (20135, 20147), False, 'import datetime\n'), ((20179, 20208), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(1)', '(2)'], {}), '(2019, 1, 2)\n', (20196, 20208), False, 'import datetime\n')]
import numpy as np import pickle as pk import matplotlib.pyplot as pl size = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] aveheight = [] # Obtain average height f_file = open('T2e_aveheight.pickle', 'rb') aveheight = pk.load(f_file) f_file.close() # Linear fit - find a crude estimate for a_0 para, var = np.polyfit(size, aveheight, 1, cov = True) xpts = np.linspace(0, 1050, 5000) ypts = para[0]*xpts + para[1] pl.figure() pl.plot(size, aveheight, 'bo', label = r"Average height $<h>$") pl.plot(xpts, ypts, 'r-', label = r"Linear fit with slope = %.3f $\pm$ %.3f" % (para[0], np.sqrt(np.diag(var))[0]) +"\n"+r"and intercept = %.3f $\pm$ %.3f" %(para[1], np.sqrt(np.diag(var))[1])) pl.xlabel(r"System size $L$") pl.ylabel(r"Average height of pile $<h>$") pl.grid() pl.legend() # Determine optimum a_0 by trying to fit the required log-log plot using a range of values testa0 = np.linspace(1.72, 1.74, 150) a0_err = 1/750 slopevar = [] for i in range(len(testa0)): y = [] for j in range(len(size)): y.append(abs(testa0[i] - aveheight[j] / size[j])) # slope, intercept, r_value, p_value, std_err = stats.linregress(np.log(np.array(newsize))/np.log(10), np.log(y)/np.log(10)) testpara, testvar = np.polyfit(np.log(np.array(size))/np.log(10), np.log(y)/np.log(10), 1, cov = True) slope_err = np.sqrt(np.diag(testvar))[0] slopevar.append(slope_err) a0index = slopevar.index(min(slopevar)) mina0 = testa0[a0index] pl.figure() pl.plot(testa0, slopevar, 'o') pl.xlabel(r"$a_0$") pl.ylabel("Standard error in the slope of the fit") pl.grid(True) # Plotting "best-fit" line together with two "worst-fit" lines to compare yfinal = mina0 - np.array(aveheight) / (np.array(size)) ybad1 = testa0[0] - np.array(aveheight) / (np.array(size)) ybad2 = testa0[-1] - np.array(aveheight) / (np.array(size)) parafinal, varfinal = np.polyfit(np.log(np.array(size))/np.log(10), np.log(yfinal)/np.log(10), 1, cov = True) pl.figure() pl.loglog(size, yfinal, 'o', label = r"Best-fit line with $a_0 = %.3f \pm %.3f$" % (mina0, a0_err)) pl.loglog(size, ybad1, 'o', label = r"Line with $a_0 = %.3f \pm %.3f$" % (testa0[0], a0_err)) pl.loglog(size, ybad2, 'o', label = r"Line with $a_0 = %.3f \pm %.3f$" % (testa0[-1], a0_err)) pl.xlabel(r"System size $L$") pl.ylabel(r"($a_0 - <h>)/ L$") pl.grid(True) # Try polynomial fitting for the "worst-fit" lines parabad1 = np.polyfit(np.log(np.array(size))/np.log(10), np.log(ybad1)/np.log(10), 2) parabad2 = np.polyfit(np.log(np.array(size))/np.log(10), np.log(ybad2)/np.log(10), 2) xptsbad = np.logspace(0.1, 3, 5000) yptsbad1 = 10**(parabad1[0]*(np.log(xptsbad)/np.log(10))**2 + parabad1[1]*(np.log(xptsbad)/np.log(10)) + parabad1[2]) pl.loglog(xptsbad, yptsbad1, 'r--', label = "Quadratic fits") yptsbad2 = 10**(parabad2[0]*(np.log(xptsbad)/np.log(10))**2 + parabad2[1]*(np.log(xptsbad)/np.log(10)) + parabad2[2]) yptsfinal = 10**(parafinal[0]*(np.log(xptsbad)/np.log(10)) + parafinal[1]) # 10**(paracurve[0]*(np.log(xptsbad)/np.log(10))*(1 - paracurve[1]*(np.log(xptsbad)/np.log(10))**(-paracurve[2]))) # pl.loglog(xptsbad, yptsbad2, 'r--') pl.loglog(xptsbad, yptsfinal, 'k--', label = r"Linear fit with slope = $%.3f \pm %.3f$" %(parafinal[0], np.sqrt(np.diag(varfinal))[0]) + "\n" + "and intercept = $%.3f \pm %.3f$" % (parafinal[1], np.sqrt(np.diag(varfinal))[1])) pl.legend() # Calculate a_1 and w_1 from the intercept and slope respectively a1 = 10**(parafinal[1] - np.log(mina0)/np.log(10)) w1 = -parafinal[0] data = [mina0, a1, w1] # a_0, a_1, w_1 # Save parafinal and varfinal for use in Task 2g f_file1 = open('T2e_para.pickle', 'wb') pk.dump(data, f_file1) f_file1.close()
[ "matplotlib.pyplot.loglog", "pickle.dump", "numpy.log", "matplotlib.pyplot.plot", "numpy.polyfit", "numpy.logspace", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "pickle.load", "numpy.array", "numpy.linspace", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.grid", "numpy.diag" ]
[((228, 243), 'pickle.load', 'pk.load', (['f_file'], {}), '(f_file)\n', (235, 243), True, 'import pickle as pk\n'), ((321, 361), 'numpy.polyfit', 'np.polyfit', (['size', 'aveheight', '(1)'], {'cov': '(True)'}), '(size, aveheight, 1, cov=True)\n', (331, 361), True, 'import numpy as np\n'), ((372, 398), 'numpy.linspace', 'np.linspace', (['(0)', '(1050)', '(5000)'], {}), '(0, 1050, 5000)\n', (383, 398), True, 'import numpy as np\n'), ((433, 444), 'matplotlib.pyplot.figure', 'pl.figure', ([], {}), '()\n', (442, 444), True, 'import matplotlib.pyplot as pl\n'), ((446, 506), 'matplotlib.pyplot.plot', 'pl.plot', (['size', 'aveheight', '"""bo"""'], {'label': '"""Average height $<h>$"""'}), "(size, aveheight, 'bo', label='Average height $<h>$')\n", (453, 506), True, 'import matplotlib.pyplot as pl\n'), ((707, 735), 'matplotlib.pyplot.xlabel', 'pl.xlabel', (['"""System size $L$"""'], {}), "('System size $L$')\n", (716, 735), True, 'import matplotlib.pyplot as pl\n'), ((738, 779), 'matplotlib.pyplot.ylabel', 'pl.ylabel', (['"""Average height of pile $<h>$"""'], {}), "('Average height of pile $<h>$')\n", (747, 779), True, 'import matplotlib.pyplot as pl\n'), ((782, 791), 'matplotlib.pyplot.grid', 'pl.grid', ([], {}), '()\n', (789, 791), True, 'import matplotlib.pyplot as pl\n'), ((793, 804), 'matplotlib.pyplot.legend', 'pl.legend', ([], {}), '()\n', (802, 804), True, 'import matplotlib.pyplot as pl\n'), ((909, 937), 'numpy.linspace', 'np.linspace', (['(1.72)', '(1.74)', '(150)'], {}), '(1.72, 1.74, 150)\n', (920, 937), True, 'import numpy as np\n'), ((1495, 1506), 'matplotlib.pyplot.figure', 'pl.figure', ([], {}), '()\n', (1504, 1506), True, 'import matplotlib.pyplot as pl\n'), ((1508, 1538), 'matplotlib.pyplot.plot', 'pl.plot', (['testa0', 'slopevar', '"""o"""'], {}), "(testa0, slopevar, 'o')\n", (1515, 1538), True, 'import matplotlib.pyplot as pl\n'), ((1540, 1558), 'matplotlib.pyplot.xlabel', 'pl.xlabel', (['"""$a_0$"""'], {}), "('$a_0$')\n", (1549, 1558), True, 'import matplotlib.pyplot as pl\n'), ((1561, 1612), 'matplotlib.pyplot.ylabel', 'pl.ylabel', (['"""Standard error in the slope of the fit"""'], {}), "('Standard error in the slope of the fit')\n", (1570, 1612), True, 'import matplotlib.pyplot as pl\n'), ((1614, 1627), 'matplotlib.pyplot.grid', 'pl.grid', (['(True)'], {}), '(True)\n', (1621, 1627), True, 'import matplotlib.pyplot as pl\n'), ((1999, 2010), 'matplotlib.pyplot.figure', 'pl.figure', ([], {}), '()\n', (2008, 2010), True, 'import matplotlib.pyplot as pl\n'), ((2012, 2114), 'matplotlib.pyplot.loglog', 'pl.loglog', (['size', 'yfinal', '"""o"""'], {'label': "('Best-fit line with $a_0 = %.3f \\\\pm %.3f$' % (mina0, a0_err))"}), "(size, yfinal, 'o', label=\n 'Best-fit line with $a_0 = %.3f \\\\pm %.3f$' % (mina0, a0_err))\n", (2021, 2114), True, 'import matplotlib.pyplot as pl\n'), ((2113, 2209), 'matplotlib.pyplot.loglog', 'pl.loglog', (['size', 'ybad1', '"""o"""'], {'label': "('Line with $a_0 = %.3f \\\\pm %.3f$' % (testa0[0], a0_err))"}), "(size, ybad1, 'o', label='Line with $a_0 = %.3f \\\\pm %.3f$' % (\n testa0[0], a0_err))\n", (2122, 2209), True, 'import matplotlib.pyplot as pl\n'), ((2208, 2305), 'matplotlib.pyplot.loglog', 'pl.loglog', (['size', 'ybad2', '"""o"""'], {'label': "('Line with $a_0 = %.3f \\\\pm %.3f$' % (testa0[-1], a0_err))"}), "(size, ybad2, 'o', label='Line with $a_0 = %.3f \\\\pm %.3f$' % (\n testa0[-1], a0_err))\n", (2217, 2305), True, 'import matplotlib.pyplot as pl\n'), ((2304, 2332), 'matplotlib.pyplot.xlabel', 'pl.xlabel', (['"""System size $L$"""'], {}), "('System size $L$')\n", (2313, 2332), True, 'import matplotlib.pyplot as pl\n'), ((2335, 2364), 'matplotlib.pyplot.ylabel', 'pl.ylabel', (['"""($a_0 - <h>)/ L$"""'], {}), "('($a_0 - <h>)/ L$')\n", (2344, 2364), True, 'import matplotlib.pyplot as pl\n'), ((2367, 2380), 'matplotlib.pyplot.grid', 'pl.grid', (['(True)'], {}), '(True)\n', (2374, 2380), True, 'import matplotlib.pyplot as pl\n'), ((2624, 2649), 'numpy.logspace', 'np.logspace', (['(0.1)', '(3)', '(5000)'], {}), '(0.1, 3, 5000)\n', (2635, 2649), True, 'import numpy as np\n'), ((2771, 2830), 'matplotlib.pyplot.loglog', 'pl.loglog', (['xptsbad', 'yptsbad1', '"""r--"""'], {'label': '"""Quadratic fits"""'}), "(xptsbad, yptsbad1, 'r--', label='Quadratic fits')\n", (2780, 2830), True, 'import matplotlib.pyplot as pl\n'), ((3147, 3182), 'matplotlib.pyplot.loglog', 'pl.loglog', (['xptsbad', 'yptsbad2', '"""r--"""'], {}), "(xptsbad, yptsbad2, 'r--')\n", (3156, 3182), True, 'import matplotlib.pyplot as pl\n'), ((3412, 3423), 'matplotlib.pyplot.legend', 'pl.legend', ([], {}), '()\n', (3421, 3423), True, 'import matplotlib.pyplot as pl\n'), ((3699, 3721), 'pickle.dump', 'pk.dump', (['data', 'f_file1'], {}), '(data, f_file1)\n', (3706, 3721), True, 'import pickle as pk\n'), ((1723, 1742), 'numpy.array', 'np.array', (['aveheight'], {}), '(aveheight)\n', (1731, 1742), True, 'import numpy as np\n'), ((1746, 1760), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (1754, 1760), True, 'import numpy as np\n'), ((1783, 1802), 'numpy.array', 'np.array', (['aveheight'], {}), '(aveheight)\n', (1791, 1802), True, 'import numpy as np\n'), ((1806, 1820), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (1814, 1820), True, 'import numpy as np\n'), ((1844, 1863), 'numpy.array', 'np.array', (['aveheight'], {}), '(aveheight)\n', (1852, 1863), True, 'import numpy as np\n'), ((1867, 1881), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (1875, 1881), True, 'import numpy as np\n'), ((1942, 1952), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (1948, 1952), True, 'import numpy as np\n'), ((1954, 1968), 'numpy.log', 'np.log', (['yfinal'], {}), '(yfinal)\n', (1960, 1968), True, 'import numpy as np\n'), ((1969, 1979), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (1975, 1979), True, 'import numpy as np\n'), ((2481, 2491), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2487, 2491), True, 'import numpy as np\n'), ((2493, 2506), 'numpy.log', 'np.log', (['ybad1'], {}), '(ybad1)\n', (2499, 2506), True, 'import numpy as np\n'), ((2507, 2517), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2513, 2517), True, 'import numpy as np\n'), ((2568, 2578), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2574, 2578), True, 'import numpy as np\n'), ((2580, 2593), 'numpy.log', 'np.log', (['ybad2'], {}), '(ybad2)\n', (2586, 2593), True, 'import numpy as np\n'), ((2594, 2604), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2600, 2604), True, 'import numpy as np\n'), ((1295, 1305), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (1301, 1305), True, 'import numpy as np\n'), ((1307, 1316), 'numpy.log', 'np.log', (['y'], {}), '(y)\n', (1313, 1316), True, 'import numpy as np\n'), ((1317, 1327), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (1323, 1327), True, 'import numpy as np\n'), ((1369, 1385), 'numpy.diag', 'np.diag', (['testvar'], {}), '(testvar)\n', (1376, 1385), True, 'import numpy as np\n'), ((1926, 1940), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (1934, 1940), True, 'import numpy as np\n'), ((2465, 2479), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (2473, 2479), True, 'import numpy as np\n'), ((2552, 2566), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (2560, 2566), True, 'import numpy as np\n'), ((3519, 3532), 'numpy.log', 'np.log', (['mina0'], {}), '(mina0)\n', (3525, 3532), True, 'import numpy as np\n'), ((3533, 3543), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (3539, 3543), True, 'import numpy as np\n'), ((1279, 1293), 'numpy.array', 'np.array', (['size'], {}), '(size)\n', (1287, 1293), True, 'import numpy as np\n'), ((2984, 2999), 'numpy.log', 'np.log', (['xptsbad'], {}), '(xptsbad)\n', (2990, 2999), True, 'import numpy as np\n'), ((3000, 3010), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (3006, 3010), True, 'import numpy as np\n'), ((2726, 2741), 'numpy.log', 'np.log', (['xptsbad'], {}), '(xptsbad)\n', (2732, 2741), True, 'import numpy as np\n'), ((2742, 2752), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2748, 2752), True, 'import numpy as np\n'), ((2909, 2924), 'numpy.log', 'np.log', (['xptsbad'], {}), '(xptsbad)\n', (2915, 2924), True, 'import numpy as np\n'), ((2925, 2935), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2931, 2935), True, 'import numpy as np\n'), ((2680, 2695), 'numpy.log', 'np.log', (['xptsbad'], {}), '(xptsbad)\n', (2686, 2695), True, 'import numpy as np\n'), ((2696, 2706), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2702, 2706), True, 'import numpy as np\n'), ((2863, 2878), 'numpy.log', 'np.log', (['xptsbad'], {}), '(xptsbad)\n', (2869, 2878), True, 'import numpy as np\n'), ((2879, 2889), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (2885, 2889), True, 'import numpy as np\n'), ((687, 699), 'numpy.diag', 'np.diag', (['var'], {}), '(var)\n', (694, 699), True, 'import numpy as np\n'), ((3387, 3404), 'numpy.diag', 'np.diag', (['varfinal'], {}), '(varfinal)\n', (3394, 3404), True, 'import numpy as np\n'), ((608, 620), 'numpy.diag', 'np.diag', (['var'], {}), '(var)\n', (615, 620), True, 'import numpy as np\n'), ((3296, 3313), 'numpy.diag', 'np.diag', (['varfinal'], {}), '(varfinal)\n', (3303, 3313), True, 'import numpy as np\n')]
''' atlas.py: part of pybraincompare package Functions to integrate atlases in image comparison ''' from __future__ import print_function from __future__ import absolute_import from __future__ import division from builtins import str from builtins import range from past.utils import old_div from builtins import object from skimage.segmentation import mark_boundaries, find_boundaries from pybraincompare.template.futils import make_tmp_folder from scipy.spatial.distance import pdist, squareform from pybraincompare.report.colors import get_colors from skimage.segmentation import felzenszwalb from skimage.util import img_as_float from .maths import percent_to_float from nilearn import plotting from xml.dom import minidom import pylab as pl import nibabel import pandas import numpy import os import re class region(object): def __init__(self,label,index,x,y,z): self.label = label self.index = index self.x = x self.y = y self.z = z class atlas(object): ''' Atlas object to hold a nifti object and xml labels ''' def __init__(self, atlas_xml, atlas_file, views=["axial","sagittal","coronal"]): self.file = atlas_file self.xml = atlas_xml self.mr = nibabel.load(atlas_file) self.labels = self.read_xml(atlas_xml) self.svg, self.paths, self.svg_file = self.make_svg(views) def get_region_names(self): regions = dict() for value,region in self.labels.items(): regions[value] = region.label return regions def read_xml(self,atlas_xml): dom = minidom.parse(atlas_xml) atlases = [] image_file = os.path.split(os.path.splitext(self.file)[0])[-1] for atlas in dom.getElementsByTagName("summaryimagefile"): atlases.append(str(os.path.split(atlas.lastChild.nodeValue)[-1])) if image_file in atlases: labels = {} # A value of 0 indicates no label in the image labels["0"] = region("No_Label",0,0,0,0) for lab in dom.getElementsByTagName("label"): # Caution - the index is 1 less than image value idx = str(int(lab.getAttribute("index"))+1) labels[idx] = region(lab.lastChild.nodeValue.replace(" ","_"), (int(lab.getAttribute("index"))+1), lab.getAttribute("x"), lab.getAttribute("y"), lab.getAttribute("z")) return labels else: print("ERROR: xml file atlas name does not match given atlas name!") def get_static_svg(self): '''Generate static svg of atlas (cannot manipulate in d3)''' with make_tmp_folder() as temp_dir: output_file='%s/atlas.svg' %(temp_dir) plotting.plot_roi(self.mr,annotate=False, draw_cross=False, cmap="nipy_spectral", black_bg=False, output_file=output_file) with open(output_file,'r') as svg_file: svg_data = svg_file.readlines() return svg_data[4:] def make_svg(self,views): '''Generate path-based svg of atlas (paths we can manipulate in d3)''' import cairo # We will save complete svg for file, partial for embedding, and paths svg_data = dict(); svg_data_partial = dict(); svg_data_file = dict(); if isinstance(views,str): views = [views] self.views = [v.lower() for v in views] mr = self.mr.get_data() middles = [numpy.round(old_div(x,2)) for x in self.mr.get_shape()] # Create a color lookup table colors_html = get_colors(len(self.labels),"hex") self.color_lookup = self.make_color_lookup(colors_html) with make_tmp_folder() as temp_dir: # Get all unique regions (may not be present in every slice) regions = [ x for x in numpy.unique(mr) if x != 0] # Get colors - will later be changed colors = get_colors(len(self.labels),"decimal") # Generate an axial, sagittal, coronal view slices = dict() for v in views: # Keep a list of region names that correspond to paths region_names = [] # Generate each of the views if v == "axial": slices[v] = numpy.rot90(mr[:,:,middles[0]],2) elif v == "sagittal" : slices[v] = numpy.rot90(mr[middles[1],:,:],2) elif v == "coronal" : slices[v] = numpy.rot90(mr[:,middles[2],:],2) # For each region in the view, but not 0 regions = [ x for x in numpy.unique(slices[v]) if x != 0] # Write svg to temporary file output_file = '%s/%s_atlas.svg' %(temp_dir,v) fo = file(output_file, 'wb') # Set up the "context" - what cairo calls a canvas width, height = numpy.shape(slices[v]) surface = cairo.SVGSurface (fo, width*3, height*3) ctx = cairo.Context (surface) ctx.scale(3.,3.) # 90 degree rotation matrix rotation_matrix = cairo.Matrix.init_rotate(old_div(numpy.pi,2)) for rr in range(0,len(regions)): index_value = regions[rr] #region_name = self.labels[str(index_value)].label filtered = numpy.zeros(numpy.shape(slices[v])) filtered[slices[v] == regions[rr]] = 1 # We aren't using Canny anymore... region = img_as_float(find_boundaries(filtered)) # Solid color ctx.set_source_rgb (float(colors[index_value-1][0]), float(colors[index_value-1][1]), float(colors[index_value-1][2])) # Segment! segments_fz = felzenszwalb(region, scale=100, sigma=0.1, min_size=10) # For each cluster in the region, skipping value of 0 for c in range(1,len(numpy.unique(segments_fz))): cluster = numpy.zeros(numpy.shape(region)) cluster[segments_fz==c] = 1 # Create distance matrix for points x,y = numpy.where(cluster==1) points = [[x[i],y[i]] for i in range(0,len(x))] disty = squareform(pdist(points, 'euclidean')) # This keeps track of which we have already visited visited = []; row = 0; current = points[row] visited.append(row) # We need to remember the first point, for the last one fp = current while len(visited) != len(points): thisx = current[0] thisy = current[1] ctx.move_to(thisx, thisy) # Find closest point, only include cols not visited distances = disty[row,:] distance_lookup = dict() # preserve indices but still eliminate visited for j in range(0,len(distances)): if j not in visited: distance_lookup[j] = distances[j] # Get key minimum distance row = min(distance_lookup, key=distance_lookup.get) next = points[row] nextx = next[0] nexty = next[1] # If the distance is more than N pixels, close path # This resolves some of the rough edges too if min(distance_lookup) > 70: ctx.line_to(fp[0],fp[1]) ctx.set_line_width(1) ctx.close_path() fp = next else: ctx.line_to(nextx, nexty) # Set next point to be current visited.append(row) current = next # Go back to the first point ctx.move_to(current[0],current[1]) ctx.line_to(fp[0],fp[1]) # Close the path ctx.set_line_width (1) ctx.stroke() # Finish the surface surface.finish() fo.close() # Now grab the file, set attributes # group name based on atlas, region id based on matching color dom = minidom.parse(output_file) for group in dom.getElementsByTagName("g"): group.setAttribute("id",os.path.split(self.file)[-1]) group.setAttribute("class",v) regexp = re.compile("stroke:rgb") # Add class to svg - important so can manipulate in d3 dom.getElementsByTagName("svg")[0].setAttribute("class",v) for path in dom.getElementsByTagName("path"): style = path.getAttribute("style") # we have to use the color to look up the region color = [x for x in style.split(";") if regexp.search(x)][0] color = [percent_to_float(x) for x in color.replace("stroke:rgb(","").replace(")","").split(",")] region_index = [x for x in range(0,len(colors)) if numpy.equal(colors[x],color).all()][0]+1 region_label = self.labels[str(region_index)].label # We don't want to rely on cairo to style the paths self.remove_attributes(path,"style") self.set_attributes(path, ["id","stroke"], [region_label, self.color_lookup[region_label]]) svg_data_file[v] = dom.toxml() # get rid of just xml tag svg_data[v] = dom.toxml().replace("<?xml version=\"1.0\" ?>","") svg_data_partial[v] = "/n".join(dom.toxml().split("\n")[1:-1]) return svg_data, svg_data_partial, svg_data_file def save_svg(self,output_folder,views=None): '''Save svg data to file''' if not views: views = self.views if not output_folder: print("Please specify an output directory") else: atlas_name = os.path.split(self.file)[-1].replace("[.]","-") for v in views: outfile = "%s/%s-%s.svg" %(output_folder,atlas_name,v) with open(outfile ,"wb") as filey: filey.writelines(self.svg_file[v]) def set_attributes(self, path, attributes, new_values): '''Internal function to add/change svg attributes''' if isinstance(attributes,str): attributes = [attributes] if isinstance(new_values,str): new_values = [new_values] if len(attributes) == len(new_values): for a in range(0,len(attributes)): path.setAttribute(attributes[a],new_values[a]) else: print("Please provide attributes list with equal length to values.") def remove_attributes(self,path,attributes): '''Internal function to remove svg attributes''' if isinstance(attributes,str): attributes = [attributes] for attribute in attributes: path.removeAttribute(attribute) def make_color_lookup(self,new_colors): '''Create color lookup table corresponding to regions''' color_lookup = dict() new_color = new_colors[:] for index,region in self.labels.items(): color_lookup[region.label] = new_color.pop() return color_lookup
[ "past.utils.old_div", "numpy.shape", "numpy.rot90", "scipy.spatial.distance.pdist", "cairo.SVGSurface", "nilearn.plotting.plot_roi", "numpy.unique", "skimage.segmentation.find_boundaries", "numpy.equal", "builtins.str", "re.compile", "nibabel.load", "cairo.Context", "xml.dom.minidom.parse", "numpy.where", "pybraincompare.template.futils.make_tmp_folder", "os.path.splitext", "os.path.split", "skimage.segmentation.felzenszwalb" ]
[((1293, 1317), 'nibabel.load', 'nibabel.load', (['atlas_file'], {}), '(atlas_file)\n', (1305, 1317), False, 'import nibabel\n'), ((1653, 1677), 'xml.dom.minidom.parse', 'minidom.parse', (['atlas_xml'], {}), '(atlas_xml)\n', (1666, 1677), False, 'from xml.dom import minidom\n'), ((2841, 2858), 'pybraincompare.template.futils.make_tmp_folder', 'make_tmp_folder', ([], {}), '()\n', (2856, 2858), False, 'from pybraincompare.template.futils import make_tmp_folder\n'), ((2936, 3064), 'nilearn.plotting.plot_roi', 'plotting.plot_roi', (['self.mr'], {'annotate': '(False)', 'draw_cross': '(False)', 'cmap': '"""nipy_spectral"""', 'black_bg': '(False)', 'output_file': 'output_file'}), "(self.mr, annotate=False, draw_cross=False, cmap=\n 'nipy_spectral', black_bg=False, output_file=output_file)\n", (2953, 3064), False, 'from nilearn import plotting\n'), ((3958, 3975), 'pybraincompare.template.futils.make_tmp_folder', 'make_tmp_folder', ([], {}), '()\n', (3973, 3975), False, 'from pybraincompare.template.futils import make_tmp_folder\n'), ((3740, 3753), 'past.utils.old_div', 'old_div', (['x', '(2)'], {}), '(x, 2)\n', (3747, 3753), False, 'from past.utils import old_div\n'), ((5197, 5219), 'numpy.shape', 'numpy.shape', (['slices[v]'], {}), '(slices[v])\n', (5208, 5219), False, 'import numpy\n'), ((5246, 5289), 'cairo.SVGSurface', 'cairo.SVGSurface', (['fo', '(width * 3)', '(height * 3)'], {}), '(fo, width * 3, height * 3)\n', (5262, 5289), False, 'import cairo\n'), ((5309, 5331), 'cairo.Context', 'cairo.Context', (['surface'], {}), '(surface)\n', (5322, 5331), False, 'import cairo\n'), ((9382, 9408), 'xml.dom.minidom.parse', 'minidom.parse', (['output_file'], {}), '(output_file)\n', (9395, 9408), False, 'from xml.dom import minidom\n'), ((9618, 9642), 're.compile', 're.compile', (['"""stroke:rgb"""'], {}), "('stroke:rgb')\n", (9628, 9642), False, 'import re\n'), ((1734, 1761), 'os.path.splitext', 'os.path.splitext', (['self.file'], {}), '(self.file)\n', (1750, 1761), False, 'import os\n'), ((4098, 4114), 'numpy.unique', 'numpy.unique', (['mr'], {}), '(mr)\n', (4110, 4114), False, 'import numpy\n'), ((4566, 4602), 'numpy.rot90', 'numpy.rot90', (['mr[:, :, middles[0]]', '(2)'], {}), '(mr[:, :, middles[0]], 2)\n', (4577, 4602), False, 'import numpy\n'), ((5470, 5490), 'past.utils.old_div', 'old_div', (['numpy.pi', '(2)'], {}), '(numpy.pi, 2)\n', (5477, 5490), False, 'from past.utils import old_div\n'), ((6230, 6285), 'skimage.segmentation.felzenszwalb', 'felzenszwalb', (['region'], {'scale': '(100)', 'sigma': '(0.1)', 'min_size': '(10)'}), '(region, scale=100, sigma=0.1, min_size=10)\n', (6242, 6285), False, 'from skimage.segmentation import felzenszwalb\n'), ((1869, 1909), 'os.path.split', 'os.path.split', (['atlas.lastChild.nodeValue'], {}), '(atlas.lastChild.nodeValue)\n', (1882, 1909), False, 'import os\n'), ((4672, 4708), 'numpy.rot90', 'numpy.rot90', (['mr[middles[1], :, :]', '(2)'], {}), '(mr[middles[1], :, :], 2)\n', (4683, 4708), False, 'import numpy\n'), ((4907, 4930), 'numpy.unique', 'numpy.unique', (['slices[v]'], {}), '(slices[v])\n', (4919, 4930), False, 'import numpy\n'), ((5702, 5724), 'numpy.shape', 'numpy.shape', (['slices[v]'], {}), '(slices[v])\n', (5713, 5724), False, 'import numpy\n'), ((5882, 5907), 'skimage.segmentation.find_boundaries', 'find_boundaries', (['filtered'], {}), '(filtered)\n', (5897, 5907), False, 'from skimage.segmentation import mark_boundaries, find_boundaries\n'), ((6783, 6808), 'numpy.where', 'numpy.where', (['(cluster == 1)'], {}), '(cluster == 1)\n', (6794, 6808), False, 'import numpy\n'), ((11288, 11312), 'os.path.split', 'os.path.split', (['self.file'], {}), '(self.file)\n', (11301, 11312), False, 'import os\n'), ((4776, 4812), 'numpy.rot90', 'numpy.rot90', (['mr[:, middles[2], :]', '(2)'], {}), '(mr[:, middles[2], :], 2)\n', (4787, 4812), False, 'import numpy\n'), ((6544, 6569), 'numpy.unique', 'numpy.unique', (['segments_fz'], {}), '(segments_fz)\n', (6556, 6569), False, 'import numpy\n'), ((6619, 6638), 'numpy.shape', 'numpy.shape', (['region'], {}), '(region)\n', (6630, 6638), False, 'import numpy\n'), ((6922, 6948), 'scipy.spatial.distance.pdist', 'pdist', (['points', '"""euclidean"""'], {}), "(points, 'euclidean')\n", (6927, 6948), False, 'from scipy.spatial.distance import pdist, squareform\n'), ((9513, 9537), 'os.path.split', 'os.path.split', (['self.file'], {}), '(self.file)\n', (9526, 9537), False, 'import os\n'), ((10336, 10353), 'builtins.str', 'str', (['region_index'], {}), '(region_index)\n', (10339, 10353), False, 'from builtins import str\n'), ((10248, 10277), 'numpy.equal', 'numpy.equal', (['colors[x]', 'color'], {}), '(colors[x], color)\n', (10259, 10277), False, 'import numpy\n')]
# -*- coding: utf-8 -*- __author__ = "<NAME>" __email__ = "<EMAIL>" __version__ = "1.0.0" import os import sys import yaml ROS_CV = '/opt/ros/kinetic/lib/python2.7/dist-packages' if ROS_CV in sys.path: sys.path.remove(ROS_CV) import cv2 import numpy as np import matplotlib.pyplot as plt from transformations import euler_matrix, translation_matrix class InversePerspectiveMapping: def __init__(self, filename): self.info = self.load_camera_info(filename) self.frame_width = self.info['width'] self.frame_height = self.info['height'] # Intrinsics self.K = np.zeros((3, 4)) self.K[:, :3] = np.asarray(self.info['intrinsics']['K']).reshape(3, 3) self.D = np.asarray(self.info['intrinsics']['D']) # Extrinsics self.extrinsics_euler = np.radians(self.info['extrinsics']['rpy']) self.extrinsics_rotation = euler_matrix(self.extrinsics_euler[0], self.extrinsics_euler[1], self.extrinsics_euler[2]) self.extrinsics_translation = translation_matrix(self.info['extrinsics']['position']) # Homography calibration parameters self.ipm_matrix = None self.in_points = np.float32([(479, 407), (816, 408), (316, 678), (980, 682)]) # Checkerboard corners self.homography_dims = (500, 500) self.homography_image_dims = (2500, 2000) self.homography_base = 1040 self.homography_translation = np.asarray([[0, 0, 0], [0, 0, -1800], [0, 0, 0]]) # Metric calibration parameters self.metric_scale_factor = (0.09, 0.435) self.metric_rotation_yaw = -0.1 self.checkerboard_center = (115, 827) # Checkerboard center after homography self.calibration_ego_y = -3.946949 self.calibration_grid_px = 44 self.calibration_grid_m = 0.4 * 8 # 40cm, 8x8 self.ipm_px_to_m = self.calibration_grid_m / self.calibration_grid_px self.ipm_m_to_px = self.calibration_grid_px / self.calibration_grid_m # Overwrite calibration data if available if 'calibration' not in self.info: print('WARNING: Calibration not performed, run InversePerspectiveMapping.calibrate() first!') return else: print('Loading calibration data from file...') self.ipm_matrix = np.asarray(self.info['calibration']['ipm_matrix']).reshape(3, 3) self.ipm_image_dims = tuple(self.info['calibration']['ipm_image_dims'][::-1]) self.ipm_px_to_m = self.info['calibration']['ipm_px_to_m'] self.ipm_m_to_px = self.info['calibration']['ipm_m_to_px'] self.calibration_ego_y = self.info['calibration']['calibration_ego_y'] def load_camera_info(self, filename): with open(filename, 'r') as f: camera_info = yaml.load(f) return camera_info def transform_image(self, img): img = cv2.warpPerspective(img, self.ipm_matrix, self.ipm_image_dims) return img def transform_points_to_px(self, points, squeeze=True): ones = np.ones((len(points), 1)) if len(np.array(points).shape) == 1: points = np.expand_dims(points, axis=0) ones = np.array([[1]]) points_px = self.ipm_matrix @ np.hstack([points, ones]).T points_px = points_px / points_px[-1] if squeeze: return points_px.T[:, :2].squeeze() return points_px.T[:, :2] def transform_points_to_m(self, points): points_px = self.transform_points_to_px(points, squeeze=False) points_px[:, 0] = points_px[:, 0] - self.ipm_image_dims[0] / 2 points_px[:, 1] = self.ipm_image_dims[1] - points_px[:, 1] points_m = points_px * self.ipm_px_to_m points_m[:, 1] += self.calibration_ego_y return points_m.squeeze() def calibrate(self, frame): # Perspective mapping b, h, w = self.homography_base, self.homography_dims[0], self.homography_dims[1] out_points = np.float32([(b, b), (h + b, b), (b, w + b), (h + b, w + b)]) homography = cv2.getPerspectiveTransform(self.in_points, out_points) homography += self.homography_translation dst = cv2.warpPerspective(frame, homography, self.homography_image_dims) # Metric scale rectification dst = cv2.resize(dst, (0, 0), fx=self.metric_scale_factor[0], fy=self.metric_scale_factor[1]) scale = np.asarray([[self.metric_scale_factor[0], 0, 0], [0, self.metric_scale_factor[1], 0], [0, 0, 1]]) # Metric rotation rectification rotation = cv2.getRotationMatrix2D((dst.shape[1] / 2, dst.shape[0] / 2), self.metric_rotation_yaw, 1) dst = cv2.warpAffine(dst, rotation, (dst.shape[1], dst.shape[0])) rotation = np.vstack([rotation, [0, 0, 1]]) # Metric offset rectification board_center_px = self.calibration_ego_y * self.ipm_m_to_px offset_translation = np.asarray([[1, 0, -(self.checkerboard_center[0] - dst.shape[1] / 2)], [0, 1, -(self.checkerboard_center[1] - dst.shape[0] - board_center_px)], [0, 0, 1]]) dst = cv2.warpPerspective(dst, offset_translation, (dst.shape[1], dst.shape[0])) # Overall IPM matrix self.ipm_matrix = offset_translation @ rotation @ scale @ homography return dst, self.ipm_matrix def find_homography(self, frame, in_points, out_points): self.ipm_matrix = cv2.findHomography(in_points, out_points)[0] dst = cv2.warpPerspective(frame, self.ipm_matrix, self.homography_image_dims) return dst, self.ipm_matrix def apply_homography(self, point): point = np.r_[point, 1] out_point = self.ipm_matrix @ point out_point = out_point / out_point[-1] return out_point def roi_crop(img, size=[540, 720]): h, w, c = img.shape del_side = (w-size[1])/2 del_top = h- size[0] cropped_img = img[int(del_top):, int(del_side):int(-del_side), :] return cropped_img def pick_points(img): points = [] def draw_circle(event, x, y, flags, param): nonlocal points, img if event == cv2.EVENT_LBUTTONDBLCLK: cv2.circle(img, (x, y), 5, (255, 0, 0), -1) points.append([x, y]) print(points[-1]) win_name = 'Picker' cv2.namedWindow(win_name) cv2.setMouseCallback(win_name, draw_circle) cv2.moveWindow(win_name, 100, 100) while True: cv2.imshow(win_name, img) k = cv2.waitKey(20) & 0xFF if k == 27: break cv2.waitKey(0) cv2.destroyAllWindows() return np.array(points) def perform_calibration(config_file, image_file): ipm = InversePerspectiveMapping(config_file) win_name = 'Calibration' cv2.namedWindow(win_name) cv2.moveWindow(win_name, 100, 100) image = cv2.imread(image_file) image = roi_crop(image) # output, ipm_matrix = ipm.calibrate(image) output, ipm_matrix = ipm.find_homography(image) # Display calibration results print('ipm_matrix:', ipm_matrix.flatten()) # print('ipm_image_dims:', list(output.shape)[:2]) # print('ipm_px_to_m:', ipm.ipm_px_to_m) # print('ipm_m_to_px:', ipm.ipm_m_to_px) # print('calibration_ego_y:', ipm.calibration_ego_y) in_points = np.array([[385, 411], [716, 193], [391, 148], [-15, 199]]) # out_points = np.array([[0.36, 0], [0.56, 1.03], [1.48, 0], [-0.56, 0.8]]) for point in in_points: print(ipm.apply_homography(point)) # cv2.imshow(win_name, output) # cv2.waitKey(0) # cv2.destroyAllWindows() def reproject(ipm_matrix, image_points, world_points): points = np.c_[world_points, np.ones((len(world_points), 1))] points = (np.linalg.inv(ipm_matrix) @ points.T).T points = (points / points[:, -1].reshape(-1, 1))[:, :2] error = np.sqrt(np.mean((points - image_points) ** 2)) return points, error def reproject_world(ipm_matrix, image_points, world_points): points = np.c_[image_points, np.ones((len(image_points), 1))] points = (ipm_matrix @ points.T).T points = (points / points[:, -1].reshape(-1, 1))[:, :2] error = np.sqrt(np.mean((points - world_points) ** 2)) return points, error def find_homography_ransac(ipm, image, image_points, world_points): best_matrix = None best_error = 100000 weights = np.hstack([np.array([0.5] * 41) / 41, np.array([0.3] * 47) / 47, np.array([0.2] * 21) / 21]) for i in range(100): idx = np.random.choice(len(world_points), 50, replace=False, p=weights) output, ipm_matrix = ipm.find_homography(image, image_points[idx], world_points[idx]) _, error1 = reproject(ipm_matrix, image_points, world_points) _, error2 = reproject_world(ipm_matrix, image_points, world_points) # print(error1, error2) error = error1 if error < best_error: best_error = error best_matrix = ipm_matrix print(best_error) return best_matrix def display_reprojection(image, ipm_matrix, image_points, world_points, world=False): if world: points, error = reproject_world(ipm_matrix, image_points, world_points) org_points = world_points else: points, error = reproject(ipm_matrix, image_points, world_points) org_points = image_points if not world: plt.imshow(image) plt.scatter(org_points[:, 0], org_points[:, 1], c='g') plt.scatter(points[:, 0], points[:, 1], c='r') plt.grid() plt.show() def perform_calibration2(config_file, image_file): ipm = InversePerspectiveMapping(config_file) image = cv2.imread(image_file) image = roi_crop(image) # points = pick_points(image) from world_points import world_points from image_points import image_points world_points, image_points = np.vstack(world_points), np.vstack(image_points) ipm_matrix = find_homography_ransac(ipm, image, image_points, world_points) display_reprojection(image, ipm_matrix, image_points, world_points) display_reprojection(image, ipm_matrix, image_points, world_points, world=True) # Display calibration results print('ipm_matrix:', ipm_matrix.flatten().tolist()) def test_calibration(config_file, image_file, display=False): ipm = InversePerspectiveMapping(config_file) print(ipm.transform_points_to_px(ipm.in_points)) print(ipm.transform_points_to_m(ipm.in_points)) if display: win_name = 'Calibration Test' cv2.namedWindow(win_name) cv2.moveWindow(win_name, 100, 100) image = cv2.imread(image_file) output = ipm.transform_image(image) cv2.imshow(win_name, output) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == '__main__': perform_calibration2('camera_info.yaml', 'ipm2.jpg') # test_calibration('camera_info.yaml', 'Calibration-04-00001--3.946949.jpg', display=True)
[ "yaml.load", "sys.path.remove", "cv2.getPerspectiveTransform", "cv2.warpAffine", "numpy.mean", "cv2.imshow", "cv2.getRotationMatrix2D", "cv2.warpPerspective", "matplotlib.pyplot.imshow", "transformations.euler_matrix", "cv2.setMouseCallback", "cv2.destroyAllWindows", "cv2.resize", "numpy.radians", "cv2.circle", "matplotlib.pyplot.show", "cv2.waitKey", "numpy.asarray", "numpy.hstack", "numpy.linalg.inv", "matplotlib.pyplot.grid", "numpy.vstack", "matplotlib.pyplot.scatter", "numpy.float32", "transformations.translation_matrix", "numpy.zeros", "numpy.expand_dims", "cv2.imread", "numpy.array", "cv2.moveWindow", "cv2.findHomography", "cv2.namedWindow" ]
[((205, 228), 'sys.path.remove', 'sys.path.remove', (['ROS_CV'], {}), '(ROS_CV)\n', (220, 228), False, 'import sys\n'), ((6351, 6376), 'cv2.namedWindow', 'cv2.namedWindow', (['win_name'], {}), '(win_name)\n', (6366, 6376), False, 'import cv2\n'), ((6381, 6424), 'cv2.setMouseCallback', 'cv2.setMouseCallback', (['win_name', 'draw_circle'], {}), '(win_name, draw_circle)\n', (6401, 6424), False, 'import cv2\n'), ((6429, 6463), 'cv2.moveWindow', 'cv2.moveWindow', (['win_name', '(100)', '(100)'], {}), '(win_name, 100, 100)\n', (6443, 6463), False, 'import cv2\n'), ((6581, 6595), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (6592, 6595), False, 'import cv2\n'), ((6600, 6623), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6621, 6623), False, 'import cv2\n'), ((6635, 6651), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (6643, 6651), True, 'import numpy as np\n'), ((6787, 6812), 'cv2.namedWindow', 'cv2.namedWindow', (['win_name'], {}), '(win_name)\n', (6802, 6812), False, 'import cv2\n'), ((6817, 6851), 'cv2.moveWindow', 'cv2.moveWindow', (['win_name', '(100)', '(100)'], {}), '(win_name, 100, 100)\n', (6831, 6851), False, 'import cv2\n'), ((6865, 6887), 'cv2.imread', 'cv2.imread', (['image_file'], {}), '(image_file)\n', (6875, 6887), False, 'import cv2\n'), ((7317, 7375), 'numpy.array', 'np.array', (['[[385, 411], [716, 193], [391, 148], [-15, 199]]'], {}), '([[385, 411], [716, 193], [391, 148], [-15, 199]])\n', (7325, 7375), True, 'import numpy as np\n'), ((9393, 9447), 'matplotlib.pyplot.scatter', 'plt.scatter', (['org_points[:, 0]', 'org_points[:, 1]'], {'c': '"""g"""'}), "(org_points[:, 0], org_points[:, 1], c='g')\n", (9404, 9447), True, 'import matplotlib.pyplot as plt\n'), ((9452, 9498), 'matplotlib.pyplot.scatter', 'plt.scatter', (['points[:, 0]', 'points[:, 1]'], {'c': '"""r"""'}), "(points[:, 0], points[:, 1], c='r')\n", (9463, 9498), True, 'import matplotlib.pyplot as plt\n'), ((9503, 9513), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (9511, 9513), True, 'import matplotlib.pyplot as plt\n'), ((9518, 9528), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9526, 9528), True, 'import matplotlib.pyplot as plt\n'), ((9643, 9665), 'cv2.imread', 'cv2.imread', (['image_file'], {}), '(image_file)\n', (9653, 9665), False, 'import cv2\n'), ((607, 623), 'numpy.zeros', 'np.zeros', (['(3, 4)'], {}), '((3, 4))\n', (615, 623), True, 'import numpy as np\n'), ((720, 760), 'numpy.asarray', 'np.asarray', (["self.info['intrinsics']['D']"], {}), "(self.info['intrinsics']['D'])\n", (730, 760), True, 'import numpy as np\n'), ((815, 857), 'numpy.radians', 'np.radians', (["self.info['extrinsics']['rpy']"], {}), "(self.info['extrinsics']['rpy'])\n", (825, 857), True, 'import numpy as np\n'), ((893, 988), 'transformations.euler_matrix', 'euler_matrix', (['self.extrinsics_euler[0]', 'self.extrinsics_euler[1]', 'self.extrinsics_euler[2]'], {}), '(self.extrinsics_euler[0], self.extrinsics_euler[1], self.\n extrinsics_euler[2])\n', (905, 988), False, 'from transformations import euler_matrix, translation_matrix\n'), ((1034, 1089), 'transformations.translation_matrix', 'translation_matrix', (["self.info['extrinsics']['position']"], {}), "(self.info['extrinsics']['position'])\n", (1052, 1089), False, 'from transformations import euler_matrix, translation_matrix\n'), ((1191, 1251), 'numpy.float32', 'np.float32', (['[(479, 407), (816, 408), (316, 678), (980, 682)]'], {}), '([(479, 407), (816, 408), (316, 678), (980, 682)])\n', (1201, 1251), True, 'import numpy as np\n'), ((1442, 1491), 'numpy.asarray', 'np.asarray', (['[[0, 0, 0], [0, 0, -1800], [0, 0, 0]]'], {}), '([[0, 0, 0], [0, 0, -1800], [0, 0, 0]])\n', (1452, 1491), True, 'import numpy as np\n'), ((2901, 2963), 'cv2.warpPerspective', 'cv2.warpPerspective', (['img', 'self.ipm_matrix', 'self.ipm_image_dims'], {}), '(img, self.ipm_matrix, self.ipm_image_dims)\n', (2920, 2963), False, 'import cv2\n'), ((3981, 4041), 'numpy.float32', 'np.float32', (['[(b, b), (h + b, b), (b, w + b), (h + b, w + b)]'], {}), '([(b, b), (h + b, b), (b, w + b), (h + b, w + b)])\n', (3991, 4041), True, 'import numpy as np\n'), ((4063, 4118), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['self.in_points', 'out_points'], {}), '(self.in_points, out_points)\n', (4090, 4118), False, 'import cv2\n'), ((4183, 4249), 'cv2.warpPerspective', 'cv2.warpPerspective', (['frame', 'homography', 'self.homography_image_dims'], {}), '(frame, homography, self.homography_image_dims)\n', (4202, 4249), False, 'import cv2\n'), ((4302, 4394), 'cv2.resize', 'cv2.resize', (['dst', '(0, 0)'], {'fx': 'self.metric_scale_factor[0]', 'fy': 'self.metric_scale_factor[1]'}), '(dst, (0, 0), fx=self.metric_scale_factor[0], fy=self.\n metric_scale_factor[1])\n', (4312, 4394), False, 'import cv2\n'), ((4406, 4508), 'numpy.asarray', 'np.asarray', (['[[self.metric_scale_factor[0], 0, 0], [0, self.metric_scale_factor[1], 0],\n [0, 0, 1]]'], {}), '([[self.metric_scale_factor[0], 0, 0], [0, self.\n metric_scale_factor[1], 0], [0, 0, 1]])\n', (4416, 4508), True, 'import numpy as np\n'), ((4564, 4659), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['(dst.shape[1] / 2, dst.shape[0] / 2)', 'self.metric_rotation_yaw', '(1)'], {}), '((dst.shape[1] / 2, dst.shape[0] / 2), self.\n metric_rotation_yaw, 1)\n', (4587, 4659), False, 'import cv2\n'), ((4669, 4728), 'cv2.warpAffine', 'cv2.warpAffine', (['dst', 'rotation', '(dst.shape[1], dst.shape[0])'], {}), '(dst, rotation, (dst.shape[1], dst.shape[0]))\n', (4683, 4728), False, 'import cv2\n'), ((4748, 4780), 'numpy.vstack', 'np.vstack', (['[rotation, [0, 0, 1]]'], {}), '([rotation, [0, 0, 1]])\n', (4757, 4780), True, 'import numpy as np\n'), ((4917, 5081), 'numpy.asarray', 'np.asarray', (['[[1, 0, -(self.checkerboard_center[0] - dst.shape[1] / 2)], [0, 1, -(self.\n checkerboard_center[1] - dst.shape[0] - board_center_px)], [0, 0, 1]]'], {}), '([[1, 0, -(self.checkerboard_center[0] - dst.shape[1] / 2)], [0, \n 1, -(self.checkerboard_center[1] - dst.shape[0] - board_center_px)], [0,\n 0, 1]])\n', (4927, 5081), True, 'import numpy as np\n'), ((5169, 5243), 'cv2.warpPerspective', 'cv2.warpPerspective', (['dst', 'offset_translation', '(dst.shape[1], dst.shape[0])'], {}), '(dst, offset_translation, (dst.shape[1], dst.shape[0]))\n', (5188, 5243), False, 'import cv2\n'), ((5535, 5606), 'cv2.warpPerspective', 'cv2.warpPerspective', (['frame', 'self.ipm_matrix', 'self.homography_image_dims'], {}), '(frame, self.ipm_matrix, self.homography_image_dims)\n', (5554, 5606), False, 'import cv2\n'), ((6489, 6514), 'cv2.imshow', 'cv2.imshow', (['win_name', 'img'], {}), '(win_name, img)\n', (6499, 6514), False, 'import cv2\n'), ((7870, 7907), 'numpy.mean', 'np.mean', (['((points - image_points) ** 2)'], {}), '((points - image_points) ** 2)\n', (7877, 7907), True, 'import numpy as np\n'), ((8182, 8219), 'numpy.mean', 'np.mean', (['((points - world_points) ** 2)'], {}), '((points - world_points) ** 2)\n', (8189, 8219), True, 'import numpy as np\n'), ((9371, 9388), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (9381, 9388), True, 'import matplotlib.pyplot as plt\n'), ((9847, 9870), 'numpy.vstack', 'np.vstack', (['world_points'], {}), '(world_points)\n', (9856, 9870), True, 'import numpy as np\n'), ((9872, 9895), 'numpy.vstack', 'np.vstack', (['image_points'], {}), '(image_points)\n', (9881, 9895), True, 'import numpy as np\n'), ((10514, 10539), 'cv2.namedWindow', 'cv2.namedWindow', (['win_name'], {}), '(win_name)\n', (10529, 10539), False, 'import cv2\n'), ((10548, 10582), 'cv2.moveWindow', 'cv2.moveWindow', (['win_name', '(100)', '(100)'], {}), '(win_name, 100, 100)\n', (10562, 10582), False, 'import cv2\n'), ((10600, 10622), 'cv2.imread', 'cv2.imread', (['image_file'], {}), '(image_file)\n', (10610, 10622), False, 'import cv2\n'), ((10676, 10704), 'cv2.imshow', 'cv2.imshow', (['win_name', 'output'], {}), '(win_name, output)\n', (10686, 10704), False, 'import cv2\n'), ((10713, 10727), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (10724, 10727), False, 'import cv2\n'), ((10736, 10759), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (10757, 10759), False, 'import cv2\n'), ((2810, 2822), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (2819, 2822), False, 'import yaml\n'), ((3151, 3181), 'numpy.expand_dims', 'np.expand_dims', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (3165, 3181), True, 'import numpy as np\n'), ((3201, 3216), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (3209, 3216), True, 'import numpy as np\n'), ((5476, 5517), 'cv2.findHomography', 'cv2.findHomography', (['in_points', 'out_points'], {}), '(in_points, out_points)\n', (5494, 5517), False, 'import cv2\n'), ((6214, 6257), 'cv2.circle', 'cv2.circle', (['img', '(x, y)', '(5)', '(255, 0, 0)', '(-1)'], {}), '(img, (x, y), 5, (255, 0, 0), -1)\n', (6224, 6257), False, 'import cv2\n'), ((6527, 6542), 'cv2.waitKey', 'cv2.waitKey', (['(20)'], {}), '(20)\n', (6538, 6542), False, 'import cv2\n'), ((7750, 7775), 'numpy.linalg.inv', 'np.linalg.inv', (['ipm_matrix'], {}), '(ipm_matrix)\n', (7763, 7775), True, 'import numpy as np\n'), ((648, 688), 'numpy.asarray', 'np.asarray', (["self.info['intrinsics']['K']"], {}), "(self.info['intrinsics']['K'])\n", (658, 688), True, 'import numpy as np\n'), ((3256, 3281), 'numpy.hstack', 'np.hstack', (['[points, ones]'], {}), '([points, ones])\n', (3265, 3281), True, 'import numpy as np\n'), ((8389, 8409), 'numpy.array', 'np.array', (['([0.5] * 41)'], {}), '([0.5] * 41)\n', (8397, 8409), True, 'import numpy as np\n'), ((8416, 8436), 'numpy.array', 'np.array', (['([0.3] * 47)'], {}), '([0.3] * 47)\n', (8424, 8436), True, 'import numpy as np\n'), ((8443, 8463), 'numpy.array', 'np.array', (['([0.2] * 21)'], {}), '([0.2] * 21)\n', (8451, 8463), True, 'import numpy as np\n'), ((2322, 2372), 'numpy.asarray', 'np.asarray', (["self.info['calibration']['ipm_matrix']"], {}), "(self.info['calibration']['ipm_matrix'])\n", (2332, 2372), True, 'import numpy as np\n'), ((3100, 3116), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (3108, 3116), True, 'import numpy as np\n')]
import numpy as np from time import sleep import serial ########## Prepare Arduino code for data output ################## # # remove the /* and */ around the print commands in functions.ino # # /* # Serial.print(dt); Serial.print("\t"); # Serial.print(pitch); Serial.print("\t"); # Serial.print(gyroYrate); Serial.print("\t"); # Serial.print(CFilteredlAngleY); Serial.print("\t"); # Serial.print(gyroYangle); Serial.print("\t"); # Serial.print("\n"); # */ # # Remember to put them back! # ################################################################## try: ser = serial.Serial('/dev/ttyUSB0', 38400) except: ser = serial.Serial('/dev/ttyUSB1', 38400) ii=1 sleep(2) t=0 def serial2v(): v1=ser.readline() a=np.array(list(map(float,v1.split('\t')[:-1]))) return a v1=np.array([[]]*5).T # expecting 5 columns for ii in range(1000): try: v1 = np.vstack([v1,serial2v()]) except: v1 = np.vstack([v1,serial2v()]) print(serial2v()) np.savetxt('T-Bot_FilteredData.dat',v1)
[ "serial.Serial", "numpy.savetxt", "numpy.array", "time.sleep" ]
[((683, 691), 'time.sleep', 'sleep', (['(2)'], {}), '(2)\n', (688, 691), False, 'from time import sleep\n'), ((994, 1034), 'numpy.savetxt', 'np.savetxt', (['"""T-Bot_FilteredData.dat"""', 'v1'], {}), "('T-Bot_FilteredData.dat', v1)\n", (1004, 1034), True, 'import numpy as np\n'), ((586, 622), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyUSB0"""', '(38400)'], {}), "('/dev/ttyUSB0', 38400)\n", (599, 622), False, 'import serial\n'), ((803, 821), 'numpy.array', 'np.array', (['([[]] * 5)'], {}), '([[]] * 5)\n', (811, 821), True, 'import numpy as np\n'), ((641, 677), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyUSB1"""', '(38400)'], {}), "('/dev/ttyUSB1', 38400)\n", (654, 677), False, 'import serial\n')]
from torch.utils.data import Dataset import tqdm import json import torch import random import numpy as np from sklearn.utils import shuffle class BERTDataset(Dataset): def __init__(self, corpus_path, word2idx_path, seq_len, hidden_dim=384, on_memory=True): # hidden dimension for positional encoding self.hidden_dim = hidden_dim # define path of dicts self.word2idx_path = word2idx_path # define max length self.seq_len = seq_len # load whole corpus at once or not self.on_memory = on_memory # directory of corpus dataset self.corpus_path = corpus_path # define special symbols self.pad_index = 0 self.unk_index = 1 self.cls_index = 2 self.sep_index = 3 self.mask_index = 4 self.num_index = 5 # 加载字典 with open(word2idx_path, "r", encoding="utf-8") as f: self.word2idx = json.load(f) # 加载语料 with open(corpus_path, "r", encoding="utf-8") as f: if not on_memory: # 如果不将数据集直接加载到内存, 则需先确定语料行数 self.corpus_lines = 0 for _ in tqdm.tqdm(f, desc="Loading Dataset"): self.corpus_lines += 1 if on_memory: # 将数据集全部加载到内存 self.lines = [eval(line) for line in tqdm.tqdm(f, desc="Loading Dataset")] self.corpus_lines = len(self.lines) if not on_memory: # 如果不全部加载到内存, 首先打开语料 self.file = open(corpus_path, "r", encoding="utf-8") # 然后再打开同样的语料, 用来抽取负样本 self.random_file = open(corpus_path, "r", encoding="utf-8") # 下面是为了错位抽取负样本 for _ in range(np.random.randint(self.corpus_lines if self.corpus_lines < 1000 else 1000)): self.random_file.__next__() def __len__(self): return self.corpus_lines def __getitem__(self, item): t1, t2, is_next_label = self.random_sent(item) t1_random, t1_label = self.random_char(t1) t2_random, t2_label = self.random_char(t2) t1 = [self.cls_index] + t1_random + [self.sep_index] t2 = t2_random + [self.sep_index] t1_label = [self.pad_index] + t1_label + [self.pad_index] t2_label = t2_label + [self.pad_index] segment_label = ([0 for _ in range(len(t1))] + [1 for _ in range(len(t2))])[:self.seq_len] bert_input = (t1 + t2)[:self.seq_len] bert_label = (t1_label + t2_label)[:self.seq_len] output = {"bert_input": torch.tensor(bert_input), "bert_label": torch.tensor(bert_label), "segment_label": torch.tensor(segment_label), "is_next": torch.tensor([is_next_label])} return output def tokenize_char(self, segments): return [self.word2idx.get(char, self.unk_index) for char in segments] def random_char(self, sentence): char_tokens_ = list(sentence) char_tokens = self.tokenize_char(char_tokens_) output_label = [] for i, token in enumerate(char_tokens): prob = random.random() if prob < 0.30: prob /= 0.30 output_label.append(char_tokens[i]) # 80% randomly change token to mask token if prob < 0.8: char_tokens[i] = self.mask_index # 10% randomly change token to random token elif prob < 0.9: char_tokens[i] = random.randrange(len(self.word2idx)) else: output_label.append(0) return char_tokens, output_label def random_sent(self, index): t1, t2 = self.get_corpus_line(index) # output_text, label(isNotNext:0, isNext:1) if random.random() > 0.5: return t1, t2, 1 else: return t1, self.get_random_line(), 0 def get_corpus_line(self, item): if self.on_memory: return self.lines[item]["text1"], self.lines[item]["text2"] else: line = self.file.__next__() if line is None: self.file.close() self.file = open(self.corpus_path, "r", encoding="utf-8") line = self.file.__next__() line = eval(line) t1, t2 = line["text1"], line["text2"] return t1, t2 def get_random_line(self): if self.on_memory: return self.lines[random.randrange(len(self.lines))]["text2"] line = self.random_file.__next__() if line is None: self.random_file.close() self.random_file = open(self.corpus_path, "r", encoding="utf-8") for _ in range(np.random.randint(self.corpus_lines if self.corpus_lines < 1000 else 1000)): self.random_file.__next__() line = self.random_file.__next__() return eval(line)["text2"]
[ "tqdm.tqdm", "json.load", "random.random", "numpy.random.randint", "torch.tensor" ]
[((942, 954), 'json.load', 'json.load', (['f'], {}), '(f)\n', (951, 954), False, 'import json\n'), ((2559, 2583), 'torch.tensor', 'torch.tensor', (['bert_input'], {}), '(bert_input)\n', (2571, 2583), False, 'import torch\n'), ((2617, 2641), 'torch.tensor', 'torch.tensor', (['bert_label'], {}), '(bert_label)\n', (2629, 2641), False, 'import torch\n'), ((2678, 2705), 'torch.tensor', 'torch.tensor', (['segment_label'], {}), '(segment_label)\n', (2690, 2705), False, 'import torch\n'), ((2736, 2765), 'torch.tensor', 'torch.tensor', (['[is_next_label]'], {}), '([is_next_label])\n', (2748, 2765), False, 'import torch\n'), ((3133, 3148), 'random.random', 'random.random', ([], {}), '()\n', (3146, 3148), False, 'import random\n'), ((3810, 3825), 'random.random', 'random.random', ([], {}), '()\n', (3823, 3825), False, 'import random\n'), ((1168, 1204), 'tqdm.tqdm', 'tqdm.tqdm', (['f'], {'desc': '"""Loading Dataset"""'}), "(f, desc='Loading Dataset')\n", (1177, 1204), False, 'import tqdm\n'), ((1734, 1808), 'numpy.random.randint', 'np.random.randint', (['(self.corpus_lines if self.corpus_lines < 1000 else 1000)'], {}), '(self.corpus_lines if self.corpus_lines < 1000 else 1000)\n', (1751, 1808), True, 'import numpy as np\n'), ((4746, 4820), 'numpy.random.randint', 'np.random.randint', (['(self.corpus_lines if self.corpus_lines < 1000 else 1000)'], {}), '(self.corpus_lines if self.corpus_lines < 1000 else 1000)\n', (4763, 4820), True, 'import numpy as np\n'), ((1359, 1395), 'tqdm.tqdm', 'tqdm.tqdm', (['f'], {'desc': '"""Loading Dataset"""'}), "(f, desc='Loading Dataset')\n", (1368, 1395), False, 'import tqdm\n')]
# !/usr/bin/env python # _*_ coding:utf-8 _*_ import jieba from HyperParameter import HyperParameter import numpy as np import random zero_pad = np.zeros(768,float) padToken, unknownToken, goToken, eosToken = 0, 1, 2, 3 class Batch: def __init__(self): self.encoder_inputs = [] self.encoder_inputs_length = [] self.decoder_targets = [] self.decoder_targets_length = [] def load_and_cut_data(filepath): with open(filepath, 'r', encoding='UTF-8') as f: data = [] lines = f.readlines() for line in lines: seg_list = jieba.cut(line.strip(), cut_all=False) cutted_line = [e for e in seg_list] data.append(cutted_line) return data def create_dic_and_map(sources, targets): special_words = ['<PAD>', '<UNK>', '<GO>', '<EOS>'] hp = HyperParameter() with open(hp.dictionary_sources, 'r', encoding='utf-8') as f: word_dic_new = f.read().split('\n') with open(hp.dictionary_targets, 'r', encoding='utf-8') as f: word_dic_new_t = f.read().split('\n') id_to_word = {idx: word for idx, word in enumerate(special_words + word_dic_new)} word_to_id = {word: idx for idx, word in id_to_word.items()} id_to_word_t = {idx: word for idx, word in enumerate(special_words + word_dic_new_t)} word_to_id_t = {word: idx for idx, word in id_to_word_t.items()} sources_data = [[word_to_id.get(character, word_to_id['<UNK>']) for character in line] for line in sources] targets_data = [[word_to_id_t.get(character, word_to_id_t['<UNK>']) for character in line] for line in targets] return sources_data, targets_data, word_to_id, id_to_word,word_to_id_t,id_to_word_t def create_batch(sources, targets): batch = Batch() batch.encoder_inputs_length = [len(source) for source in sources] batch.decoder_targets_length = [len(target) + 1 for target in targets] max_source_length = max(batch.encoder_inputs_length) max_target_length = max(batch.decoder_targets_length) for source in sources: pad = [padToken] * (max_source_length - len(source)) batch.encoder_inputs.append(source + pad) for target in targets: pad = [padToken] * (max_target_length - (len(target) + 1)) eos = [eosToken] * 1 batch.decoder_targets.append(target + eos + pad) return batch def get_batches(sources_data, targets_data, batch_size): data_len = len(sources_data) def gen_next_samples(): for i in range(0, data_len, batch_size): yield sources_data[i:min(i + batch_size, data_len)], targets_data[i:min(i + batch_size,data_len)] batches = [] for sources, targets, in gen_next_samples(): batch = create_batch(sources, targets) batches.append(batch) return batches def sentence2enco(sentence, word2id): if sentence == '': return None seg_list = jieba.cut(sentence.strip(), cut_all=False) cutted_line = [e for e in seg_list] wordIds = [] for word in cutted_line: wordIds.append(word2id.get(word, unknownToken)) print(wordIds) batch = create_batch([wordIds], [[]]) return batch if __name__ == '__main__': sources_txt = 'data/sources.txt' targets_txt = 'data/targets.txt' keep_rate = 0.6 batch_size = 128 sources = load_and_cut_data(sources_txt) targets = load_and_cut_data(targets_txt) sources_data, targets_data, word_to_id, id_to_word,word_to_id_t,id_to_word_t = create_dic_and_map(sources, targets) batches = get_batches(sources_data, targets_data, batch_size)
[ "HyperParameter.HyperParameter", "numpy.zeros" ]
[((147, 167), 'numpy.zeros', 'np.zeros', (['(768)', 'float'], {}), '(768, float)\n', (155, 167), True, 'import numpy as np\n'), ((847, 863), 'HyperParameter.HyperParameter', 'HyperParameter', ([], {}), '()\n', (861, 863), False, 'from HyperParameter import HyperParameter\n')]
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Argo, test #12. (10C, 5PSU) """ import logging import numpy as np from numpy import ma from .qctests import QCCheckVar from .rate_of_change import rate_of_change module_logger = logging.getLogger(__name__) class DigitRollOver(QCCheckVar): def set_features(self): self.features = {"rate_of_change": rate_of_change(self.data[self.varname])} def test(self): self.flags = {} try: threshold = self.cfg["threshold"] except KeyError: module_logger.debug( "Deprecated cfg format. It should contain a threshold item." ) threshold = self.cfg assert ( (np.size(threshold) == 1) and (threshold is not None) and (np.isfinite(threshold)) ) feature = ma.absolute(self.features["rate_of_change"]) flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1") flag[feature > threshold] = self.flag_bad flag[feature <= threshold] = self.flag_good x = np.atleast_1d(self.data[self.varname]) flag[ma.getmaskarray(x) | ~np.isfinite(x)] = 9 self.flags["digit_roll_over"] = flag
[ "numpy.ma.absolute", "numpy.size", "numpy.ma.getmaskarray", "numpy.isfinite", "numpy.shape", "numpy.atleast_1d", "logging.getLogger" ]
[((281, 308), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (298, 308), False, 'import logging\n'), ((908, 952), 'numpy.ma.absolute', 'ma.absolute', (["self.features['rate_of_change']"], {}), "(self.features['rate_of_change'])\n", (919, 952), False, 'from numpy import ma\n'), ((1139, 1177), 'numpy.atleast_1d', 'np.atleast_1d', (['self.data[self.varname]'], {}), '(self.data[self.varname])\n', (1152, 1177), True, 'import numpy as np\n'), ((855, 877), 'numpy.isfinite', 'np.isfinite', (['threshold'], {}), '(threshold)\n', (866, 877), True, 'import numpy as np\n'), ((978, 1011), 'numpy.shape', 'np.shape', (['self.data[self.varname]'], {}), '(self.data[self.varname])\n', (986, 1011), True, 'import numpy as np\n'), ((773, 791), 'numpy.size', 'np.size', (['threshold'], {}), '(threshold)\n', (780, 791), True, 'import numpy as np\n'), ((1191, 1209), 'numpy.ma.getmaskarray', 'ma.getmaskarray', (['x'], {}), '(x)\n', (1206, 1209), False, 'from numpy import ma\n'), ((1213, 1227), 'numpy.isfinite', 'np.isfinite', (['x'], {}), '(x)\n', (1224, 1227), True, 'import numpy as np\n')]
#!/usr/bin/enum_weights python # -*- coding: utf-8 -*- # Copyright (C) 2019 <NAME>, <NAME>, <NAME> # # All Rights Reserved. # # Authors: <NAME>, <NAME>, <NAME> # # Please cite: # # <NAME>, <NAME>, and <NAME>, "Quasi-Newton Methods for # Deep Learning: Forget the Past, Just Sample." (2019). Lehigh University. # http://arxiv.org/abs/1901.09997 # ========================================================================== import numpy as np import pickle import os.path import os import sys import tensorflow as tf import time from util_func import * from network import * from data_generation import * #from sampleSY import * # ========================================================================== def LSR1(w_init, X, y, seed, numIter, mmr, radius, eps, eta, delta_init, epsTR, num_weights, dnn, sess): """Sampled LSR1 method.""" w = w_init sess.run(dnn.params.assign(w)) # Assign initial weights to parameters of the network np.random.seed(seed) # Set random seed numFunEval = 0 # Initialize counters (function values, gradients and Hessians) numGradEval = 0 numHessEval = 0 deltak = delta_init # Initialize trust region radius HISTORY = [] # Initialize array for storage weightLSR1 = [] # Initialize array for storing weights k = 0 # Initialize iteration counter st = time.time() # Start the timer objFunOld = sess.run(dnn.cross_entropy, feed_dict={dnn.x: X, dnn.y: y}) # Compute function value at current iterate numFunEval += 1 print(objFunOld) import collections S_buffer = collections.deque(maxlen=mmr) Y_buffer = collections.deque(maxlen=mmr) # Method while loop (terminate after numIter or Accuracy 1 achieved) while k<100: gradTemp, acc, xOld = sess.run([dnn.G, dnn.accuracy, dnn.params], feed_dict={dnn.x: X, dnn.y: y}) # Compute gradient and accuracy gard_k = gradTemp[0] numGradEval += 1 norm_g = LA.norm(gard_k) # Sample S, Y pairs #S, Y, counterSucc, numHessEval = sample_pairs_SY_LSR1(X, y, num_weights, mmr, radius, eps, dnn, numHessEval, sess) counterSucc = 0 # Append to History array HISTORY.append( [k, objFunOld, acc, norm_g, numFunEval, numGradEval, numHessEval, numFunEval + numGradEval + numHessEval, counterSucc, time.time() - st, deltak]) print(HISTORY[k]) # Print History array if k > numIter or acc == 1: # Terminate if number of iterations > numIter or Accuracy = 1 break weightLSR1.append(sess.run(dnn.params)) # Append weights if k>0: sk_TR = CG_Steinhaug_matFree(epsTR, gard_k, deltak, S, Y, num_weights) # Compute step using CG Steinhaug else: sk_TR = -gard_k sess.run(dnn.ASSIGN_OP, feed_dict={dnn.updateVal: xOld + sk_TR}) # Assign new S_buffer.append(sk_TR) S = np.squeeze(S_buffer).T objFunNew = sess.run(dnn.cross_entropy, feed_dict={dnn.x: X, dnn.y: y}) # Compute new function value numFunEval += 1 gradTemp, acc, xOld = sess.run([dnn.G, dnn.accuracy, dnn.params], feed_dict={dnn.x: X, dnn.y: y}) # Compute gradient and accuracy grad_kp1 = gradTemp[0] numGradEval += 1 Y_buffer.append(grad_kp1-gard_k) Y = np.squeeze(Y_buffer).T try: dimY = Y.shape[1] except: Y = Y.reshape(-1,1) S = S.reshape(-1,1) ared = objFunOld - objFunNew # Compute actual reduction Lp = np.zeros((Y.shape[1], Y.shape[1])) for ii in range(Y.shape[1]): for jj in range(0, ii): Lp[ii, jj] = S[:, ii].dot(Y[:, jj]) tmpp = np.sum((S * Y), axis=0) Dp = np.diag(tmpp) Mp = (Dp + Lp + Lp.T) Minvp = np.linalg.inv(Mp) tmpp1 = np.matmul(Y.T, sk_TR) tmpp2 = np.matmul(Minvp, tmpp1) Bk_skTR = np.matmul(Y, tmpp2) pred = -(gard_k.T.dot(sk_TR) + 0.5 * sk_TR.T.dot(Bk_skTR)) # Compute predicted reduction # Take step if ared / pred > eta: xNew = xOld + sk_TR objFunOld = objFunNew else: xNew = xOld # Update trust region radius if ared / pred > 0.75: deltak = 2 * deltak elif ared / pred >= 0.1 and ared / pred <= 0.75: pass # no need to change deltak elif ared / pred < 0.1: deltak = deltak * 0.5 k += 1 # Increment iteration counter sess.run(dnn.ASSIGN_OP, feed_dict={dnn.updateVal: xNew}) # Assign updated weights pickle.dump(HISTORY, open("./_saved_log_files/LSR1.pkl", "wb")) # Save History in .pkl file # pickle.dump( weightLSR1, open( "./_saved_log_files/LSR1_weights.pkl", "wb" ) ) # Save Weights in .pkl file
[ "numpy.random.seed", "numpy.sum", "numpy.zeros", "time.time", "numpy.linalg.inv", "numpy.matmul", "numpy.squeeze", "numpy.diag", "collections.deque" ]
[((963, 983), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (977, 983), True, 'import numpy as np\n'), ((1363, 1374), 'time.time', 'time.time', ([], {}), '()\n', (1372, 1374), False, 'import time\n'), ((1597, 1626), 'collections.deque', 'collections.deque', ([], {'maxlen': 'mmr'}), '(maxlen=mmr)\n', (1614, 1626), False, 'import collections\n'), ((1642, 1671), 'collections.deque', 'collections.deque', ([], {'maxlen': 'mmr'}), '(maxlen=mmr)\n', (1659, 1671), False, 'import collections\n'), ((3666, 3700), 'numpy.zeros', 'np.zeros', (['(Y.shape[1], Y.shape[1])'], {}), '((Y.shape[1], Y.shape[1]))\n', (3674, 3700), True, 'import numpy as np\n'), ((3843, 3864), 'numpy.sum', 'np.sum', (['(S * Y)'], {'axis': '(0)'}), '(S * Y, axis=0)\n', (3849, 3864), True, 'import numpy as np\n'), ((3880, 3893), 'numpy.diag', 'np.diag', (['tmpp'], {}), '(tmpp)\n', (3887, 3893), True, 'import numpy as np\n'), ((3940, 3957), 'numpy.linalg.inv', 'np.linalg.inv', (['Mp'], {}), '(Mp)\n', (3953, 3957), True, 'import numpy as np\n'), ((3974, 3995), 'numpy.matmul', 'np.matmul', (['Y.T', 'sk_TR'], {}), '(Y.T, sk_TR)\n', (3983, 3995), True, 'import numpy as np\n'), ((4012, 4035), 'numpy.matmul', 'np.matmul', (['Minvp', 'tmpp1'], {}), '(Minvp, tmpp1)\n', (4021, 4035), True, 'import numpy as np\n'), ((4054, 4073), 'numpy.matmul', 'np.matmul', (['Y', 'tmpp2'], {}), '(Y, tmpp2)\n', (4063, 4073), True, 'import numpy as np\n'), ((2978, 2998), 'numpy.squeeze', 'np.squeeze', (['S_buffer'], {}), '(S_buffer)\n', (2988, 2998), True, 'import numpy as np\n'), ((3426, 3446), 'numpy.squeeze', 'np.squeeze', (['Y_buffer'], {}), '(Y_buffer)\n', (3436, 3446), True, 'import numpy as np\n'), ((2408, 2419), 'time.time', 'time.time', ([], {}), '()\n', (2417, 2419), False, 'import time\n')]
# coding=utf-8 ''' Calculates PSF, jitter and telescope background and transmission ''' import sys import logging import multiprocessing as mp import signal import time import numpy as np import scipy.constants as sp from scipy.signal import fftconvolve from src.config import * from src.modules.create_psf import create_psf, define_psf from src.modules.em_model import * def process_lambda(params, lamb, image, px, py, pback): padding_plane = np.zeros((px, py)) #return i, padding_plane psf = create_psf(lamb) # np.sum(psf) is < 1, so to recover the same back emission after the convolution we need to # subctract before and then add the back emission. We assume that the back emission is uniform # within the field padding_plane[psf.shape[0]:psf.shape[0]+image.shape[0], psf.shape[1]:psf.shape[1]+image.shape[1]] = image - pback conv_image = fftconvolve(padding_plane, psf) + pback return params, conv_image counter = None result_cube = None bar_str = None llambs = None def save_result(results): global counter, result_cube, bar_str, llambs counter = counter + 1 sys.stdout.write(bar_str.format(int(100.*counter/llambs), counter, llambs) + "\r") sys.stdout.flush() (i, x0, x1, y0, y1), conv_image = results result_cube[i, :, :] = conv_image[y0:y1, x0:x1] def sim_telescope(input_parameteres, cube, back_emission, transmission, ext_lambs, cube_lamb_mask, debug_plots=False, output_file=""): ''' Simulates telescope effects Inputs: input_parameters: input dictionary exposure_time: Exposure time [s] jitter: Residual telescope jitter [mas] air_mass: Air mass of the observation zenith_seeing: Atmospheric seeing FWHM [arcsec] spaxel_scale: spatial pixel (spaxel) scale [mas] telescope_temp: Telescope temperature [K] ao_mode: LTAO/SCAO/NOAO/AIRY/User defined PSF fits file ao_star_hmag: AO star H mag ao_star_distance: AO star distance [arcsec] user_defined_psf: user defined fits PSF n_cpus: no. of CPUs to use cube: Input datacube (RA, DEC, lambda) back_emission: Input background emission transmission: Input transmission ext_lambs: extended lambda array [um] cube_lamb_mask: mask array to get the lambs of the cube debug_plots: Produce debug plots output_file: File name for debug plots Outputs: cube: Cube including telescope background and emission and convolved with PSF back_emission: back_emission including telescope PSF: PSF of the first lambda ''' # Get telescope reflectivity logging.info("Calculating telescope reflectivity") telescope_reflectivity = load_transmission_curve(ext_lambs, "ELT_mirror_reflectivity.txt", debug_plots, [output_file, "tel"], "telescope transmission") #telescope_reflectivity = load_transmission_curve(ext_lambs, "ELT_mirror_reflectivity_age0.txt", debug_plots, [output_file, "tel"], "telescope transmission") back_emission *= telescope_reflectivity transmission *= telescope_reflectivity # Get telescope background logging.info("Calculating telescope background") telescope_background = get_background_emission(ext_lambs, input_parameteres["telescope_temp"], 1. - telescope_reflectivity, input_parameteres["exposure_time"], debug_plots, [output_file, "tel"], "telescope emission [photons/m$^2$/$\mu$m/arcsec$^2$]") back_emission += telescope_background # Add telescope emission/transmission to the input cube tel_reflectivity_cube = telescope_reflectivity[cube_lamb_mask] tel_reflectivity_cube.shape = (np.sum(cube_lamb_mask), 1, 1) cube *= tel_reflectivity_cube tel_background_cube = telescope_background[cube_lamb_mask] tel_background_cube.shape = (np.sum(cube_lamb_mask), 1, 1) cube += tel_background_cube # PSF + Jitter + Instrument PSF logging.info("Define PSF") jitter = input_parameteres["jitter"] spax = input_parameteres["spaxel_scale"] FWHM_instrument = (config_data["dynamic_instrument_psf"]**2 + config_data["static_instrument_psf"][spax]**2)**0.5 sigma_instrument = FWHM_instrument/2.35482 sigma_combined = (jitter**2 + sigma_instrument**2)**0.5 logging.info("Residual telescope jitter = {0:.2f}x{1:.2f} mas".format(*jitter)) logging.info("Instrument PSF σ = {:.2f} mas".format(sigma_instrument)) logging.info("-> Combined σ = {0:.2f}x{1:.2f} mas".format(*sigma_combined)) psf_size = config_data["spaxel_scale"][spax].psfsize define_psf(input_parameteres, sigma_combined, psf_size, config_data["spaxel_scale"][spax].psfscale) lambs = ext_lambs[cube_lamb_mask] # padding with back_emission padding_x = cube.shape[2] + 2*psf_size padding_y = cube.shape[1] + 2*psf_size padding_back = back_emission[cube_lamb_mask] padding_back.shape = (len(lambs), 1, 1) conv_side_x = padding_x + psf_size - 1 conv_side_y = padding_y + psf_size - 1 # extract convolved image x0 = int((conv_side_x - cube.shape[2])/2.)+1 x1 = x0 + cube.shape[2] y0 = int((conv_side_y - cube.shape[1])/2.)+1 y1 = y0 + cube.shape[1] logging.info("Convolve with PSF") global counter, result_cube, bar_str, llambs bar_str = "[ {:2d}% {:" + str(len(str(len(lambs)))) + "d}/{:" + str(len(str(len(lambs)))) + "d} ]" ncpus = input_parameteres["n_cpus"] logging.info(("Using {:d} CPU" + ("s" if ncpus > 1 else "")).format(ncpus)) if ncpus > 1: def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) pool = mp.Pool(ncpus, init_worker) counter = 0 result_cube = np.zeros_like(cube) llambs = len(lambs) for j in range(0, len(lambs), ncpus): result = [] for i in range(j, min([len(lambs), j+ncpus])): result.append(pool.apply_async(process_lambda, args=((i, x0, x1, y0, y1), lambs[i], cube[i, :, :], padding_x, padding_y, padding_back[i]), callback=save_result)) try: while True: time.sleep(0.5) if all([r.ready() for r in result]): break except KeyboardInterrupt: pool.terminate() pool.join() pool.close() pool.join() cube = result_cube else: for i in range(len(lambs)): sys.stdout.write(bar_str.format(int(100.*i/len(lambs)), i, len(lambs)) + "\r") sys.stdout.flush() #break _, conv_image = process_lambda(i, lambs[i], cube[i, :, :], padding_x, padding_y, padding_back[i]) cube[i, :, :] = conv_image[y0:y1, x0:x1] central_lambda = (lambs[0] + lambs[-1])*0.5 return (cube, back_emission, transmission), create_psf(central_lambda), central_lambda
[ "numpy.zeros_like", "numpy.sum", "numpy.zeros", "time.sleep", "src.modules.create_psf.create_psf", "logging.info", "sys.stdout.flush", "multiprocessing.Pool", "scipy.signal.fftconvolve", "signal.signal", "src.modules.create_psf.define_psf" ]
[((451, 469), 'numpy.zeros', 'np.zeros', (['(px, py)'], {}), '((px, py))\n', (459, 469), True, 'import numpy as np\n'), ((503, 519), 'src.modules.create_psf.create_psf', 'create_psf', (['lamb'], {}), '(lamb)\n', (513, 519), False, 'from src.modules.create_psf import create_psf, define_psf\n'), ((1174, 1192), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1190, 1192), False, 'import sys\n'), ((2495, 2545), 'logging.info', 'logging.info', (['"""Calculating telescope reflectivity"""'], {}), "('Calculating telescope reflectivity')\n", (2507, 2545), False, 'import logging\n'), ((2970, 3018), 'logging.info', 'logging.info', (['"""Calculating telescope background"""'], {}), "('Calculating telescope background')\n", (2982, 3018), False, 'import logging\n'), ((3714, 3740), 'logging.info', 'logging.info', (['"""Define PSF"""'], {}), "('Define PSF')\n", (3726, 3740), False, 'import logging\n'), ((4330, 4434), 'src.modules.create_psf.define_psf', 'define_psf', (['input_parameteres', 'sigma_combined', 'psf_size', "config_data['spaxel_scale'][spax].psfscale"], {}), "(input_parameteres, sigma_combined, psf_size, config_data[\n 'spaxel_scale'][spax].psfscale)\n", (4340, 4434), False, 'from src.modules.create_psf import create_psf, define_psf\n'), ((4921, 4954), 'logging.info', 'logging.info', (['"""Convolve with PSF"""'], {}), "('Convolve with PSF')\n", (4933, 4954), False, 'import logging\n'), ((859, 890), 'scipy.signal.fftconvolve', 'fftconvolve', (['padding_plane', 'psf'], {}), '(padding_plane, psf)\n', (870, 890), False, 'from scipy.signal import fftconvolve\n'), ((3465, 3487), 'numpy.sum', 'np.sum', (['cube_lamb_mask'], {}), '(cube_lamb_mask)\n', (3471, 3487), True, 'import numpy as np\n'), ((3617, 3639), 'numpy.sum', 'np.sum', (['cube_lamb_mask'], {}), '(cube_lamb_mask)\n', (3623, 3639), True, 'import numpy as np\n'), ((5318, 5345), 'multiprocessing.Pool', 'mp.Pool', (['ncpus', 'init_worker'], {}), '(ncpus, init_worker)\n', (5325, 5345), True, 'import multiprocessing as mp\n'), ((5379, 5398), 'numpy.zeros_like', 'np.zeros_like', (['cube'], {}), '(cube)\n', (5392, 5398), True, 'import numpy as np\n'), ((6319, 6345), 'src.modules.create_psf.create_psf', 'create_psf', (['central_lambda'], {}), '(central_lambda)\n', (6329, 6345), False, 'from src.modules.create_psf import create_psf, define_psf\n'), ((5263, 5307), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal.SIG_IGN'], {}), '(signal.SIGINT, signal.SIG_IGN)\n', (5276, 5307), False, 'import signal\n'), ((6050, 6068), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (6066, 6068), False, 'import sys\n'), ((5732, 5747), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (5742, 5747), False, 'import time\n')]
# -*- coding: utf-8 -*- # /usr/bin/python2 ''' By <NAME>. <EMAIL>. https://www.github.com/kyubyong/neurobind. ''' from __future__ import print_function import os import sys from scipy.stats import spearmanr from data_load import get_batch_data, load_vocab, load_data from hyperparams import Hyperparams as hp import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from train import Graph def eval(): # Load graph g = Graph(is_training=False); print("Graph loaded") # Load data X, Y = load_data(mode="test") nucl2idx, idx2nucl = load_vocab() with g.graph.as_default(): sv = tf.train.Supervisor() with sv.managed_session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Restore parameters sv.saver.restore(sess, tf.train.latest_checkpoint(hp.logdir)); print("Restored!") # Get model name mname = open(hp.logdir + '/checkpoint', 'r').read().split('"')[1] # model name # Inference if not os.path.exists(hp.results): os.mkdir(hp.results) with open(os.path.join(hp.results, mname), 'w') as fout: fout.write("{}\t{}\t{}\n".format("probe", "expected intensity", "predicted intensity")) expected, predicted = [], [] for step in range(len(X) // hp.batch_size): x = X[step * hp.batch_size: (step + 1) * hp.batch_size] y = Y[step * hp.batch_size: (step + 1) * hp.batch_size] # predict intensities logits = sess.run(g.logits, {g.x: x}) expected.extend(list(y)) predicted.extend(list(logits)) for xx, yy, ll in zip(x, y, logits): # sequence-wise fout.write("{}\t{}\t{}\n".format("".join(idx2nucl[idx] for idx in xx), yy, ll)) # Get spearman coefficients score, _ = spearmanr(expected, predicted) fout.write("{}{}\n".format("Spearman Coefficient: ", score)) # Plot the ranks of the top 100 positive probes expected_predicted = sorted(zip(expected, predicted), key=lambda x: float(x[0]), reverse=True) expected_predicted = [list(each) + [int(i < 100)] for i, each in enumerate(expected_predicted)] expected_predicted = sorted(expected_predicted, key=lambda x: float(x[1]), reverse=True) predicted_ranks = np.array([each[-1] for each in expected_predicted]) # Plot axprops = dict(xticks=[], yticks=[]) barprops = dict(aspect='auto', cmap=plt.cm.binary, interpolation='nearest') fig = plt.figure() predicted_ranks.shape = len(predicted_ranks), 1 ax = fig.add_axes([0, 0, .5, 1], **axprops) ax.imshow(predicted_ranks, **barprops) fig.savefig('fig/rank.png') if __name__ == '__main__': eval() print("Done")
[ "os.mkdir", "train.Graph", "scipy.stats.spearmanr", "os.path.exists", "data_load.load_data", "data_load.load_vocab", "tensorflow.train.Supervisor", "matplotlib.pyplot.figure", "tensorflow.train.latest_checkpoint", "numpy.array", "tensorflow.ConfigProto", "os.path.join" ]
[((451, 475), 'train.Graph', 'Graph', ([], {'is_training': '(False)'}), '(is_training=False)\n', (456, 475), False, 'from train import Graph\n'), ((527, 549), 'data_load.load_data', 'load_data', ([], {'mode': '"""test"""'}), "(mode='test')\n", (536, 549), False, 'from data_load import get_batch_data, load_vocab, load_data\n'), ((575, 587), 'data_load.load_vocab', 'load_vocab', ([], {}), '()\n', (585, 587), False, 'from data_load import get_batch_data, load_vocab, load_data\n'), ((633, 654), 'tensorflow.train.Supervisor', 'tf.train.Supervisor', ([], {}), '()\n', (652, 654), True, 'import tensorflow as tf\n'), ((814, 851), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['hp.logdir'], {}), '(hp.logdir)\n', (840, 851), True, 'import tensorflow as tf\n'), ((1039, 1065), 'os.path.exists', 'os.path.exists', (['hp.results'], {}), '(hp.results)\n', (1053, 1065), False, 'import os\n'), ((1067, 1087), 'os.mkdir', 'os.mkdir', (['hp.results'], {}), '(hp.results)\n', (1075, 1087), False, 'import os\n'), ((1967, 1997), 'scipy.stats.spearmanr', 'spearmanr', (['expected', 'predicted'], {}), '(expected, predicted)\n', (1976, 1997), False, 'from scipy.stats import spearmanr\n'), ((2502, 2553), 'numpy.array', 'np.array', (['[each[-1] for each in expected_predicted]'], {}), '([each[-1] for each in expected_predicted])\n', (2510, 2553), True, 'import numpy as np\n'), ((2762, 2774), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2772, 2774), True, 'import matplotlib.pyplot as plt\n'), ((694, 735), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (708, 735), True, 'import tensorflow as tf\n'), ((1110, 1141), 'os.path.join', 'os.path.join', (['hp.results', 'mname'], {}), '(hp.results, mname)\n', (1122, 1141), False, 'import os\n')]
from bricks_modeling.file_IO.model_writer import write_bricks_to_file_with_steps from util.debugger import MyDebugger import os import csv import solvers.brick_heads.bach_render_images as render import solvers.brick_heads.part_selection as p_select from bricks_modeling.file_IO.model_reader import read_bricks_from_file import numpy as np def one_line_arrange(): final_str = "" left_trans_vec = np.array([150, 0, 70]) right_trans_vec = np.array([-150, 0, 70]) i = 1 for j in range(1, 50): file_path = os.path.join(dir_path, f"complete_{j}.ldr") if os.path.exists(file_path): bricks = read_bricks_from_file(file_path, read_fake_bricks=True) trans_vec = (i // 2) * left_trans_vec if i % 2 == 0 else (i // 2) * right_trans_vec for b in bricks: b.translate(trans_vec) final_str += b.to_ldraw() final_str += "\n" final_str += "\n0 STEP\n" i = i + 1 return final_str def line_arrange(): final_str = "" for i in range(80, 104): file_path = os.path.join(dir_path, f"complete_{i}.ldr") bricks = read_bricks_from_file(file_path, read_fake_bricks=True) trans_vec = np.array([180*i, 0, 0]) for b in bricks: b.translate(trans_vec) final_str += b.to_ldraw() final_str += "\n" final_str += "\n0 STEP\n" return final_str def triangle_arrange(): final_str = "" z_shift = 300 x_shift = 300 row, row_shift = 0,0 for j in range(1, 120): file_path = os.path.join(dir_path, f"complete_{j}.ldr") if os.path.exists(file_path): bricks = read_bricks_from_file(file_path, read_fake_bricks=True) x = (-row * x_shift)/2 + row_shift * x_shift z = row * z_shift trans_vec = np.array([x, 0, z]) for b in bricks: b.translate(trans_vec) final_str += b.to_ldraw() final_str += "\n" final_str += "\n0 STEP\n" if row_shift + 1 > row: row = row + 1 row_shift = 0 else: row_shift = row_shift + 1 return final_str if __name__ == "__main__": debugger = MyDebugger("brick_heads") dir_path = r"/Users/apple/Dropbox/deecamp/results" final_str = line_arrange() file = open(debugger.file_path('composed.ldr'), "a") file.write(final_str) file.close()
[ "util.debugger.MyDebugger", "os.path.exists", "bricks_modeling.file_IO.model_reader.read_bricks_from_file", "numpy.array", "os.path.join" ]
[((404, 426), 'numpy.array', 'np.array', (['[150, 0, 70]'], {}), '([150, 0, 70])\n', (412, 426), True, 'import numpy as np\n'), ((449, 472), 'numpy.array', 'np.array', (['[-150, 0, 70]'], {}), '([-150, 0, 70])\n', (457, 472), True, 'import numpy as np\n'), ((2298, 2323), 'util.debugger.MyDebugger', 'MyDebugger', (['"""brick_heads"""'], {}), "('brick_heads')\n", (2308, 2323), False, 'from util.debugger import MyDebugger\n'), ((532, 575), 'os.path.join', 'os.path.join', (['dir_path', 'f"""complete_{j}.ldr"""'], {}), "(dir_path, f'complete_{j}.ldr')\n", (544, 575), False, 'import os\n'), ((587, 612), 'os.path.exists', 'os.path.exists', (['file_path'], {}), '(file_path)\n', (601, 612), False, 'import os\n'), ((1103, 1146), 'os.path.join', 'os.path.join', (['dir_path', 'f"""complete_{i}.ldr"""'], {}), "(dir_path, f'complete_{i}.ldr')\n", (1115, 1146), False, 'import os\n'), ((1164, 1219), 'bricks_modeling.file_IO.model_reader.read_bricks_from_file', 'read_bricks_from_file', (['file_path'], {'read_fake_bricks': '(True)'}), '(file_path, read_fake_bricks=True)\n', (1185, 1219), False, 'from bricks_modeling.file_IO.model_reader import read_bricks_from_file\n'), ((1240, 1265), 'numpy.array', 'np.array', (['[180 * i, 0, 0]'], {}), '([180 * i, 0, 0])\n', (1248, 1265), True, 'import numpy as np\n'), ((1604, 1647), 'os.path.join', 'os.path.join', (['dir_path', 'f"""complete_{j}.ldr"""'], {}), "(dir_path, f'complete_{j}.ldr')\n", (1616, 1647), False, 'import os\n'), ((1659, 1684), 'os.path.exists', 'os.path.exists', (['file_path'], {}), '(file_path)\n', (1673, 1684), False, 'import os\n'), ((635, 690), 'bricks_modeling.file_IO.model_reader.read_bricks_from_file', 'read_bricks_from_file', (['file_path'], {'read_fake_bricks': '(True)'}), '(file_path, read_fake_bricks=True)\n', (656, 690), False, 'from bricks_modeling.file_IO.model_reader import read_bricks_from_file\n'), ((1707, 1762), 'bricks_modeling.file_IO.model_reader.read_bricks_from_file', 'read_bricks_from_file', (['file_path'], {'read_fake_bricks': '(True)'}), '(file_path, read_fake_bricks=True)\n', (1728, 1762), False, 'from bricks_modeling.file_IO.model_reader import read_bricks_from_file\n'), ((1874, 1893), 'numpy.array', 'np.array', (['[x, 0, z]'], {}), '([x, 0, z])\n', (1882, 1893), True, 'import numpy as np\n')]
# Only about 74% accuratee import tensorflow as tf import nltk import io from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer # useful for finding roots of words import numpy as np import pickle n_nodes_hl1 = 400 #these can be different and whatever you like n_nodes_hl2 = 400 lemmatizer = WordNetLemmatizer() n_classes = 2 batch_size = 32 total_batches = int(1600000/batch_size) hm_epochs = 10 x = tf.placeholder('float') # will throw an error if the shape is not correct y = tf.placeholder('float') hidden_1_layer = {'f_fum': n_nodes_hl1, 'weights':tf.Variable(tf.truncated_normal([2569, n_nodes_hl1], stddev=0.1)), 'biases':tf.Variable(tf.constant(0.1,shape=[n_nodes_hl1]))} hidden_2_layer = {'f_fum': n_nodes_hl2, 'weights':tf.Variable(tf.truncated_normal([n_nodes_hl1, n_nodes_hl2], stddev=0.1)), 'biases':tf.Variable(tf.constant(0.1,shape=[n_nodes_hl2]))} output_layer = {'f_fum': None, 'weights':tf.Variable(tf.truncated_normal([n_nodes_hl2, n_classes], stddev=0.1)), 'biases':tf.Variable(tf.constant(0.1,shape=[n_classes]))} def neural_network_model(data): # input_data*weights + biases layer1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases']) layer1 = tf.nn.relu(layer1) # applies an activation function for rectified linear layer2 = tf.add(tf.matmul(layer1, hidden_2_layer['weights']), hidden_2_layer['biases']) layer2 = tf.nn.relu(layer2) output = tf.matmul(layer2, output_layer['weights'])+ output_layer['biases'] return output saver = tf.train.Saver() tf_log = 'tf.log' def train_neural_net(x): prediction = neural_network_model(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) try: epoch = int(open(tf_log, 'r').read().split('\n')[-2])+1 print('Starting:', epoch) except: epoch = 1 while epoch <= hm_epochs: if epoch != 1: saver.restore(sess, "./model.ckpt") epoch_loss = 1 with open('lexicon-2500-2569.pickle', 'rb') as f: lexicon = pickle.load(f) with open('train_set_shuffled.csv', buffering = 200000, encoding='latin-1') as f: counter = 0 batch_x = [] batch_y = [] batches_run = 0 for line in f: counter += 1 label = line.split(':::')[0] tweet = line.split(':::')[1] current_words = word_tokenize(tweet.lower()) current_words = [lemmatizer.lemmatize(i) for i in current_words] features = np.zeros(len(lexicon)) for word in current_words: if word.lower() in lexicon: index_value = lexicon.index(word.lower()) features[index_value] += 1 batch_x.append(list(features)) batch_y.append(eval(label)) if len(batch_x) >= batch_size: _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) epoch_loss += c batch_x = [] batch_y = [] batches_run += 1 if (batches_run / 1000).is_integer(): print('Batch run:', batches_run, '/', total_batches,'| Epoch:', epoch, '| Batch Loss:', c,) saver.save(sess, "./model.ckpt") print('Epoch', epoch+1, 'completed out of', hm_epochs, 'loss:', epoch_loss) with open(tf_log, 'a') as f: f.write(str(epoch)+'\n') epoch +=1 # Do once! # train_neural_net(x) def test_NN(): prediction = neural_network_model(x) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(hm_epochs): try: saver.restore(sess, './model.ckpt') except Exception as e: print(str(e)) epoch_loss = 0 correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) featuresets = [] labels = [] counter = 0 with open('processed-test-set.csv', buffering=200000) as f: for line in f: try: features = list(eval(line.split('::')[0])) label = list(eval(line.split('::')[1])) featuresets.append(features) labels.append(label) counter +=1 except: pass print("Tested", counter, "samples.") test_x = np.array(featuresets) test_y= np.array(labels) print('Accuracy:',accuracy.eval({x:test_x, y:test_y})) test_NN()
[ "tensorflow.nn.relu", "tensorflow.train.Saver", "nltk.stem.WordNetLemmatizer", "tensorflow.global_variables_initializer", "tensorflow.argmax", "tensorflow.Session", "tensorflow.constant", "tensorflow.nn.softmax_cross_entropy_with_logits_v2", "tensorflow.placeholder", "tensorflow.matmul", "tensorflow.cast", "numpy.array", "pickle.load", "tensorflow.train.AdamOptimizer", "tensorflow.truncated_normal" ]
[((335, 354), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (352, 354), False, 'from nltk.stem import WordNetLemmatizer\n'), ((451, 474), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (465, 474), True, 'import tensorflow as tf\n'), ((530, 553), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (544, 553), True, 'import tensorflow as tf\n'), ((1631, 1647), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1645, 1647), True, 'import tensorflow as tf\n'), ((1315, 1333), 'tensorflow.nn.relu', 'tf.nn.relu', (['layer1'], {}), '(layer1)\n', (1325, 1333), True, 'import tensorflow as tf\n'), ((1497, 1515), 'tensorflow.nn.relu', 'tf.nn.relu', (['layer2'], {}), '(layer2)\n', (1507, 1515), True, 'import tensorflow as tf\n'), ((619, 671), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[2569, n_nodes_hl1]'], {'stddev': '(0.1)'}), '([2569, n_nodes_hl1], stddev=0.1)\n', (638, 671), True, 'import tensorflow as tf\n'), ((714, 751), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': '[n_nodes_hl1]'}), '(0.1, shape=[n_nodes_hl1])\n', (725, 751), True, 'import tensorflow as tf\n'), ((818, 877), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[n_nodes_hl1, n_nodes_hl2]'], {'stddev': '(0.1)'}), '([n_nodes_hl1, n_nodes_hl2], stddev=0.1)\n', (837, 877), True, 'import tensorflow as tf\n'), ((914, 951), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': '[n_nodes_hl2]'}), '(0.1, shape=[n_nodes_hl2])\n', (925, 951), True, 'import tensorflow as tf\n'), ((1009, 1066), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[n_nodes_hl2, n_classes]'], {'stddev': '(0.1)'}), '([n_nodes_hl2, n_classes], stddev=0.1)\n', (1028, 1066), True, 'import tensorflow as tf\n'), ((1103, 1138), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': '[n_classes]'}), '(0.1, shape=[n_classes])\n', (1114, 1138), True, 'import tensorflow as tf\n'), ((1231, 1273), 'tensorflow.matmul', 'tf.matmul', (['data', "hidden_1_layer['weights']"], {}), "(data, hidden_1_layer['weights'])\n", (1240, 1273), True, 'import tensorflow as tf\n'), ((1411, 1455), 'tensorflow.matmul', 'tf.matmul', (['layer1', "hidden_2_layer['weights']"], {}), "(layer1, hidden_2_layer['weights'])\n", (1420, 1455), True, 'import tensorflow as tf\n'), ((1532, 1574), 'tensorflow.matmul', 'tf.matmul', (['layer2', "output_layer['weights']"], {}), "(layer2, output_layer['weights'])\n", (1541, 1574), True, 'import tensorflow as tf\n'), ((1764, 1835), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'prediction', 'labels': 'y'}), '(logits=prediction, labels=y)\n', (1806, 1835), True, 'import tensorflow as tf\n'), ((1929, 1941), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1939, 1941), True, 'import tensorflow as tf\n'), ((4218, 4230), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (4228, 4230), True, 'import tensorflow as tf\n'), ((5188, 5209), 'numpy.array', 'np.array', (['featuresets'], {}), '(featuresets)\n', (5196, 5209), True, 'import numpy as np\n'), ((5227, 5243), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (5235, 5243), True, 'import numpy as np\n'), ((1854, 1897), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (1876, 1897), True, 'import tensorflow as tf\n'), ((1969, 2002), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2000, 2002), True, 'import tensorflow as tf\n'), ((4258, 4291), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4289, 4291), True, 'import tensorflow as tf\n'), ((4529, 4553), 'tensorflow.argmax', 'tf.argmax', (['prediction', '(1)'], {}), '(prediction, 1)\n', (4538, 4553), True, 'import tensorflow as tf\n'), ((4555, 4570), 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), '(y, 1)\n', (4564, 4570), True, 'import tensorflow as tf\n'), ((4607, 4632), 'tensorflow.cast', 'tf.cast', (['correct', '"""float"""'], {}), "(correct, 'float')\n", (4614, 4632), True, 'import tensorflow as tf\n'), ((2420, 2434), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2431, 2434), False, 'import pickle\n')]
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import matplotlib.transforms as transforms from matplotlib import rcParams from matplotlib.colors import LinearSegmentedColormap from p3iv_utils_probability.distributions import ( BivariateNormalDistribution, UnivariateNormalDistributionSequence, ) # , \ # TruncatedUnivariateNormalSequenceDistribution, UnivariateNormalSequenceMixtureDistribution, \ # TruncatedUnivariateNormalSequenceMixtureDistribution rcParams["text.usetex"] = True class PlotProbabilityDistribution(object): def __init__(self): self.colors = [ "#FF0000", # red "#800000", # maroon "#0000FF", # blue "#000080", # navy "#008080", # teal "#800080", # purple "#9FE2BF", # light-green "#FA8072", # salmon "#CCCCFF", # lila "#FF00FF", ] # fuchsia def __call__(self, ax, distribution, *args, **kwargs): """Inspect the type of distribution and call the corresponding plot method.""" assert isinstance(ax, plt.Axes) color = np.random.choice(self.colors) cmap = self.AlphaGradientColormap(color) if isinstance(distribution, BivariateNormalDistribution): self.plot_bivariate_pdf(ax, distribution, cmap=cmap) # elif isinstance(distribution, (UnivariateNormalSequenceDistribution, TruncatedUnivariateNormalSequenceDistribution)): elif isinstance(distribution, UnivariateNormalDistributionSequence): self.plot_univariate_sequence_cmap(ax, distribution, cmap=cmap) """ elif isinstance(distribution, (UnivariateNormalSequenceMixtureDistribution, TruncatedUnivariateNormalSequenceMixtureDistribution)): self.plot_univariate_sequence_mixture(ax, distribution) """ else: raise Exception("Plot function is not defined for data type %s" % str(type(distribution))) @staticmethod def AlphaGradientColormap(color): """ Factory function for creating colormap instances with alpha gradient. :param color: Hex color code w/o alpha value e.g. '#AABBCC' :return: LinearSegmentedColormap instance """ colors = [color + "00", color + "FF"] return LinearSegmentedColormap.from_list("alpha_gradient_color_map_" + color, colors) @staticmethod def plot_bivariate_pdf(ax, distribution, cmap="viridis", annotate=False): x, y = distribution.mean mesh_range = 10 X, Y = np.meshgrid( np.linspace(x - mesh_range, x + mesh_range, 500), np.linspace(y - mesh_range, y + mesh_range, 500) ) ax.contourf(X, Y, distribution.pdf(x, y, mesh_range=10), 50, cmap=cmap) if annotate: ax.annotate( r"$ \mu = (%.2f, %.2f) \\ " r"\Sigma = \left[\begin{array}{cc} %.2f & %.2f \\ %.2f & %.2f \\ \end{array}\right]$" % ( x, y, distribution.covariance[0, 0], distribution.covariance[0, 1], distribution.covariance[1, 0], distribution.covariance[1, 1], ), (x, y - mesh_range + 2), textcoords="offset points", size=12, ) def plot_bivariate_pdf_confidence_ellipse(self, ax, distribution, color=None, n_std=2): if not color: color = np.random.choice(self.colors) ax.plot(distribution.mean[0], distribution.mean[1], color=color, marker="o") for i in range(n_std): n = i + 1 x, y, theta, ell_radius_x, ell_radius_y = distribution.range(n) ellipse = Ellipse( (0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, linestyle="dashed", edgecolor=color, facecolor="none", linewidth=1.5, label=r"$%d\sigma$" % n, ) transf = transforms.Affine2D().rotate_deg(np.rad2deg(theta)).translate(x, y) ellipse.set_transform(transf + ax.transData) ax.add_patch(ellipse) def plot_bivariate_sequence_1d(self, ax, distribution, n_std=2): pass def plot_univariate_pdf(self, ax, distribution, n_std=3.0, weight=1.0): pass def plot_univariate_sequence(self, ax, distribution, color=None, n_std=3, weight=1.0): plots = [] if not color: color = np.random.choice(self.colors) sequence_range = np.arange(len(distribution.mean)) (p,) = ax.plot(sequence_range, distribution.mean, color=color, linestyle="--", linewidth=1) plots.append(p) gamma = 1 / n_std for i in range(n_std): n = i + 1 lower_bound, upper_bound = distribution.range(n) c = ax.fill_between(sequence_range, upper_bound, lower_bound, facecolor=color, alpha=gamma * weight) plots.append(c) return plots @staticmethod def plot_univariate_sequence_cmap(ax, distribution, cmap="viridis", n_std=3, weight=1.0): max_std = np.max(distribution.covariance) # the points for which every distribution is calculated ny = 1000 y0 = np.linspace(-n_std * max_std, n_std * max_std, ny) X, Y = np.meshgrid(list(range(len(distribution))), y0) Y += distribution.mean # shift Y by the mean to get the true coordinates # map X and Y coordinates to indices of img Y = Y.astype(float) miny = np.min(Y) maxy = np.max(Y) y_idx = np.round((Y - miny) / (maxy - miny) * (ny - 1)).astype(int) X = X.astype(float) minx = np.min(X) maxx = np.max(X) nx = float(len(distribution)) x_idx = np.round((X - minx) / (maxx - minx) * (nx - 1)).astype(int) # convert X, Y, Z to one array for imshow img = np.zeros((ny, len(distribution))) img[y_idx, x_idx] = distribution.pdf(Y, distribution.mean) extent = np.min(X), np.max(X), np.min(Y), np.max(Y) ax.imshow(img, cmap=cmap, origin="lower", aspect="auto", extent=extent) def plot_univariate_sequence_mixture(self, ax, tr_g_m, n_std=3): plots = [] color = np.random.choice(self.colors) for i in range(len(tr_g_m.weights)): weight = tr_g_m.weights[i] tr_g = tr_g_m.components[i] pl = self.plot_univariate_sequence(ax, tr_g, color=color, n_std=n_std, weight=weight) plots.extend(pl) return plots
[ "matplotlib.colors.LinearSegmentedColormap.from_list", "numpy.rad2deg", "numpy.max", "numpy.min", "numpy.linspace", "numpy.random.choice", "matplotlib.patches.Ellipse", "numpy.round", "matplotlib.transforms.Affine2D" ]
[((1169, 1198), 'numpy.random.choice', 'np.random.choice', (['self.colors'], {}), '(self.colors)\n', (1185, 1198), True, 'import numpy as np\n'), ((2366, 2444), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (["('alpha_gradient_color_map_' + color)", 'colors'], {}), "('alpha_gradient_color_map_' + color, colors)\n", (2399, 2444), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((5296, 5327), 'numpy.max', 'np.max', (['distribution.covariance'], {}), '(distribution.covariance)\n', (5302, 5327), True, 'import numpy as np\n'), ((5424, 5474), 'numpy.linspace', 'np.linspace', (['(-n_std * max_std)', '(n_std * max_std)', 'ny'], {}), '(-n_std * max_std, n_std * max_std, ny)\n', (5435, 5474), True, 'import numpy as np\n'), ((5716, 5725), 'numpy.min', 'np.min', (['Y'], {}), '(Y)\n', (5722, 5725), True, 'import numpy as np\n'), ((5741, 5750), 'numpy.max', 'np.max', (['Y'], {}), '(Y)\n', (5747, 5750), True, 'import numpy as np\n'), ((5871, 5880), 'numpy.min', 'np.min', (['X'], {}), '(X)\n', (5877, 5880), True, 'import numpy as np\n'), ((5896, 5905), 'numpy.max', 'np.max', (['X'], {}), '(X)\n', (5902, 5905), True, 'import numpy as np\n'), ((6432, 6461), 'numpy.random.choice', 'np.random.choice', (['self.colors'], {}), '(self.colors)\n', (6448, 6461), True, 'import numpy as np\n'), ((2639, 2687), 'numpy.linspace', 'np.linspace', (['(x - mesh_range)', '(x + mesh_range)', '(500)'], {}), '(x - mesh_range, x + mesh_range, 500)\n', (2650, 2687), True, 'import numpy as np\n'), ((2689, 2737), 'numpy.linspace', 'np.linspace', (['(y - mesh_range)', '(y + mesh_range)', '(500)'], {}), '(y - mesh_range, y + mesh_range, 500)\n', (2700, 2737), True, 'import numpy as np\n'), ((3570, 3599), 'numpy.random.choice', 'np.random.choice', (['self.colors'], {}), '(self.colors)\n', (3586, 3599), True, 'import numpy as np\n'), ((3837, 4006), 'matplotlib.patches.Ellipse', 'Ellipse', (['(0, 0)'], {'width': '(ell_radius_x * 2)', 'height': '(ell_radius_y * 2)', 'linestyle': '"""dashed"""', 'edgecolor': 'color', 'facecolor': '"""none"""', 'linewidth': '(1.5)', 'label': "('$%d\\\\sigma$' % n)"}), "((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, linestyle=\n 'dashed', edgecolor=color, facecolor='none', linewidth=1.5, label=\n '$%d\\\\sigma$' % n)\n", (3844, 4006), False, 'from matplotlib.patches import Ellipse\n'), ((4648, 4677), 'numpy.random.choice', 'np.random.choice', (['self.colors'], {}), '(self.colors)\n', (4664, 4677), True, 'import numpy as np\n'), ((6204, 6213), 'numpy.min', 'np.min', (['X'], {}), '(X)\n', (6210, 6213), True, 'import numpy as np\n'), ((6215, 6224), 'numpy.max', 'np.max', (['X'], {}), '(X)\n', (6221, 6224), True, 'import numpy as np\n'), ((6226, 6235), 'numpy.min', 'np.min', (['Y'], {}), '(Y)\n', (6232, 6235), True, 'import numpy as np\n'), ((6237, 6246), 'numpy.max', 'np.max', (['Y'], {}), '(Y)\n', (6243, 6246), True, 'import numpy as np\n'), ((5767, 5814), 'numpy.round', 'np.round', (['((Y - miny) / (maxy - miny) * (ny - 1))'], {}), '((Y - miny) / (maxy - miny) * (ny - 1))\n', (5775, 5814), True, 'import numpy as np\n'), ((5960, 6007), 'numpy.round', 'np.round', (['((X - minx) / (maxx - minx) * (nx - 1))'], {}), '((X - minx) / (maxx - minx) * (nx - 1))\n', (5968, 6007), True, 'import numpy as np\n'), ((4195, 4212), 'numpy.rad2deg', 'np.rad2deg', (['theta'], {}), '(theta)\n', (4205, 4212), True, 'import numpy as np\n'), ((4162, 4183), 'matplotlib.transforms.Affine2D', 'transforms.Affine2D', ([], {}), '()\n', (4181, 4183), True, 'import matplotlib.transforms as transforms\n')]
# todo: Implement Neural Network (or Logistic Regression) From Scratch</h2> # todo: importing libraries import numpy as np from tensorflow import keras import pandas as pd from matplotlib import pyplot as plt # todo: load dataSet df = pd.read_csv("insurance_data.csv") df.head() # todo: Split train and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(df[['age', 'affordibility']], df.bought_insurance, test_size=0.2, random_state=25) # todo: PreProcessing: Scale the data so that both age and affordability are in same scaling range X_train_scaled = X_train.copy() X_train_scaled['age'] = X_train_scaled['age'] / 100 X_test_scaled = X_test.copy() X_test_scaled['age'] = X_test_scaled['age'] / 100 # todo: DL model model = keras.Sequential([ keras.layers.Dense(1, input_shape=(2,), activation='sigmoid', kernel_initializer='ones', bias_initializer='zeros') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(X_train_scaled, y_train, epochs=5000) # todo: Evaluate the model on test set model.evaluate(X_test_scaled, y_test) print("model predict", model.predict(X_test_scaled)) print("y_test", y_test) # todo: Now get the value of weights and bias from the model coef, intercept = model.get_weights() print("coef, intercept", coef, intercept) # todo: This means w1=5.060867, w2=1.4086502, bias =-2.9137027 def sigmoid(x): import math return 1 / (1 + math.exp(-x)) print("sigmoid(18)", sigmoid(18)) print("X_test", X_test) # todo: Instead of model.predict, write our own prediction function that uses w1,w2 and bias def prediction_function(age, affordibility): weighted_sum = coef[0] * age + coef[1] * affordibility + intercept return sigmoid(weighted_sum) print(".47, 1", prediction_function(.47, 1)) print(".18, 1", prediction_function(.18, 1)) def sigmoid_numpy(x): return 1 / (1 + np.exp(-x)) print("sigmoid_numpy", sigmoid_numpy(np.array([12, 0, 1]))) def log_loss(y_true, y_predicted): epsilon = 1e-15 y_predicted_new = [max(i, epsilon) for i in y_predicted] y_predicted_new = [min(i, 1 - epsilon) for i in y_predicted_new] y_predicted_new = np.array(y_predicted_new) return -np.mean(y_true * np.log(y_predicted_new) + (1 - y_true) * np.log(1 - y_predicted_new)) # todo: All right now comes the time to implement our own custom neural network class !! yay !!! class myNN: def __init__(self): self.w1 = 1 self.w2 = 1 self.bias = 0 def fit(self, X, y, epochs, loss_thresold): self.w1, self.w2, self.bias = self.gradient_descent(X['age'], X['affordibility'], y, epochs, loss_thresold) print(f"Final weights and bias: w1: {self.w1}, w2: {self.w2}, bias: {self.bias}") def predict(self, X_test): weighted_sum = self.w1 * X_test['age'] + self.w2 * X_test['affordibility'] + self.bias return sigmoid_numpy(weighted_sum) def gradient_descent(self, age, affordability, y_true, epochs, loss_thresold): w1 = w2 = 1 bias = 0 rate = 0.5 n = len(age) for i in range(epochs): weighted_sum = w1 * age + w2 * affordability + bias y_predicted = sigmoid_numpy(weighted_sum) loss = log_loss(y_true, y_predicted) w1d = (1 / n) * np.dot(np.transpose(age), (y_predicted - y_true)) w2d = (1 / n) * np.dot(np.transpose(affordability), (y_predicted - y_true)) bias_d = np.mean(y_predicted - y_true) w1 = w1 - rate * w1d w2 = w2 - rate * w2d bias = bias - rate * bias_d if i % 50 == 0: print(f'Epoch:{i}, w1:{w1}, w2:{w2}, bias:{bias}, loss:{loss}') if loss <= loss_thresold: print(f'Epoch:{i}, w1:{w1}, w2:{w2}, bias:{bias}, loss:{loss}') break return w1, w2, bias customModel = myNN() customModel.fit(X_train_scaled, y_train, epochs=8000, loss_thresold=0.4631) print(coef, intercept) # todo: This shows that in the end we were able to come up with same value of w1,w2 and bias using a plain python implementation of gradient descent function print(X_test_scaled) # todo: (1) Predict using custom model print(customModel.predict(X_test_scaled)) # todo: (2) Predict using tensorflow model print(model.predict(X_test_scaled))
[ "math.exp", "numpy.log", "tensorflow.keras.layers.Dense", "pandas.read_csv", "sklearn.model_selection.train_test_split", "numpy.transpose", "numpy.mean", "numpy.array", "numpy.exp" ]
[((237, 270), 'pandas.read_csv', 'pd.read_csv', (['"""insurance_data.csv"""'], {}), "('insurance_data.csv')\n", (248, 270), True, 'import pandas as pd\n'), ((404, 507), 'sklearn.model_selection.train_test_split', 'train_test_split', (["df[['age', 'affordibility']]", 'df.bought_insurance'], {'test_size': '(0.2)', 'random_state': '(25)'}), "(df[['age', 'affordibility']], df.bought_insurance,\n test_size=0.2, random_state=25)\n", (420, 507), False, 'from sklearn.model_selection import train_test_split\n'), ((2299, 2324), 'numpy.array', 'np.array', (['y_predicted_new'], {}), '(y_predicted_new)\n', (2307, 2324), True, 'import numpy as np\n'), ((869, 987), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'input_shape': '(2,)', 'activation': '"""sigmoid"""', 'kernel_initializer': '"""ones"""', 'bias_initializer': '"""zeros"""'}), "(1, input_shape=(2,), activation='sigmoid',\n kernel_initializer='ones', bias_initializer='zeros')\n", (887, 987), False, 'from tensorflow import keras\n'), ((2067, 2087), 'numpy.array', 'np.array', (['[12, 0, 1]'], {}), '([12, 0, 1])\n', (2075, 2087), True, 'import numpy as np\n'), ((1562, 1574), 'math.exp', 'math.exp', (['(-x)'], {}), '(-x)\n', (1570, 1574), False, 'import math\n'), ((2016, 2026), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (2022, 2026), True, 'import numpy as np\n'), ((3595, 3624), 'numpy.mean', 'np.mean', (['(y_predicted - y_true)'], {}), '(y_predicted - y_true)\n', (3602, 3624), True, 'import numpy as np\n'), ((2354, 2377), 'numpy.log', 'np.log', (['y_predicted_new'], {}), '(y_predicted_new)\n', (2360, 2377), True, 'import numpy as np\n'), ((2395, 2422), 'numpy.log', 'np.log', (['(1 - y_predicted_new)'], {}), '(1 - y_predicted_new)\n', (2401, 2422), True, 'import numpy as np\n'), ((3442, 3459), 'numpy.transpose', 'np.transpose', (['age'], {}), '(age)\n', (3454, 3459), True, 'import numpy as np\n'), ((3520, 3547), 'numpy.transpose', 'np.transpose', (['affordability'], {}), '(affordability)\n', (3532, 3547), True, 'import numpy as np\n')]
######################################### # # # <NAME> and <NAME> # # University of Fribourg # # 2019 # # Master's thesis # # # ######################################### import matplotlib.pyplot as plt import nibabel as nib import numpy as np from PIL import Image import sys def exploreAndConvert(niftiNpArray, npArrayMax, npArrayMin, sliceNumber, outputName, outputFolder, axisName, timeStamp=None, flip=False): """ Description: Converts a NIfTI slice to png Params: - niftiNpArray: 2d slice (NumPy array) - npArrayMax: maximal pixel value - npArrayMin: minimal pixel value - slice: index of the given slice - outputName: name of the output file - timeStamp: timestamp of the given slice Returns: - no return value """ # normalize pixel values niftiNpArray = (niftiNpArray - npArrayMin) * 255.0 / (npArrayMax - npArrayMin) # convert to 8 bits (required to export as PNG) niftiNpArray = (niftiNpArray).astype('uint8') if flip: niftiNpArray = 255 - niftiNpArray # create a grayscaled image png = Image.fromarray(niftiNpArray).convert('L') # save as PNG if (timeStamp == None): png.save("{}{}_{}_slice{}.png".format(outputFolder, outputName, axisName, sliceNumber)) else: png.save("{}{}_{}_time{}_slice{}.png".format(outputFolder, outputName,axisName, timeStamp, sliceNumber)) def niftiToPng(niftiPath, outputName, outputFolder='./', flip=False): """ Description: Converts 3D or 4D .nii images to png Params: - niftiPath: path to the .nii file - outputName: name used in the output file Returns: - no return value """ # Load the .nii file niftiObject = nib.load(niftiPath) # get_fdata() casts to 64 bits niftiNpArray = niftiObject.get_fdata() # 3D if (len(niftiObject.shape) == 3): # Get the dimensions (x, y, z) = niftiObject.shape npArrayMin = np.min(niftiNpArray) npArrayMax = np.max(niftiNpArray) # On X-Axis for i in range (0, x): exploreAndConvert(niftiNpArray[i,:,:], npArrayMax, npArrayMin, i, outputName, outputFolder, 'x', flip=flip) # On Y-Axis for i in range (0, y): exploreAndConvert(niftiNpArray[:,i,:], npArrayMax, npArrayMin, i, outputName, outputFolder, 'y', flip=flip) # On Z-Axis for i in range (0, z): exploreAndConvert(niftiNpArray[:,:,i], npArrayMax, npArrayMin, i, outputName, outputFolder, 'z', flip=flip) # 4D elif (len(niftiObject.shape) == 4): # x = nb of Rows, y = nb of Columns, z = nb of Slices, t = time frame (x, y, z, t) = niftiObject.shape for ythTimeStamp in range(0, t): # Get maximal and mini values npArrayMin = np.min(niftiNpArray[:,:,:,ythTimeStamp]) npArrayMax = np.max(niftiNpArray[:,:,:,ythTimeStamp]) # On X-Axis for ithSlice in range (0, x): exploreAndConvert(niftiNpArray[ithSlice, :, :, ythTimeStamp], npArrayMax, npArrayMin, ithSlice, outputName, outputFolder, 'x', ythTimeStamp, flip=flip) # On Y-Axis for ithSlice in range (0, y): exploreAndConvert(niftiNpArray[:, ithSlice,:, ythTimeStamp], npArrayMax, npArrayMin, ithSlice, outputName, outputFolder, 'y', ythTimeStamp, flip=flip) # On Z-Axis for ithSlice in range (0, z): exploreAndConvert(niftiNpArray[:, :, ithSlice, ythTimeStamp], npArrayMax, npArrayMin, ithSlice, outputName, outputFolder, 'z', ythTimeStamp, flip=flip)
[ "PIL.Image.fromarray", "numpy.min", "numpy.max", "nibabel.load" ]
[((1908, 1927), 'nibabel.load', 'nib.load', (['niftiPath'], {}), '(niftiPath)\n', (1916, 1927), True, 'import nibabel as nib\n'), ((2145, 2165), 'numpy.min', 'np.min', (['niftiNpArray'], {}), '(niftiNpArray)\n', (2151, 2165), True, 'import numpy as np\n'), ((2187, 2207), 'numpy.max', 'np.max', (['niftiNpArray'], {}), '(niftiNpArray)\n', (2193, 2207), True, 'import numpy as np\n'), ((1268, 1297), 'PIL.Image.fromarray', 'Image.fromarray', (['niftiNpArray'], {}), '(niftiNpArray)\n', (1283, 1297), False, 'from PIL import Image\n'), ((3003, 3046), 'numpy.min', 'np.min', (['niftiNpArray[:, :, :, ythTimeStamp]'], {}), '(niftiNpArray[:, :, :, ythTimeStamp])\n', (3009, 3046), True, 'import numpy as np\n'), ((3069, 3112), 'numpy.max', 'np.max', (['niftiNpArray[:, :, :, ythTimeStamp]'], {}), '(niftiNpArray[:, :, :, ythTimeStamp])\n', (3075, 3112), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on 15 Jul 2019 19:58:50 @author: jiahuei """ from link_dirs import BASE_DIR, CURR_DIR, pjoin import argparse import os import json import re import numpy as np from time import localtime, strftime from tqdm import tqdm from bisect import bisect_left from common.natural_sort import natural_keys as nat_key from common import configuration_v1 as cfg P_NUM = re.compile(r'[0-9][0-9,]+') pjoin = os.path.join # noinspection PyTypeChecker def _create_parser(): _parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter) _parser.add_argument( '--log_dir', '-l', type=str, default='', help='The logging directory.') _parser.add_argument( '--collect_runs', '-c', type=str, default='1', help='Comma-separated list of runs to collect.') _parser.add_argument( '--reverse_sort_dirs', '-r', type=bool, default=False, help='If True, reverse sort directories.') _parser.add_argument( '--caption_statistics', '-s', type=bool, default=True, help='If True, calculate statistics of captions including percentage of unique captions etc.') _parser.add_argument( '--verbose', '-v', type=bool, default=False, help='If True, print everything.') _parser.add_argument( '--train_caption_txt', '-t', type=str, default='/home/jiahuei/Documents/3_Datasets/MSCOCO_captions/captions/mscoco_train_w5_s20_include_restval.txt', help='Training data text file.') return _parser def main(args): print('') a = args default_exp_dir = pjoin(BASE_DIR, 'experiments') if a.log_dir == '': a.log_dir = default_exp_dir def _should_add(path): _is_infer = 'infer' in os.path.split(path)[1] if args.collect_runs == 'all': return _is_infer else: runs = ['run_{:02d}'.format(int(r)) for r in args.collect_runs.split(',')] return _is_infer and _extract_keys(path)[1] in runs # List experiments exp_dirs = [pjoin(a.log_dir, n) for n in os.listdir(a.log_dir)] all_score_dirs = [] for exp_dir in exp_dirs: if not os.path.isdir(exp_dir): continue sub_dirs = [pjoin(exp_dir, d) for d in os.listdir(exp_dir)] score_dirs = [d for d in sub_dirs if _should_add(d)] all_score_dirs += score_dirs # Extract scores for sort_checkpoints in [True, False]: score_dict = {} _loop(all_score_dirs, score_dict, 'valid', sort_checkpoints, args) _loop(all_score_dirs, score_dict, 'test', sort_checkpoints, args) _write_output_csv(score_dict, args.log_dir, sort_checkpoints, reverse_exps=a.reverse_sort_dirs) print('\nScore collection completed.\n') def _loop(all_score_dirs, score_dict, current_set, sort_checkpoints, args): desc = 'Collecting `{}` {} checkpoint sorting'.format(current_set, 'with' if sort_checkpoints else 'without') for d in tqdm(sorted(all_score_dirs), desc=desc): if current_set not in d: continue exp_name, run, infer_name, datetime = _extract_keys(d) score_file = pjoin(d, 'metric_scores.csv') if not os.path.isfile(score_file): print('WARNING: `{}` does not contain `metric_scores.csv` file.'.format( pjoin(exp_name, '___'.join([run, infer_name, datetime])))) continue if args.verbose: s = os.path.sep print('Processing dir: `{}`'.format(s.join(d.split(s)[-2:]))) if current_set == 'test': valid_name = infer_name.replace('test', 'valid') try: best_ckpt_num = score_dict[valid_name][exp_name][run]['best_ckpt'] _, best_score = _get_ckpt(score_file, get_checkpoint_num=best_ckpt_num) except KeyError: print('WARNING: Validation results not found for: `{}`'.format( pjoin(exp_name, '___'.join([run, infer_name])))) continue else: best_ckpt_num, best_score = _get_ckpt(score_file, sort_checkpoints) # Get captions stats if args.caption_statistics: with open(args.train_caption_txt, 'r') as f: train_caption = [ l.strip().split(',')[1].replace('<GO> ', '').replace(' <EOS>', '') for l in f.readlines()] train_caption = set(train_caption) # train_caption.sort() stats = _get_caption_statistics(train_caption_set=train_caption, curr_score_dir=d, checkpoint_num=best_ckpt_num) else: stats = np.array([-1, -1, -1]) model_size = _get_model_size(curr_score_dir=d) val = dict(name=exp_name, run=run, infer_name=infer_name, datetime=datetime, best_ckpt=best_ckpt_num, best_score=best_score, caption_stats=stats, model_size=model_size) if infer_name not in score_dict: score_dict[infer_name] = {} if exp_name not in score_dict[infer_name]: score_dict[infer_name][exp_name] = {} if run in score_dict[infer_name][exp_name]: print('WARNING: `{}` has more than 1 eval results. Keeping latest one.'.format( pjoin(exp_name, '___'.join([run, infer_name])))) score_dict[infer_name][exp_name][run] = val def _write_output_csv(sc_dict, log_dir, sort_checkpoints, reverse_exps=False): if sort_checkpoints: sfx = 'sorted' else: sfx = 'last' for infer_name in sorted(sc_dict): datetime = strftime('%m-%d_%H-%M-%S', localtime()) fname = infer_name.replace('infer_', '') + '___{}___{}.csv'.format(sfx, datetime) lines = [] for exp_name in sorted(sc_dict[infer_name], reverse=reverse_exps): runs = [sc_dict[infer_name][exp_name][r] for r in sorted(sc_dict[infer_name][exp_name])] mean_stats = [] for i, r in enumerate(runs): mean_stats.append(r['caption_stats']) if i == 0: name = r['name'] else: name = '-' line = ','.join([name, r['run'], str(r['best_ckpt']), _score_to_string(r['best_score']), r['model_size'], _score_to_string(r['caption_stats']), r['infer_name'], r['datetime']]) lines.append(line) if len(runs) > 1: mean_score = _score_to_string(_get_average([r['best_score'] for r in runs])) mean_stats = _score_to_string(_get_average(mean_stats)) line = ','.join(['-', 'mean', '0', mean_score, mean_stats, 'N/A', 'N/A']) lines.append(line) with open(pjoin(log_dir, fname), 'w') as f: f.write('\r\n'.join(lines)) def _score_to_string(score): return ','.join(['{:1.3f}'.format(sc) for sc in list(score)]) def _get_average(list_of_scores): scores = np.stack(list_of_scores, axis=0) return np.mean(scores, axis=0) def _get_ckpt(score_file, sort_checkpoints=True, get_checkpoint_num=None): scores = np.genfromtxt(score_file, delimiter=',') if scores.shape[1] > 3: # MNIST files have only 3 columns scores = scores[:, :-2] ckpt_nums, scores = scores[:, 0].astype(np.int64), scores[:, 1:].astype(np.float64) # Calculate weighted average # 2x weightage for B-4, CIDEr, SPICE wg = np.array([[1, 1, 1, 2, 1, 1, 2, 2]]).astype(np.float64) try: scores_wg_av = np.mean(scores * wg, axis=1) except ValueError: # Give up, take first value lol scores_wg_av = scores[:, 0] if get_checkpoint_num: max_idx = int(np.where(ckpt_nums == int(get_checkpoint_num))[0]) # max_idx = np.where(ckpt_nums == int(get_checkpoint_num))[0] else: if sort_checkpoints: # Get best checkpoint max_idx = np.where(scores_wg_av == np.amax(scores_wg_av)) if len(max_idx[0]) > 1: if scores.shape[1] > 6: # For ties, sort by CIDEr max_idx = int(np.argmax(scores[:, 6])) else: # MNIST, take last checkpoint max_idx = max_idx[0][-1] else: max_idx = int(max_idx[0]) else: # Get final checkpoint max_idx = ckpt_nums.shape[0] - 1 sparsity_file = pjoin(os.path.split(score_file)[0], 'sparsity_values.csv') if os.path.isfile(sparsity_file): sparsity = np.genfromtxt(sparsity_file, delimiter=',', skip_header=1) def _check(): # noinspection PyTypeChecker return sparsity.shape[0] != ckpt_nums.shape[0] or sparsity[max_idx, 0] != ckpt_nums[max_idx] if _check(): # Try again without skipping header sparsity = np.genfromtxt(sparsity_file, delimiter=',') if _check(): raise ValueError('Checkpoint check failed. {} vs {} for idx {}'.format( sparsity[max_idx, 0], ckpt_nums[max_idx], max_idx)) sparsity = sparsity[max_idx, 1:2] else: sparsity = [-1] score = np.concatenate([sparsity, scores[max_idx], [scores_wg_av[max_idx]]]) return ckpt_nums[max_idx], score def _get_caption_statistics(train_caption_set, curr_score_dir, checkpoint_num=None, default_vocab_size=9962): # float_str = '{:.3f}' # assert isinstance(train_caption_list, list) assert isinstance(train_caption_set, set) # Try to load vocab size from config c = cfg.load_config(pjoin(os.path.dirname(curr_score_dir), 'run_01', 'config.pkl')) try: vocab_size = len(c.itow) except AttributeError: vocab_size = default_vocab_size # Find caption file if checkpoint_num is None: jsons = [f for f in os.listdir(curr_score_dir) if 'captions___' in f] jsons = [j for j in sorted(jsons, key=nat_key)] caption_json = pjoin(curr_score_dir, jsons[-1]) else: caption_json = pjoin(curr_score_dir, 'captions___{}.json'.format(checkpoint_num)) # Load captions with open(caption_json, 'r') as f: captions = json.load(f) captions_list = [d['caption'] for d in captions] # Calculate stats appear_in_train = 0 counts = {} caption_length = [] for caption in captions_list: # Unique if caption in train_caption_set: appear_in_train += 1 # appear_in_train += binary_search(data_list=train_caption_list, query=caption) # Vocab caption = caption.split(' ') for w in caption: counts[w] = counts.get(w, 0) + 1 # Length caption_length.append(len(caption)) vocab_coverage = (len(counts) / (vocab_size - 2)) * 100. # Exclude <GO> and <EOS> average_length = np.mean(caption_length) percent_unique = (1. - (appear_in_train / len(captions_list))) * 100. return np.array([vocab_coverage, percent_unique, average_length]) def _get_model_size(curr_score_dir): # Try to load model size file msfp = pjoin(os.path.dirname(curr_score_dir), 'run_01', 'model_size.txt') with open(msfp, 'r') as f: line = f.readlines()[1] model_size = P_NUM.findall(line) assert isinstance(model_size, list) and len(model_size) == 1 return model_size[0].replace(',', '') def binary_search(data_list, query, lo=0, hi=None): # can't use data_list to specify default for hi # https://stackoverflow.com/questions/212358/binary-search-bisection-in-python hi = hi if hi is not None else len(data_list) # hi defaults to len(data_list) pos = bisect_left(a=data_list, x=query, lo=lo, hi=hi) # find insertion position return 1 if pos != hi and data_list[pos] == query else 0 # don't walk off the end def _extract_keys(score_dirpath): exp_dirpath, score_dir = os.path.split(score_dirpath) exp_name = os.path.split(exp_dirpath)[1] elems = score_dir.split('___') if len(elems) == 3: run, infer_name, datetime = elems elif len(elems) == 2: run, infer_name = elems datetime = 'none' else: raise ValueError('Invalid directory name format. Must have at least `run_XX` and `infer_name`.') return exp_name, run, infer_name, datetime if __name__ == '__main__': parser = _create_parser() main(parser.parse_args())
[ "numpy.stack", "json.load", "bisect.bisect_left", "argparse.ArgumentParser", "numpy.argmax", "os.path.isdir", "os.path.dirname", "numpy.genfromtxt", "numpy.amax", "os.path.isfile", "numpy.mean", "numpy.array", "time.localtime", "os.path.split", "link_dirs.pjoin", "os.listdir", "numpy.concatenate", "re.compile" ]
[((395, 421), 're.compile', 're.compile', (['"""[0-9][0-9,]+"""'], {}), "('[0-9][0-9,]+')\n", (405, 421), False, 'import re\n'), ((511, 588), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(formatter_class=argparse.RawDescriptionHelpFormatter)\n', (534, 588), False, 'import argparse\n'), ((1633, 1663), 'link_dirs.pjoin', 'pjoin', (['BASE_DIR', '"""experiments"""'], {}), "(BASE_DIR, 'experiments')\n", (1638, 1663), False, 'from link_dirs import BASE_DIR, CURR_DIR, pjoin\n'), ((7228, 7260), 'numpy.stack', 'np.stack', (['list_of_scores'], {'axis': '(0)'}), '(list_of_scores, axis=0)\n', (7236, 7260), True, 'import numpy as np\n'), ((7272, 7295), 'numpy.mean', 'np.mean', (['scores'], {'axis': '(0)'}), '(scores, axis=0)\n', (7279, 7295), True, 'import numpy as np\n'), ((7386, 7426), 'numpy.genfromtxt', 'np.genfromtxt', (['score_file'], {'delimiter': '""","""'}), "(score_file, delimiter=',')\n", (7399, 7426), True, 'import numpy as np\n'), ((8775, 8804), 'os.path.isfile', 'os.path.isfile', (['sparsity_file'], {}), '(sparsity_file)\n', (8789, 8804), False, 'import os\n'), ((9467, 9535), 'numpy.concatenate', 'np.concatenate', (['[sparsity, scores[max_idx], [scores_wg_av[max_idx]]]'], {}), '([sparsity, scores[max_idx], [scores_wg_av[max_idx]]])\n', (9481, 9535), True, 'import numpy as np\n'), ((11231, 11254), 'numpy.mean', 'np.mean', (['caption_length'], {}), '(caption_length)\n', (11238, 11254), True, 'import numpy as np\n'), ((11340, 11398), 'numpy.array', 'np.array', (['[vocab_coverage, percent_unique, average_length]'], {}), '([vocab_coverage, percent_unique, average_length])\n', (11348, 11398), True, 'import numpy as np\n'), ((12036, 12083), 'bisect.bisect_left', 'bisect_left', ([], {'a': 'data_list', 'x': 'query', 'lo': 'lo', 'hi': 'hi'}), '(a=data_list, x=query, lo=lo, hi=hi)\n', (12047, 12083), False, 'from bisect import bisect_left\n'), ((12263, 12291), 'os.path.split', 'os.path.split', (['score_dirpath'], {}), '(score_dirpath)\n', (12276, 12291), False, 'import os\n'), ((2087, 2106), 'link_dirs.pjoin', 'pjoin', (['a.log_dir', 'n'], {}), '(a.log_dir, n)\n', (2092, 2106), False, 'from link_dirs import BASE_DIR, CURR_DIR, pjoin\n'), ((3202, 3231), 'link_dirs.pjoin', 'pjoin', (['d', '"""metric_scores.csv"""'], {}), "(d, 'metric_scores.csv')\n", (3207, 3231), False, 'from link_dirs import BASE_DIR, CURR_DIR, pjoin\n'), ((7786, 7814), 'numpy.mean', 'np.mean', (['(scores * wg)'], {'axis': '(1)'}), '(scores * wg, axis=1)\n', (7793, 7814), True, 'import numpy as np\n'), ((8825, 8883), 'numpy.genfromtxt', 'np.genfromtxt', (['sparsity_file'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(sparsity_file, delimiter=',', skip_header=1)\n", (8838, 8883), True, 'import numpy as np\n'), ((10347, 10379), 'link_dirs.pjoin', 'pjoin', (['curr_score_dir', 'jsons[-1]'], {}), '(curr_score_dir, jsons[-1])\n', (10352, 10379), False, 'from link_dirs import BASE_DIR, CURR_DIR, pjoin\n'), ((10563, 10575), 'json.load', 'json.load', (['f'], {}), '(f)\n', (10572, 10575), False, 'import json\n'), ((11489, 11520), 'os.path.dirname', 'os.path.dirname', (['curr_score_dir'], {}), '(curr_score_dir)\n', (11504, 11520), False, 'import os\n'), ((12307, 12333), 'os.path.split', 'os.path.split', (['exp_dirpath'], {}), '(exp_dirpath)\n', (12320, 12333), False, 'import os\n'), ((2116, 2137), 'os.listdir', 'os.listdir', (['a.log_dir'], {}), '(a.log_dir)\n', (2126, 2137), False, 'import os\n'), ((2207, 2229), 'os.path.isdir', 'os.path.isdir', (['exp_dir'], {}), '(exp_dir)\n', (2220, 2229), False, 'import os\n'), ((2272, 2289), 'link_dirs.pjoin', 'pjoin', (['exp_dir', 'd'], {}), '(exp_dir, d)\n', (2277, 2289), False, 'from link_dirs import BASE_DIR, CURR_DIR, pjoin\n'), ((3247, 3273), 'os.path.isfile', 'os.path.isfile', (['score_file'], {}), '(score_file)\n', (3261, 3273), False, 'import os\n'), ((4777, 4799), 'numpy.array', 'np.array', (['[-1, -1, -1]'], {}), '([-1, -1, -1])\n', (4785, 4799), True, 'import numpy as np\n'), ((5772, 5783), 'time.localtime', 'localtime', ([], {}), '()\n', (5781, 5783), False, 'from time import localtime, strftime\n'), ((7698, 7734), 'numpy.array', 'np.array', (['[[1, 1, 1, 2, 1, 1, 2, 2]]'], {}), '([[1, 1, 1, 2, 1, 1, 2, 2]])\n', (7706, 7734), True, 'import numpy as np\n'), ((8715, 8740), 'os.path.split', 'os.path.split', (['score_file'], {}), '(score_file)\n', (8728, 8740), False, 'import os\n'), ((9162, 9205), 'numpy.genfromtxt', 'np.genfromtxt', (['sparsity_file'], {'delimiter': '""","""'}), "(sparsity_file, delimiter=',')\n", (9175, 9205), True, 'import numpy as np\n'), ((9963, 9994), 'os.path.dirname', 'os.path.dirname', (['curr_score_dir'], {}), '(curr_score_dir)\n', (9978, 9994), False, 'import os\n'), ((1787, 1806), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (1800, 1806), False, 'import os\n'), ((2299, 2318), 'os.listdir', 'os.listdir', (['exp_dir'], {}), '(exp_dir)\n', (2309, 2318), False, 'import os\n'), ((7008, 7029), 'link_dirs.pjoin', 'pjoin', (['log_dir', 'fname'], {}), '(log_dir, fname)\n', (7013, 7029), False, 'from link_dirs import BASE_DIR, CURR_DIR, pjoin\n'), ((10218, 10244), 'os.listdir', 'os.listdir', (['curr_score_dir'], {}), '(curr_score_dir)\n', (10228, 10244), False, 'import os\n'), ((8209, 8230), 'numpy.amax', 'np.amax', (['scores_wg_av'], {}), '(scores_wg_av)\n', (8216, 8230), True, 'import numpy as np\n'), ((8388, 8411), 'numpy.argmax', 'np.argmax', (['scores[:, 6]'], {}), '(scores[:, 6])\n', (8397, 8411), True, 'import numpy as np\n')]
import numpy as np import torch from torch import nn import torchvision from core import build_graph, cat, to_numpy torch.backends.cudnn.benchmark = True device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") @cat.register(torch.Tensor) def _(*xs): return torch.cat(xs) @to_numpy.register(torch.Tensor) def _(x): return x.detach().cpu().numpy() def warmup_cudnn(model, batch_size): #run forward and backward pass of the model on a batch of random inputs #to allow benchmarking of cudnn kernels batch = { 'input': torch.Tensor(np.random.rand(batch_size, 3, 32, 32)).cuda().half(), 'target': torch.LongTensor(np.random.randint(0, 10, batch_size)).cuda() } model.train(True) o = model(batch) o['loss'].sum().backward() model.zero_grad() torch.cuda.synchronize() ##################### ## dataset ##################### def cifar10(root): train_set = torchvision.datasets.CIFAR10(root=root, train=True, download=True) test_set = torchvision.datasets.CIFAR10(root=root, train=False, download=True) return { 'train': { 'data': train_set.data, 'labels': train_set.targets }, 'test': { 'data': test_set.data, 'labels': test_set.targets } } def cifar100(root): train_set = torchvision.datasets.CIFAR100(root=root, train=True, download=True) test_set = torchvision.datasets.CIFAR100(root=root, train=False, download=True) return { 'train': { 'data': train_set.data, 'labels': train_set.targets }, 'test': { 'data': test_set.data, 'labels': test_set.targets } } ##################### ## data loading ##################### class Batches(): def __init__(self, dataset, batch_size, shuffle, set_random_choices=False, num_workers=0, drop_last=False): self.dataset = dataset self.batch_size = batch_size self.set_random_choices = set_random_choices self.dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, shuffle=shuffle, drop_last=drop_last) def __iter__(self): if self.set_random_choices: self.dataset.set_random_choices() return ({ 'input': x.to(device).half(), 'target': y.to(device).long() } for (x, y) in self.dataloader) def __len__(self): return len(self.dataloader) ##################### ## torch stuff ##################### class Identity(nn.Module): def forward(self, x): return x class Mul(nn.Module): def __init__(self, weight): super().__init__() self.weight = weight def __call__(self, x): return x * self.weight class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), x.size(1)) class Add(nn.Module): def forward(self, x, y): return x + y class Concat(nn.Module): def forward(self, *xs): return torch.cat(xs, 1) class Correct(nn.Module): def forward(self, classifier, target): return classifier.max(dim=1)[1] == target def batch_norm(num_channels, bn_bias_init=None, bn_bias_freeze=False, bn_weight_init=None, bn_weight_freeze=False): m = nn.BatchNorm2d(num_channels) if bn_bias_init is not None: m.bias.data.fill_(bn_bias_init) if bn_bias_freeze: m.bias.requires_grad = False if bn_weight_init is not None: m.weight.data.fill_(bn_weight_init) if bn_weight_freeze: m.weight.requires_grad = False return m class Network(nn.Module): def __init__(self, net): self.graph = build_graph(net) super().__init__() for n, (v, _) in self.graph.items(): setattr(self, n, v) def forward(self, inputs): self.cache = dict(inputs) for n, (_, i) in self.graph.items(): self.cache[n] = getattr(self, n)(*[self.cache[x] for x in i]) return self.cache def half(self): for module in self.children(): if not isinstance(module, nn.BatchNorm2d): module.half() return self trainable_params = lambda model: filter(lambda p: p.requires_grad, model.parameters()) class TorchOptimiser(): def __init__(self, weights, optimizer, step_number=0, **opt_params): self.weights = weights self.step_number = step_number self.opt_params = opt_params self._opt = optimizer(weights, **self.param_values()) def param_values(self): return { k: v(self.step_number) if callable(v) else v for k, v in self.opt_params.items() } def step(self): self.step_number += 1 self._opt.param_groups[0].update(**self.param_values()) self._opt.step() def __repr__(self): return repr(self._opt) def SGD(weights, lr=0, momentum=0, weight_decay=0, dampening=0, nesterov=False): return TorchOptimiser(weights, torch.optim.SGD, lr=lr, momentum=momentum, weight_decay=weight_decay, dampening=dampening, nesterov=nesterov)
[ "torch.cuda.synchronize", "torch.utils.data.DataLoader", "torchvision.datasets.CIFAR100", "torch.cat", "core.to_numpy.register", "core.build_graph", "torchvision.datasets.CIFAR10", "torch.nn.BatchNorm2d", "numpy.random.randint", "torch.cuda.is_available", "core.cat.register", "numpy.random.rand" ]
[((230, 256), 'core.cat.register', 'cat.register', (['torch.Tensor'], {}), '(torch.Tensor)\n', (242, 256), False, 'from core import build_graph, cat, to_numpy\n'), ((295, 326), 'core.to_numpy.register', 'to_numpy.register', (['torch.Tensor'], {}), '(torch.Tensor)\n', (312, 326), False, 'from core import build_graph, cat, to_numpy\n'), ((278, 291), 'torch.cat', 'torch.cat', (['xs'], {}), '(xs)\n', (287, 291), False, 'import torch\n'), ((835, 859), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (857, 859), False, 'import torch\n'), ((952, 1018), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': 'root', 'train': '(True)', 'download': '(True)'}), '(root=root, train=True, download=True)\n', (980, 1018), False, 'import torchvision\n'), ((1118, 1185), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': 'root', 'train': '(False)', 'download': '(True)'}), '(root=root, train=False, download=True)\n', (1146, 1185), False, 'import torchvision\n'), ((1513, 1580), 'torchvision.datasets.CIFAR100', 'torchvision.datasets.CIFAR100', ([], {'root': 'root', 'train': '(True)', 'download': '(True)'}), '(root=root, train=True, download=True)\n', (1542, 1580), False, 'import torchvision\n'), ((1682, 1750), 'torchvision.datasets.CIFAR100', 'torchvision.datasets.CIFAR100', ([], {'root': 'root', 'train': '(False)', 'download': '(True)'}), '(root=root, train=False, download=True)\n', (1711, 1750), False, 'import torchvision\n'), ((3944, 3972), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channels'], {}), '(num_channels)\n', (3958, 3972), False, 'from torch import nn\n'), ((189, 214), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (212, 214), False, 'import torch\n'), ((2456, 2600), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'num_workers': 'num_workers', 'pin_memory': '(True)', 'shuffle': 'shuffle', 'drop_last': 'drop_last'}), '(dataset, batch_size=batch_size, num_workers=\n num_workers, pin_memory=True, shuffle=shuffle, drop_last=drop_last)\n', (2483, 2600), False, 'import torch\n'), ((3628, 3644), 'torch.cat', 'torch.cat', (['xs', '(1)'], {}), '(xs, 1)\n', (3637, 3644), False, 'import torch\n'), ((4309, 4325), 'core.build_graph', 'build_graph', (['net'], {}), '(net)\n', (4320, 4325), False, 'from core import build_graph, cat, to_numpy\n'), ((696, 732), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', 'batch_size'], {}), '(0, 10, batch_size)\n', (713, 732), True, 'import numpy as np\n'), ((566, 603), 'numpy.random.rand', 'np.random.rand', (['batch_size', '(3)', '(32)', '(32)'], {}), '(batch_size, 3, 32, 32)\n', (580, 603), True, 'import numpy as np\n')]
"""Functions to find optimal production strategies.""" # Load packages # Standard library from itertools import product, chain, groupby from collections import namedtuple, defaultdict # External libraries import numpy as np from scipy.optimize import linprog # Local libraries from recipes import Item, Technology from common import update # Define named tuples EnumItem = namedtuple('item', ['id', *Item._fields]) OptimalTech = namedtuple( 'technology', [*Technology._fields, 'cycles'] ) TotalFlows = namedtuple('totalflows', ['inputs', 'intermediate', 'outputs']) def list_items(technologies): """List all items.""" inputs = set(i.name for t in technologies for i in t.inputs) outputs = set(i.name for t in technologies for i in t.outputs) return inputs.union(outputs) def list_products(technologies): """List intermediate and final products.""" return set(i.name for t in technologies for i in t.outputs) def list_resources(technologies): """List resources (there are no technologies that produce them).""" inputs = set(i.name for t in technologies for i in t.inputs) outputs = set(i.name for t in technologies for i in t.outputs) return inputs - outputs def enumerate_items(technologies): """Enumerate technology/item pairs""" rslt = [] j0 = 0 for t in technologies: j1 = j0 + len(t.inputs) inputs = [EnumItem(j0 + j, *item) for j, item in enumerate(t.inputs)] outputs = [EnumItem(j1 + j, *item) for j, item in enumerate(t.outputs)] rslt.append(Technology(**update(t, inputs=inputs, outputs=outputs))) j0 = j1 + len(t.outputs) return rslt def eq_matrices(technologies, no_vars): """Prepare matrices for equality constraints.""" no_eqs = no_vars - len(technologies) A_eq = np.zeros((no_eqs, no_vars)) b_eq = np.zeros(no_eqs) eq = 0 for t in technologies: x = product(t.inputs, t.outputs[:1]) y = product(t.inputs[:1], t.outputs[1:]) for (i, _, _, a), (j, _, _, b) in chain(x, y): A_eq[eq, i] = -b A_eq[eq, j] = a eq += 1 return A_eq, b_eq def ub_matrices(technologies, product_id, objectives, no_vars): """Prepare matrices for inequality constraints.""" no_eqs = len(product_id) A_ub = np.zeros((no_eqs, no_vars)) b_ub = np.zeros(no_eqs) for t in technologies: for i, n, _, _ in t.inputs: if (j := product_id.get(n)) is not None: A_ub[j, i] = 1 for i, n, _, _ in t.outputs: if (j := product_id.get(n)) is not None: A_ub[j, i] = -1 for i, a in objectives.items(): b_ub[product_id[i]] = -a return A_ub, b_ub def default_weights(resources, multiplier=1000): """Construct default weights.""" weights = defaultdict(lambda: 1) for r in resources: weights[r] = multiplier weights['water'] = 0 return weights def obj_vector(technologies, weights, no_vars): """Prepare the objective vector (minimizes production scale).""" c = np.zeros(no_vars) for t in technologies: for i, n, _, _ in t.inputs + t.outputs: c[i] = weights[n] return c def collect_results(technologies, lp_res): """List necessary technologies and the number of cycles required.""" solution = [] for t in technologies: i, _, _, a = t.outputs[0] cycles = lp_res.x[i]/a if not np.isclose(cycles, 0): inputs = [Item(*i[1:]) for i in t.inputs] # drop id outputs = [Item(*i[1:]) for i in t.outputs] # drop id solution.append(OptimalTech(**update( t, inputs=inputs, outputs=outputs, cycles=cycles ))) return solution def aggregate_flows(technologies): """Aggregate flows (assume worst-case layout for intermediate products).""" items = defaultdict(lambda: [0, 0]) types = {} for t in technologies: for name, item_type, amount in t.inputs: items[name][0] += amount*t.cycles types[name] = item_type for name, item_type, amount in t.outputs: items[name][1] += amount*t.cycles types[name] = item_type # Note: intermediate can overlap with inputs and outputs return TotalFlows( # Inputs (negative total balance) [Item(n, types[n], ain - aout) for n, (ain, aout) in items.items() if not np.isclose(ain, aout) and ain > aout], # Intermediate (there is both consumption and production) [Item(n, types[n], max(ain, aout)) for n, (ain, aout) in items.items() if not np.isclose(ain, 0) and not np.isclose(aout, 0)], # Outputs (positive total balance) [Item(n, types[n], aout - ain) for n, (ain, aout) in items.items() if not np.isclose(ain, aout) and aout > ain] ) def optimize(objectives, resources, technologies, weights=None): """Find optimal production inputs and respective technologies.""" if weights is None: weights = default_weights(resources) technologies = enumerate_items(technologies) products = list(list_items(technologies) - resources) product_id = {p: i for i, p in enumerate(products)} no_vars = sum(len(t.inputs) + len(t.outputs) for t in technologies) # Preapare and solve LP problem # (method='interior-point' fails to find some solutions) A_eq, b_eq = eq_matrices(technologies, no_vars) A_ub, b_ub = ub_matrices(technologies, product_id, objectives, no_vars) c = obj_vector(technologies, weights, no_vars) lp_res = linprog(c, A_ub, b_ub, A_eq, b_eq, method='highs-ds') if not lp_res.success: raise RuntimeError("The linear programming problem has no solution.") solution = collect_results(technologies, lp_res) return solution, aggregate_flows(solution) def optimize_or(objectives, resources, technologies): """Compute optimal technologes that would satisfy either objective.""" solutions = [optimize({k: v}, resources, technologies) for k, v in objectives.items()] # Merge technologies sol = [t for s, _ in solutions for t in s] key = lambda t: t.name sol = [list(g) for n, g in groupby(sorted(sol, key=key), key=key)] sol = [OptimalTech(**update(g[0], cycles=max(t.cycles for t in g))) for g in sol] # Merge flows def merge_flow(k): items = [i for _, f in solutions for i in f[k]] key = lambda i: i.name items = [list(g) for n, g in groupby(sorted(items, key=key), key=key)] return [Item(*g[0][:2], max(t[2] for t in g)) for g in items] flows = TotalFlows(*(merge_flow(i) for i in range(3))) return sol, flows
[ "numpy.zeros", "collections.defaultdict", "numpy.isclose", "scipy.optimize.linprog", "collections.namedtuple", "itertools.product", "itertools.chain", "common.update", "recipes.Item" ]
[((378, 419), 'collections.namedtuple', 'namedtuple', (['"""item"""', "['id', *Item._fields]"], {}), "('item', ['id', *Item._fields])\n", (388, 419), False, 'from collections import namedtuple, defaultdict\n'), ((434, 491), 'collections.namedtuple', 'namedtuple', (['"""technology"""', "[*Technology._fields, 'cycles']"], {}), "('technology', [*Technology._fields, 'cycles'])\n", (444, 491), False, 'from collections import namedtuple, defaultdict\n'), ((511, 574), 'collections.namedtuple', 'namedtuple', (['"""totalflows"""', "['inputs', 'intermediate', 'outputs']"], {}), "('totalflows', ['inputs', 'intermediate', 'outputs'])\n", (521, 574), False, 'from collections import namedtuple, defaultdict\n'), ((1806, 1833), 'numpy.zeros', 'np.zeros', (['(no_eqs, no_vars)'], {}), '((no_eqs, no_vars))\n', (1814, 1833), True, 'import numpy as np\n'), ((1849, 1865), 'numpy.zeros', 'np.zeros', (['no_eqs'], {}), '(no_eqs)\n', (1857, 1865), True, 'import numpy as np\n'), ((2315, 2342), 'numpy.zeros', 'np.zeros', (['(no_eqs, no_vars)'], {}), '((no_eqs, no_vars))\n', (2323, 2342), True, 'import numpy as np\n'), ((2358, 2374), 'numpy.zeros', 'np.zeros', (['no_eqs'], {}), '(no_eqs)\n', (2366, 2374), True, 'import numpy as np\n'), ((2840, 2863), 'collections.defaultdict', 'defaultdict', (['(lambda : 1)'], {}), '(lambda : 1)\n', (2851, 2863), False, 'from collections import namedtuple, defaultdict\n'), ((3090, 3107), 'numpy.zeros', 'np.zeros', (['no_vars'], {}), '(no_vars)\n', (3098, 3107), True, 'import numpy as np\n'), ((3904, 3932), 'collections.defaultdict', 'defaultdict', (['(lambda : [0, 0])'], {}), '(lambda : [0, 0])\n', (3915, 3932), False, 'from collections import namedtuple, defaultdict\n'), ((5622, 5675), 'scipy.optimize.linprog', 'linprog', (['c', 'A_ub', 'b_ub', 'A_eq', 'b_eq'], {'method': '"""highs-ds"""'}), "(c, A_ub, b_ub, A_eq, b_eq, method='highs-ds')\n", (5629, 5675), False, 'from scipy.optimize import linprog\n'), ((1917, 1949), 'itertools.product', 'product', (['t.inputs', 't.outputs[:1]'], {}), '(t.inputs, t.outputs[:1])\n', (1924, 1949), False, 'from itertools import product, chain, groupby\n'), ((1962, 1998), 'itertools.product', 'product', (['t.inputs[:1]', 't.outputs[1:]'], {}), '(t.inputs[:1], t.outputs[1:])\n', (1969, 1998), False, 'from itertools import product, chain, groupby\n'), ((2041, 2052), 'itertools.chain', 'chain', (['x', 'y'], {}), '(x, y)\n', (2046, 2052), False, 'from itertools import product, chain, groupby\n'), ((3469, 3490), 'numpy.isclose', 'np.isclose', (['cycles', '(0)'], {}), '(cycles, 0)\n', (3479, 3490), True, 'import numpy as np\n'), ((4373, 4402), 'recipes.Item', 'Item', (['n', 'types[n]', '(ain - aout)'], {}), '(n, types[n], ain - aout)\n', (4377, 4402), False, 'from recipes import Item, Technology\n'), ((4762, 4791), 'recipes.Item', 'Item', (['n', 'types[n]', '(aout - ain)'], {}), '(n, types[n], aout - ain)\n', (4766, 4791), False, 'from recipes import Item, Technology\n'), ((3514, 3526), 'recipes.Item', 'Item', (['*i[1:]'], {}), '(*i[1:])\n', (3518, 3526), False, 'from recipes import Item, Technology\n'), ((3580, 3592), 'recipes.Item', 'Item', (['*i[1:]'], {}), '(*i[1:])\n', (3584, 3592), False, 'from recipes import Item, Technology\n'), ((1566, 1607), 'common.update', 'update', (['t'], {'inputs': 'inputs', 'outputs': 'outputs'}), '(t, inputs=inputs, outputs=outputs)\n', (1572, 1607), False, 'from common import update\n'), ((3666, 3722), 'common.update', 'update', (['t'], {'inputs': 'inputs', 'outputs': 'outputs', 'cycles': 'cycles'}), '(t, inputs=inputs, outputs=outputs, cycles=cycles)\n', (3672, 3722), False, 'from common import update\n'), ((4458, 4479), 'numpy.isclose', 'np.isclose', (['ain', 'aout'], {}), '(ain, aout)\n', (4468, 4479), True, 'import numpy as np\n'), ((4661, 4679), 'numpy.isclose', 'np.isclose', (['ain', '(0)'], {}), '(ain, 0)\n', (4671, 4679), True, 'import numpy as np\n'), ((4688, 4707), 'numpy.isclose', 'np.isclose', (['aout', '(0)'], {}), '(aout, 0)\n', (4698, 4707), True, 'import numpy as np\n'), ((4847, 4868), 'numpy.isclose', 'np.isclose', (['ain', 'aout'], {}), '(ain, aout)\n', (4857, 4868), True, 'import numpy as np\n')]
from numpy.testing import assert_almost_equal from ctapipe.io.hessio import hessio_event_source from ctapipe.utils import get_dataset from ctapipe.calib.camera.r1 import CameraR1CalibratorFactory, \ HessioR1Calibrator def get_test_event(): filename = get_dataset('gamma_test.simtel.gz') source = hessio_event_source(filename, requested_event=409, use_event_id=True) event = next(source) return event def test_hessio_r1_calibrator(): telid = 11 event = get_test_event() calibrator = HessioR1Calibrator(None, None) calibrator.calibrate(event) r1 = event.r1.tel[telid].pe_samples assert_almost_equal(r1[0, 0, 0], -0.091, 3) def test_check_r0_exists(): telid = 11 event = get_test_event() calibrator = HessioR1Calibrator(None, None) assert(calibrator.check_r0_exists(event, telid) is True) event.r0.tel[telid].adc_samples = None assert(calibrator.check_r0_exists(event, telid) is False) def test_factory(): factory = CameraR1CalibratorFactory(None, None) cls = factory.get_class() calibrator = cls(None, None) telid = 11 event = get_test_event() calibrator.calibrate(event) r1 = event.r1.tel[telid].pe_samples assert_almost_equal(r1[0, 0, 0], -0.091, 3)
[ "ctapipe.calib.camera.r1.HessioR1Calibrator", "numpy.testing.assert_almost_equal", "ctapipe.io.hessio.hessio_event_source", "ctapipe.utils.get_dataset", "ctapipe.calib.camera.r1.CameraR1CalibratorFactory" ]
[((261, 296), 'ctapipe.utils.get_dataset', 'get_dataset', (['"""gamma_test.simtel.gz"""'], {}), "('gamma_test.simtel.gz')\n", (272, 296), False, 'from ctapipe.utils import get_dataset\n'), ((310, 379), 'ctapipe.io.hessio.hessio_event_source', 'hessio_event_source', (['filename'], {'requested_event': '(409)', 'use_event_id': '(True)'}), '(filename, requested_event=409, use_event_id=True)\n', (329, 379), False, 'from ctapipe.io.hessio import hessio_event_source\n'), ((551, 581), 'ctapipe.calib.camera.r1.HessioR1Calibrator', 'HessioR1Calibrator', (['None', 'None'], {}), '(None, None)\n', (569, 581), False, 'from ctapipe.calib.camera.r1 import CameraR1CalibratorFactory, HessioR1Calibrator\n'), ((658, 701), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['r1[0, 0, 0]', '(-0.091)', '(3)'], {}), '(r1[0, 0, 0], -0.091, 3)\n', (677, 701), False, 'from numpy.testing import assert_almost_equal\n'), ((793, 823), 'ctapipe.calib.camera.r1.HessioR1Calibrator', 'HessioR1Calibrator', (['None', 'None'], {}), '(None, None)\n', (811, 823), False, 'from ctapipe.calib.camera.r1 import CameraR1CalibratorFactory, HessioR1Calibrator\n'), ((1026, 1063), 'ctapipe.calib.camera.r1.CameraR1CalibratorFactory', 'CameraR1CalibratorFactory', (['None', 'None'], {}), '(None, None)\n', (1051, 1063), False, 'from ctapipe.calib.camera.r1 import CameraR1CalibratorFactory, HessioR1Calibrator\n'), ((1248, 1291), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['r1[0, 0, 0]', '(-0.091)', '(3)'], {}), '(r1[0, 0, 0], -0.091, 3)\n', (1267, 1291), False, 'from numpy.testing import assert_almost_equal\n')]
import numpy as np from itertools import product from . import tensor class Module(object): """Base class for all neural network modules. """ def __init__(self) -> None: """If a module behaves different between training and testing, its init method should inherit from this one.""" self.training = True def __call__(self, x: np.ndarray) -> np.ndarray: """Defines calling forward method at every call. Should not be overridden by subclasses. """ return self.forward(x) def forward(self, x: np.ndarray) -> np.ndarray: """Defines the forward propagation of the module performed at every call. Should be overridden by all subclasses. """ ... def backward(self, dy: np.ndarray) -> np.ndarray: """Defines the backward propagation of the module. """ return dy def train(self): """Sets the mode of the module to training. Should not be overridden by subclasses. """ if 'training' in vars(self): self.training = True for attr in vars(self).values(): if isinstance(attr, Module): Module.train() def eval(self): """Sets the mode of the module to eval. Should not be overridden by subclasses. """ if 'training' in vars(self): self.training = False for attr in vars(self).values(): if isinstance(attr, Module): Module.eval() class Linear(Module): def __init__(self, in_length: int, out_length: int, x): """Module which applies linear transformation to input. Args: in_length: L_in from expected input shape (N, L_in). out_length: L_out from output shape (N, L_out). """ # TODO Initialize the weight # of linear module. self.w = tensor.zeros((in_length, out_length)) self.x = x # End of todo def forward(self, x): """Forward propagation of linear module. Args: x: input of shape (N, L_in). Returns: out: output of shape (N, L_out). """ # TODO Implement forward propogation # of linear module. out = np.dot(x, self.w) return out # End of todo def backward(self, dy): """Backward propagation of linear module. Args: dy: output delta of shape (N, L_out). Returns: dx: input delta of shape (N, L_in). """ # TODO Implement backward propogation # of linear module. self.w.grad = np.dot(np.transpose(self.x), dy) dx = np.dot(dy, np.transpose(self.w)) return dx # End of todo class BatchNorm1d(Module): def __init__(self, length: int, momentum: float=0.9): """Module which applies batch normalization to input. Args: length: L from expected input shape (N, L). momentum: default 0.9. """ super(BatchNorm1d, self).__init__() # TODO Initialize the attributes # of 1d batchnorm module. self.length = length self.momentum = self.momentum # End of todo def forward(self, x): """Forward propagation of batch norm module. Args: x: input of shape (N, L). Returns: out: output of shape (N, L). """ # TODO Implement forward propogation # of 1d batchnorm module. out = None N = x.shape[0] # 求均值 ave_ope = 1/N * tensor.ones((1, N)) aves = np.dot(ave_ope, x) self.aves = aves # 求方差 x_squares = np.square(x) vars = 1/N * np.dot(ave_ope, x_squares) - np.square(aves) self.vars = vars # nolmalization out = (x - aves)/vars return out # End of todo def backward(self, dy): """Backward propagation of batch norm module. Args: dy: output delta of shape (N, L). Returns: dx: input delta of shape (N, L). """ # TODO Implement backward propogation # of 1d batchnorm module. dx = dy/self.vars return dx # End of todo class Conv2d(Module): def __init__(self, in_channels: int, channels: int, kernel_size: int=3, stride: int=1, padding: int=0, bias: bool=False): # 假定padding一直为0 # 假定只有一个卷积核 """Module which applies 2D convolution to input. Args: in_channels: C_in from expected input shape (B, C_in, H_in, W_in). channels: C_out from output shape (B, C_out, H_out, W_out). kernel_size: default 3. stride: default 1. padding: default 0. """ # TODO Initialize the attributes # of 2d convolution module. self.C_in = in_channels self.C_out = channels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.bias = bias self.kernel = tensor.random((self.kernel_size, self.kernel_size, in_channels)) # End of todo def forward(self, x): """Forward propagation of convolution module. Args: x: input of shape (B, C_in, H_in, W_in). Returns: out: output of shape (B, C_out, H_out, W_out). """ # TODO Implement forward propogation # of 2d convolution module. B, C_in, H_in, W_in = x.shape # compute output shape W_out = int((W_in - self.kernel_size)/self.stride + 1) H_out = int((H_in - self.kernel_size)/self.stride + 1) # Img2Col and merge channels img_col = Conv2d_im2col.forward(self, x) W_img_col = img_col.shape[3] img_col = img_col.reshape(B, -1, W_img_col) # kelnel2Col and merge kernel_col = self.kernel.reshape(1, self.kernel_size**2 * self.in_channels) out_col = np.dot(self.kernel, img_col) + self.bias.reshape(-1, 1) out = out_col.reshape(B, 1, H_out, W_out) # End of todo def backward(self, dy): """Backward propagation of convolution module. Args: dy: output delta of shape (B, C_out, H_out, W_out). Returns: dx: input delta of shape (B, C_in, H_in, W_in). """ # TODO Implement backward propogation # of 2d convolution module. kernel_size = self.kernel_size stride = self.stride C_in = self.C_in C_out = self.C_out B, C_in, H_in, W_in = input.shape ################################################################################# B, C_out, H_out, W_out = dy.shape """ compute b_grad """ b_grad = np.sum(dy, axis=(0, 2, 3)) b_grad = b_grad.reshape(C_out) # pad zero to input pad_input = np.pad(input, ((0, 0), (0, 0), (0, 0), (0, 0)), 'constant', constant_values=0) # Img2Col col_input = Conv2d_im2col.forward(pad_input, dy) # merge channel col_input = col_input.reshape(col_input.shape[0], -1, col_input.shape[3]) # transpose and reshape col_input to 2D matrix X_hat = col_input.transpose(1, 2, 0).reshape(C_in * self.kernel_size**2, -1) # transpose and reshape out_grad out_grad_reshape = dy.transpose(1, 2, 3, 0).reshape(C_out, -1) """ compute w_grad """ w_grad = out_grad_reshape @ X_hat.T w_grad = w_grad.reshape(W_out.shape) """ compute in_grad """ # reshape kernel W = W_out.reshape(C_out, -1) in_grad_column = W.T @ out_grad_reshape # Split batch dimension and transpose batch to first dimension in_grad_column = in_grad_column.reshape(in_grad_column.shape[0], -1, B).transpose(2, 0, 1) in_grad = Conv2d_col2im.forward(in_grad_column, dy) ################################################################################# return in_grad, w_grad, b_grad # End of todo class Conv2d_im2col(Conv2d): def forward(self, x): # TODO Implement forward propogation of # 2d convolution module using im2col method. """ Args: x: images of shape(B, C_in, H_in, W_in) Returns: out: column of shape(B, C_in, Kernel_size**2, W_out) """ B, C_in, H_in, W_in= x.shape W_out = ((W_in - self.kernel_size)/self.stride + 1) * \ ((H_in - self.kernel_size)/self.stride + 1) """W_out 的计算用到了除法,是float类型,需要转换成int""" W_out = int(W_out) out = tensor.zeros((B, C_in, self.kernel_size**2, W_out)) convhIdx = 0 convwIdx = 0 for i in range(B): for j in range(C_in): # scan from left_top convhIdx = 0 convwIdx = 0 for k in range(): if convwIdx + self.kernel_size > W_in: convwIdx = 0 convhIdx += self.stride out[i, j, :, k] = x[i, j, convhIdx:convhIdx+self.kernel_size, convwIdx:convwIdx+self.kernel_size].flatten().reshape((self.kernel_size**2, 1)) convwIdx += 1 return out # End of todo class Conv2d_col2im(Conv2d): def forward(self, x): # TODO Implement forward propogation of # 2d convolution module using col2im method. """ Args: x: column of shape(B, C_in, Kernel_size**2, W_in) Returns: out: images of shape(B, C_in, H_out, W_out) """ B = x.shape[0] C_in = x.shape[1] out = np.zeros((B, C_in, 0, 0)) # unchannel input, get shape (batch, channel, kernel_h*kernel_w, out_h*out_w) unchannel_x = x.reshape(x.shape[0], x.shape[1], -1, x.shape[2]) col_idx = 0 for i in range(B): for j in range(C_in): widx = 0 hidx = 0 # for each column in one channel for col_idx in range(unchannel_x.shape[-1]): # print(i, j, hidx, widx) out[i, j, hidx:hidx + self.kernel_size, widx:widx + self.kernel_size] += unchannel_x[i, j, :, col_idx].reshape( self.kernel_size, -1) widx += self.stride if widx + self.kernel_size > 0: widx = 0 hidx += self.stride return out # End of todo class AvgPool(Module): def __init__(self, kernel_size: int=2, stride: int=2, padding: int=0): """Module which applies average pooling to input. Args: kernel_size: default 2. stride: default 2. padding: default 0. """ # TODO Initialize the attributes # of average pooling module. self.kernel_size = kernel_size self.stride = stride self.padding = padding # End of todo def forward(self, x): """Forward propagation of average pooling module. Args: x: input of shape (B, C, H_in, W_in). Returns: out: output of shape (B, C, H_out, W_out). """ # TODO Implement forward propogation # of average pooling module. B, C, H_in, W_in = x.shape # compute output shape H_out = int((H_in - self.kernel_size)/self.stride + 1) W_out = int((W_in - self.kernel_size)/self.stride + 1) # Img2col img_col = Conv2d_im2col.forward(self, x) out = np.average(img_col, axis=2).reshape(B, C, H_out, W_out) return out # End of todo def backward(self, dy): """Backward propagation of average pooling module. Args: dy: output delta of shape (B, C, H_out, W_out). Returns: dx: input delta of shape (B, C, H_in, W_in). """ # TODO Implement backward propogation # of average pooling module. pool_size = self.kernel_size stride = self.stride B, C, H_in, W_in = dy.shape out_height = 1 + (H_in - pool_size) // stride out_width = 1 + (W_in - pool_size) // stride input_pad = np.pad(dy, pad_width=((0, 0), (0, 0), 0, 0), mode='constant', constant_values=0) recep_fields_h = [stride * i for i in range(out_height)] recep_fields_w = [stride * i for i in range(out_width)] input_pool = Conv2d_im2col.forward(input_pad, recep_fields_h, recep_fields_w, pool_size, pool_size) input_pool = input_pool.reshape( B, C, -1, out_height, out_width) scale = 1 / pool_size**2 input_pool_grad = scale * \ np.repeat(dy[:, :, np.newaxis, :, :], pool_size**2, axis=2) input_pool_grad = input_pool_grad.reshape( B, C, -1, out_height * out_width) input_pad_grad = np.zeros(input_pad.shape) idx = 0 for i in recep_fields_h: for j in recep_fields_w: input_pad_grad[:, :, i:i + pool_size, j:j + pool_size] += \ input_pool_grad[:, :, :, idx].reshape( B, C, pool_size, pool_size) idx += 1 in_grad = input_pad_grad[:, :, 0: H_in, 0: W_in] return in_grad # End of todo class MaxPool(Module): def __init__(self, kernel_size: int=2, stride: int=2, padding: int=0): """Module which applies max pooling to input. Args: kernel_size: default 2. stride: default 2. padding: default 0. """ # TODO Initialize the attributes # of maximum pooling module. self.kernel_size = kernel_size self.stride = stride self.padding = padding # End of todo def forward(self, x): """Forward propagation of max pooling module. Args: x: input of shape (B, C, H_in, W_in). Returns: out: output of shape (B, C, H_out, W_out). """ # TODO Implement forward propogation # of maximum pooling module. B, C, H_in, W_in = x.shape # compute output shape H_out = int((H_in - self.kernel_size) / self.stride + 1) W_out = int((W_in - self.kernel_size) / self.stride + 1) # Img2col img_col = Conv2d_im2col.forward(self, x) out = img_col.max(axis=2).reshape(B, C, H_out, W_out) return out # End of todo def backward(self, dy): """Backward propagation of max pooling module. Args: dy: output delta of shape (B, C, H_out, W_out). Returns: out: input delta of shape (B, C, H_in, W_in). """ # TODO Implement backward propogation # of maximum pooling module. pool_size = self.kernel_size stride = self.stride B, C, H_in, W_in = dy.shape out_height = 1 + (H_in - pool_size) // stride out_width = 1 + (W_in - pool_size) // stride input_pad = np.pad(dy, pad_width=((0, 0), (0, 0), 0, 0), mode='constant', constant_values=0) recep_fields_h = [stride * i for i in range(out_height)] recep_fields_w = [stride * i for i in range(out_width)] input_pool = Conv2d_im2col.forward(input_pad, recep_fields_h, recep_fields_w, pool_size, pool_size) input_pool = input_pool.reshape( B, C, -1, out_height, out_width) input_pool_grad = (input_pool == np.max(input_pool, axis=2, keepdims=True)) * \ dy[:, :, np.newaxis, :, :] input_pad_grad = np.zeros(input_pad.shape) idx = 0 for i in recep_fields_h: for j in recep_fields_w: input_pad_grad[:, :, i:i + pool_size, j:j + pool_size] += \ input_pool_grad[:, :, :, idx].reshape( B, C, pool_size, pool_size) idx += 1 in_grad = input_pad_grad[:, :, 0: H_in, 0: W_in] return in_grad # End of todo class Dropout(Module): def __init__(self, p: float=0.5): # TODO Initialize the attributes # of dropout module. self.p = 0.5 # End of todo def forward(self, x): # TODO Implement forward propogation # of dropout module. H1 = forward(x) U1 = np.random.rand(*H1.shape) < self.p # first dropout mask H1 *= U1 # drop! H2 = forward(H1) U2 = np.random.rand(*H2.shape) < self.p # second dropout mask H2 *= U2 # drop! out = forward(H2) # End of todo def backward(self, dy): # TODO Implement backward propogation # of dropout module. ... # End of todo if __name__ == '__main__': import pdb; pdb.set_trace()
[ "numpy.pad", "numpy.sum", "numpy.average", "numpy.square", "numpy.zeros", "numpy.transpose", "numpy.max", "pdb.set_trace", "numpy.random.rand", "numpy.dot", "numpy.repeat" ]
[((17418, 17433), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (17431, 17433), False, 'import pdb\n'), ((2285, 2302), 'numpy.dot', 'np.dot', (['x', 'self.w'], {}), '(x, self.w)\n', (2291, 2302), True, 'import numpy as np\n'), ((3661, 3679), 'numpy.dot', 'np.dot', (['ave_ope', 'x'], {}), '(ave_ope, x)\n', (3667, 3679), True, 'import numpy as np\n'), ((3739, 3751), 'numpy.square', 'np.square', (['x'], {}), '(x)\n', (3748, 3751), True, 'import numpy as np\n'), ((6878, 6904), 'numpy.sum', 'np.sum', (['dy'], {'axis': '(0, 2, 3)'}), '(dy, axis=(0, 2, 3))\n', (6884, 6904), True, 'import numpy as np\n'), ((6993, 7071), 'numpy.pad', 'np.pad', (['input', '((0, 0), (0, 0), (0, 0), (0, 0))', '"""constant"""'], {'constant_values': '(0)'}), "(input, ((0, 0), (0, 0), (0, 0), (0, 0)), 'constant', constant_values=0)\n", (6999, 7071), True, 'import numpy as np\n'), ((9919, 9944), 'numpy.zeros', 'np.zeros', (['(B, C_in, 0, 0)'], {}), '((B, C_in, 0, 0))\n', (9927, 9944), True, 'import numpy as np\n'), ((12633, 12718), 'numpy.pad', 'np.pad', (['dy'], {'pad_width': '((0, 0), (0, 0), 0, 0)', 'mode': '"""constant"""', 'constant_values': '(0)'}), "(dy, pad_width=((0, 0), (0, 0), 0, 0), mode='constant', constant_values=0\n )\n", (12639, 12718), True, 'import numpy as np\n'), ((13414, 13439), 'numpy.zeros', 'np.zeros', (['input_pad.shape'], {}), '(input_pad.shape)\n', (13422, 13439), True, 'import numpy as np\n'), ((15585, 15670), 'numpy.pad', 'np.pad', (['dy'], {'pad_width': '((0, 0), (0, 0), 0, 0)', 'mode': '"""constant"""', 'constant_values': '(0)'}), "(dy, pad_width=((0, 0), (0, 0), 0, 0), mode='constant', constant_values=0\n )\n", (15591, 15670), True, 'import numpy as np\n'), ((16229, 16254), 'numpy.zeros', 'np.zeros', (['input_pad.shape'], {}), '(input_pad.shape)\n', (16237, 16254), True, 'import numpy as np\n'), ((2670, 2690), 'numpy.transpose', 'np.transpose', (['self.x'], {}), '(self.x)\n', (2682, 2690), True, 'import numpy as np\n'), ((2720, 2740), 'numpy.transpose', 'np.transpose', (['self.w'], {}), '(self.w)\n', (2732, 2740), True, 'import numpy as np\n'), ((3802, 3817), 'numpy.square', 'np.square', (['aves'], {}), '(aves)\n', (3811, 3817), True, 'import numpy as np\n'), ((6050, 6078), 'numpy.dot', 'np.dot', (['self.kernel', 'img_col'], {}), '(self.kernel, img_col)\n', (6056, 6078), True, 'import numpy as np\n'), ((13194, 13255), 'numpy.repeat', 'np.repeat', (['dy[:, :, np.newaxis, :, :]', '(pool_size ** 2)'], {'axis': '(2)'}), '(dy[:, :, np.newaxis, :, :], pool_size ** 2, axis=2)\n', (13203, 13255), True, 'import numpy as np\n'), ((16978, 17003), 'numpy.random.rand', 'np.random.rand', (['*H1.shape'], {}), '(*H1.shape)\n', (16992, 17003), True, 'import numpy as np\n'), ((17099, 17124), 'numpy.random.rand', 'np.random.rand', (['*H2.shape'], {}), '(*H2.shape)\n', (17113, 17124), True, 'import numpy as np\n'), ((3773, 3799), 'numpy.dot', 'np.dot', (['ave_ope', 'x_squares'], {}), '(ave_ope, x_squares)\n', (3779, 3799), True, 'import numpy as np\n'), ((11970, 11997), 'numpy.average', 'np.average', (['img_col'], {'axis': '(2)'}), '(img_col, axis=2)\n', (11980, 11997), True, 'import numpy as np\n'), ((16103, 16144), 'numpy.max', 'np.max', (['input_pool'], {'axis': '(2)', 'keepdims': '(True)'}), '(input_pool, axis=2, keepdims=True)\n', (16109, 16144), True, 'import numpy as np\n')]
""" Non-Deterministic Gradient-Boosting ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We optimize a GradientBoosting on an artificially created binary classification dataset. The results are not deterministic so we need to evaluate each configuration multiple times. To ensure fair comparison, SMAC will only sample from a fixed set of random seeds and apply them to control the randomness of the function to be evaluated. To evaluate undeterministic functions, we need to set "deterministic" as "false". Additional to the configuration, the function should make use of the seed parameter as well. """ import logging logging.basicConfig(level=logging.INFO) import numpy as np from ConfigSpace.hyperparameters import ( UniformFloatHyperparameter, UniformIntegerHyperparameter, ) from sklearn.datasets import make_hastie_10_2 from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from smac.configspace import ConfigurationSpace from smac.facade.smac_hpo_facade import SMAC4HPO from smac.scenario.scenario import Scenario __copyright__ = "Copyright 2021, AutoML.org Freiburg-Hannover" __license__ = "3-clause BSD" # load data and split it into training and test dataset X, y = make_hastie_10_2(random_state=0) X_train, X_test = X[:8400], X[8400:] y_train, y_test = y[:8400], y[8400:] # Gradient Boosting scored with cross validation def xgboost_from_cfg(cfg, seed=0): # use random seed to control the randomness of the model and cross validator clf = GradientBoostingClassifier(**cfg, random_state=seed).fit(X_train, y_train) cv = KFold(n_splits=5, shuffle=True, random_state=seed) scores = cross_val_score(clf, X_train, y_train, cv=cv) return 1 - np.mean(scores) def eval_undeterministic_model(cfg, seeds): # Evaluate an undeterminstic model with the given configuration and a seed pool cfg_cv_scores = [0.0] * len(run_seeds) cfg_test_scores = [0.0] * len(run_seeds) for i, seed in enumerate(seeds): cfg_cv_scores[i] = xgboost_from_cfg(cfg, seed=seed) clf = GradientBoostingClassifier(**cfg, random_state=seed).fit(X_train, y_train) cfg_test_scores[i] = 1 - clf.score(X_test, y_test) return cfg_cv_scores, cfg_test_scores if __name__ == "__main__": # creating a Configuration Space with every parameter over which SMAC is going to optimize cs = ConfigurationSpace() max_depth = UniformIntegerHyperparameter("max_depth", 1, 10, default_value=3) cs.add_hyperparameter(max_depth) learning_rate = UniformFloatHyperparameter( "learning_rate", 0.01, 1.0, default_value=1.0, log=True ) cs.add_hyperparameter(learning_rate) min_samples_split = UniformFloatHyperparameter( "min_samples_split", 0.01, 1.0, default_value=0.1, log=True ) max_features = UniformIntegerHyperparameter("max_features", 2, 10, default_value=4) cs.add_hyperparameters([min_samples_split, max_features]) subsample = UniformFloatHyperparameter("subsample", 0.5, 1, default_value=0.8) cs.add_hyperparameter(subsample) cfg = cs.get_default_configuration() clf = GradientBoostingClassifier(**cfg, random_state=0).fit(X_train, y_train) def_test_score = 1 - clf.score(X_test, y_test) print("Default cross validation score: %.2f" % (xgboost_from_cfg(cfg))) print("Default test score: %.2f" % def_test_score) # scenario object scenario = Scenario( { "run_obj": "quality", "runcount-limit": 100, "cs": cs, # the evaluations are not deterministic, we need to repeat each # configuration several times and take the mean value of these repetitions "deterministic": "false", "wallclock_limit": 120, "maxR": 3, # Each configuration will be evaluated maximal 3 times with various seeds "minR": 1, # Each configuration will be repeated at least 1 time with different seeds } ) intensifier_kwargs = { "maxR": 3, # Each configuration will be evaluated maximal 3 times with various seeds "minR": 1, # Each configuration will be repeated at least 1 time with different seeds } smac = SMAC4HPO( scenario=scenario, rng=np.random.RandomState(0), intensifier_kwargs=intensifier_kwargs, tae_runner=xgboost_from_cfg, ) incumbent = smac.optimize() # get all the seeds applied to incumbent run_seeds = [] for inst_seed_budget in smac.get_runhistory().get_runs_for_config( incumbent, only_max_observed_budget=True ): run_seeds.append(inst_seed_budget.seed) cfg_default = cs.get_default_configuration() cfg_default_cv_scores, cfg_default_test_scores = eval_undeterministic_model( cfg_default, seeds=run_seeds ) print("Default cross validation score: %.2f" % (np.mean(cfg_default_cv_scores))) print("Default test score: %.2f" % np.mean(cfg_default_test_scores)) # the optimization process is called cfg_inc_cv_scores, cfg_inc_test_scores = eval_undeterministic_model( cfg_default, seeds=run_seeds ) # a classifier is trained with the hyperparameters returned from the optimizer print("Score on test set: %.2f" % np.mean(cfg_inc_test_scores))
[ "sklearn.datasets.make_hastie_10_2", "logging.basicConfig", "sklearn.model_selection.cross_val_score", "ConfigSpace.hyperparameters.UniformIntegerHyperparameter", "sklearn.model_selection.KFold", "numpy.random.RandomState", "sklearn.ensemble.GradientBoostingClassifier", "smac.configspace.ConfigurationSpace", "smac.scenario.scenario.Scenario", "ConfigSpace.hyperparameters.UniformFloatHyperparameter", "numpy.mean" ]
[((611, 650), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (630, 650), False, 'import logging\n'), ((1279, 1311), 'sklearn.datasets.make_hastie_10_2', 'make_hastie_10_2', ([], {'random_state': '(0)'}), '(random_state=0)\n', (1295, 1311), False, 'from sklearn.datasets import make_hastie_10_2\n'), ((1647, 1697), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(5)', 'shuffle': '(True)', 'random_state': 'seed'}), '(n_splits=5, shuffle=True, random_state=seed)\n', (1652, 1697), False, 'from sklearn.model_selection import KFold\n'), ((1711, 1756), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['clf', 'X_train', 'y_train'], {'cv': 'cv'}), '(clf, X_train, y_train, cv=cv)\n', (1726, 1756), False, 'from sklearn.model_selection import cross_val_score\n'), ((2427, 2447), 'smac.configspace.ConfigurationSpace', 'ConfigurationSpace', ([], {}), '()\n', (2445, 2447), False, 'from smac.configspace import ConfigurationSpace\n'), ((2465, 2530), 'ConfigSpace.hyperparameters.UniformIntegerHyperparameter', 'UniformIntegerHyperparameter', (['"""max_depth"""', '(1)', '(10)'], {'default_value': '(3)'}), "('max_depth', 1, 10, default_value=3)\n", (2493, 2530), False, 'from ConfigSpace.hyperparameters import UniformFloatHyperparameter, UniformIntegerHyperparameter\n'), ((2589, 2676), 'ConfigSpace.hyperparameters.UniformFloatHyperparameter', 'UniformFloatHyperparameter', (['"""learning_rate"""', '(0.01)', '(1.0)'], {'default_value': '(1.0)', 'log': '(True)'}), "('learning_rate', 0.01, 1.0, default_value=1.0,\n log=True)\n", (2615, 2676), False, 'from ConfigSpace.hyperparameters import UniformFloatHyperparameter, UniformIntegerHyperparameter\n'), ((2753, 2845), 'ConfigSpace.hyperparameters.UniformFloatHyperparameter', 'UniformFloatHyperparameter', (['"""min_samples_split"""', '(0.01)', '(1.0)'], {'default_value': '(0.1)', 'log': '(True)'}), "('min_samples_split', 0.01, 1.0, default_value=\n 0.1, log=True)\n", (2779, 2845), False, 'from ConfigSpace.hyperparameters import UniformFloatHyperparameter, UniformIntegerHyperparameter\n'), ((2874, 2942), 'ConfigSpace.hyperparameters.UniformIntegerHyperparameter', 'UniformIntegerHyperparameter', (['"""max_features"""', '(2)', '(10)'], {'default_value': '(4)'}), "('max_features', 2, 10, default_value=4)\n", (2902, 2942), False, 'from ConfigSpace.hyperparameters import UniformFloatHyperparameter, UniformIntegerHyperparameter\n'), ((3022, 3088), 'ConfigSpace.hyperparameters.UniformFloatHyperparameter', 'UniformFloatHyperparameter', (['"""subsample"""', '(0.5)', '(1)'], {'default_value': '(0.8)'}), "('subsample', 0.5, 1, default_value=0.8)\n", (3048, 3088), False, 'from ConfigSpace.hyperparameters import UniformFloatHyperparameter, UniformIntegerHyperparameter\n'), ((3471, 3612), 'smac.scenario.scenario.Scenario', 'Scenario', (["{'run_obj': 'quality', 'runcount-limit': 100, 'cs': cs, 'deterministic':\n 'false', 'wallclock_limit': 120, 'maxR': 3, 'minR': 1}"], {}), "({'run_obj': 'quality', 'runcount-limit': 100, 'cs': cs,\n 'deterministic': 'false', 'wallclock_limit': 120, 'maxR': 3, 'minR': 1})\n", (3479, 3612), False, 'from smac.scenario.scenario import Scenario\n'), ((1773, 1788), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (1780, 1788), True, 'import numpy as np\n'), ((1563, 1615), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'random_state': 'seed'}), '(**cfg, random_state=seed)\n', (1589, 1615), False, 'from sklearn.ensemble import GradientBoostingClassifier\n'), ((3178, 3227), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'random_state': '(0)'}), '(**cfg, random_state=0)\n', (3204, 3227), False, 'from sklearn.ensemble import GradientBoostingClassifier\n'), ((4316, 4340), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (4337, 4340), True, 'import numpy as np\n'), ((4933, 4963), 'numpy.mean', 'np.mean', (['cfg_default_cv_scores'], {}), '(cfg_default_cv_scores)\n', (4940, 4963), True, 'import numpy as np\n'), ((5005, 5037), 'numpy.mean', 'np.mean', (['cfg_default_test_scores'], {}), '(cfg_default_test_scores)\n', (5012, 5037), True, 'import numpy as np\n'), ((5318, 5346), 'numpy.mean', 'np.mean', (['cfg_inc_test_scores'], {}), '(cfg_inc_test_scores)\n', (5325, 5346), True, 'import numpy as np\n'), ((2118, 2170), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'random_state': 'seed'}), '(**cfg, random_state=seed)\n', (2144, 2170), False, 'from sklearn.ensemble import GradientBoostingClassifier\n')]
import os import os.path as osp import numpy as np from config import cfg import copy import json import scipy.io as sio import cv2 import random import math import torch import transforms3d from pycocotools.coco import COCO from utils.smpl import SMPL from utils.preprocessing import load_img, process_bbox, augmentation from utils.vis import vis_keypoints, vis_mesh, save_obj from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db class MSCOCO(torch.utils.data.Dataset): def __init__(self, transform, data_split): self.transform = transform self.data_split = 'train' if data_split == 'train' else 'val' self.img_path = osp.join('..', 'data', 'MSCOCO', 'images') self.annot_path = osp.join('..', 'data', 'MSCOCO', 'annotations') self.rootnet_output_path = osp.join('..', 'data', 'MSCOCO', 'rootnet_output', 'bbox_root_coco_output.json') self.fitting_thr = 3.0 # pixel in cfg.output_hm_shape space # mscoco skeleton self.coco_joint_num = 18 # original: 17, manually added pelvis self.coco_joints_name = ('Nose', 'L_Eye', 'R_Eye', 'L_Ear', 'R_Ear', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', 'L_Hip', 'R_Hip', 'L_Knee', 'R_Knee', 'L_Ankle', 'R_Ankle', 'Pelvis') self.coco_skeleton = ( (1, 2), (0, 1), (0, 2), (2, 4), (1, 3), (6, 8), (8, 10), (5, 7), (7, 9), (12, 14), (14, 16), (11, 13), (13, 15), (5, 6), (11, 12) ) self.coco_flip_pairs = ( (1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16) ) self.coco_joint_regressor = np.load(osp.join('..', 'data', 'MSCOCO', 'J_regressor_coco_hip_smpl.npy')) # smpl skeleton self.smpl = SMPL() self.face = self.smpl.face self.joint_regressor = self.smpl.joint_regressor self.vertex_num = self.smpl.vertex_num self.joint_num = self.smpl.joint_num self.joints_name = self.smpl.joints_name self.flip_pairs = self.smpl.flip_pairs self.skeleton = self.smpl.skeleton self.root_joint_idx = self.smpl.root_joint_idx self.face_kps_vertex = self.smpl.face_kps_vertex self.datalist = self.load_data() def add_pelvis(self, joint_coord): lhip_idx = self.coco_joints_name.index('L_Hip') rhip_idx = self.coco_joints_name.index('R_Hip') pelvis = (joint_coord[lhip_idx, :] + joint_coord[rhip_idx, :]) * 0.5 pelvis[2] = joint_coord[lhip_idx,2] * joint_coord[rhip_idx,2] # joint_valid pelvis = pelvis.reshape(1, 3) joint_coord = np.concatenate((joint_coord, pelvis)) return joint_coord def load_data(self): db = COCO(osp.join(self.annot_path, 'person_keypoints_' + self.data_split + '2017.json')) with open(osp.join(self.annot_path, 'coco_smplifyx_train.json')) as f: smplify_results = json.load(f) datalist = [] if self.data_split == 'train': for aid in db.anns.keys(): ann = db.anns[aid] img = db.loadImgs(ann['image_id'])[0] imgname = osp.join('train2017', img['file_name']) img_path = osp.join(self.img_path, imgname) width, height = img['width'], img['height'] if ann['iscrowd'] or (ann['num_keypoints'] == 0): continue # bbox bbox = process_bbox(ann['bbox'], width, height) if bbox is None: continue # joint coordinates joint_img = np.array(ann['keypoints'], dtype=np.float32).reshape(-1,3) joint_img = self.add_pelvis(joint_img) joint_valid = (joint_img[:,2].copy().reshape(-1,1) > 0).astype(np.float32) joint_img[:,2] = 0 if str(aid) in smplify_results: smplify_result = smplify_results[str(aid)] else: smplify_result = None datalist.append({ 'img_path': img_path, 'img_shape': (height, width), 'bbox': bbox, 'joint_img': joint_img, 'joint_valid': joint_valid, 'smplify_result': smplify_result }) else: with open(self.rootnet_output_path) as f: rootnet_output = json.load(f) print('Load RootNet output from ' + self.rootnet_output_path) for i in range(len(rootnet_output)): image_id = rootnet_output[i]['image_id'] if image_id not in db.imgs: continue img = db.loadImgs(image_id)[0] imgname = osp.join('val2017', img['file_name']) img_path = osp.join(self.img_path, imgname) height, width = img['height'], img['width'] fx, fy, cx, cy = 1500, 1500, img['width']/2, img['height']/2 focal = np.array([fx, fy], dtype=np.float32); princpt = np.array([cx, cy], dtype=np.float32); root_joint_depth = np.array(rootnet_output[i]['root_cam'][2]) bbox = np.array(rootnet_output[i]['bbox']).reshape(4) cam_param = {'focal': focal, 'princpt': princpt} datalist.append({ 'img_path': img_path, 'img_shape': (height, width), 'bbox': bbox, 'root_joint_depth': root_joint_depth, 'cam_param': cam_param }) return datalist def get_smpl_coord(self, smpl_param, cam_param, do_flip, img_shape): pose, shape, trans = smpl_param['pose'], smpl_param['shape'], smpl_param['trans'] smpl_pose = torch.FloatTensor(pose).view(1,-1); smpl_shape = torch.FloatTensor(shape).view(1,-1); # smpl parameters (pose: 72 dimension, shape: 10 dimension) smpl_trans = torch.FloatTensor(trans).view(1,-1) # translation vector # flip smpl pose parameter (axis-angle) if do_flip: smpl_pose = smpl_pose.view(-1,3) for pair in self.flip_pairs: if pair[0] < len(smpl_pose) and pair[1] < len(smpl_pose): # face keypoints are already included in self.flip_pairs. However, they are not included in smpl_pose. smpl_pose[pair[0], :], smpl_pose[pair[1], :] = smpl_pose[pair[1], :].clone(), smpl_pose[pair[0], :].clone() smpl_pose[:,1:3] *= -1; # multiply -1 to y and z axis of axis-angle smpl_pose = smpl_pose.view(1,-1) # get mesh and joint coordinates smpl_mesh_coord, smpl_joint_coord = self.smpl.layer['neutral'](smpl_pose, smpl_shape, smpl_trans) # incorporate face keypoints smpl_mesh_coord = smpl_mesh_coord.numpy().astype(np.float32).reshape(-1,3); smpl_joint_coord = smpl_joint_coord.numpy().astype(np.float32).reshape(-1,3) smpl_face_kps_coord = smpl_mesh_coord[self.face_kps_vertex,:].reshape(-1,3) smpl_joint_coord = np.concatenate((smpl_joint_coord, smpl_face_kps_coord)) # flip translation if do_flip: # avg of old and new root joint should be image center. focal, princpt = cam_param['focal'], cam_param['princpt'] flip_trans_x = 2 * (((img_shape[1] - 1)/2. - princpt[0]) / focal[0] * (smpl_joint_coord[self.root_joint_idx,2])) - 2 * smpl_joint_coord[self.root_joint_idx][0] smpl_mesh_coord[:,0] += flip_trans_x smpl_joint_coord[:,0] += flip_trans_x # change to mean shape if beta is too far from it smpl_shape[(smpl_shape.abs() > 3).any(dim=1)] = 0. return smpl_mesh_coord, smpl_joint_coord, smpl_pose[0].numpy(), smpl_shape[0].numpy() def get_fitting_error(self, coco_joint, smpl_mesh, cam_param, img2bb_trans, coco_joint_valid): # get coco joint from smpl mesh coco_from_smpl = np.dot(self.coco_joint_regressor, smpl_mesh) coco_from_smpl = self.add_pelvis(coco_from_smpl) # z-axis component will be removed coco_from_smpl = cam2pixel(coco_from_smpl, cam_param['focal'], cam_param['princpt']) coco_from_smpl_xy1 = np.concatenate((coco_from_smpl[:,:2], np.ones_like(coco_from_smpl[:,0:1])),1) coco_from_smpl[:,:2] = np.dot(img2bb_trans, coco_from_smpl_xy1.transpose(1,0)).transpose(1,0) coco_from_smpl[:,0] = coco_from_smpl[:,0] / cfg.input_img_shape[1] * cfg.output_hm_shape[2] coco_from_smpl[:,1] = coco_from_smpl[:,1] / cfg.input_img_shape[0] * cfg.output_hm_shape[1] # mask joint coordinates coco_joint = coco_joint[:,:2][np.tile(coco_joint_valid,(1,2))==1].reshape(-1,2) coco_from_smpl = coco_from_smpl[:,:2][np.tile(coco_joint_valid,(1,2))==1].reshape(-1,2) error = np.sqrt(np.sum((coco_joint - coco_from_smpl)**2,1)).mean() return error def __len__(self): return len(self.datalist) def __getitem__(self, idx): data = copy.deepcopy(self.datalist[idx]) img_path, img_shape, bbox = data['img_path'], data['img_shape'], data['bbox'] # image load and affine transform img = load_img(img_path) img, img2bb_trans, bb2img_trans, rot, do_flip = augmentation(img, bbox, self.data_split) img = self.transform(img.astype(np.float32))/255. if self.data_split == 'train': # coco gt coco_joint_img = data['joint_img'] coco_joint_valid = data['joint_valid'] if do_flip: coco_joint_img[:,0] = img_shape[1] - 1 - coco_joint_img[:,0] for pair in self.coco_flip_pairs: coco_joint_img[pair[0],:], coco_joint_img[pair[1],:] = coco_joint_img[pair[1],:].copy(), coco_joint_img[pair[0],:].copy() coco_joint_valid[pair[0],:], coco_joint_valid[pair[1],:] = coco_joint_valid[pair[1],:].copy(), coco_joint_valid[pair[0],:].copy() coco_joint_img_xy1 = np.concatenate((coco_joint_img[:,:2], np.ones_like(coco_joint_img[:,:1])),1) coco_joint_img[:,:2] = np.dot(img2bb_trans, coco_joint_img_xy1.transpose(1,0)).transpose(1,0) coco_joint_img[:,0] = coco_joint_img[:,0] / cfg.input_img_shape[1] * cfg.output_hm_shape[2] coco_joint_img[:,1] = coco_joint_img[:,1] / cfg.input_img_shape[0] * cfg.output_hm_shape[1] # backup for calculating fitting error _coco_joint_img = coco_joint_img.copy() _coco_joint_valid = coco_joint_valid.copy() # check truncation coco_joint_trunc = coco_joint_valid * ((coco_joint_img[:,0] >= 0) * (coco_joint_img[:,0] < cfg.output_hm_shape[2]) * \ (coco_joint_img[:,1] >= 0) * (coco_joint_img[:,1] < cfg.output_hm_shape[1])).reshape(-1,1).astype(np.float32) # transform coco joints to target db joints coco_joint_img = transform_joint_to_other_db(coco_joint_img, self.coco_joints_name, self.joints_name) coco_joint_cam = np.zeros((self.joint_num,3), dtype=np.float32) # dummy coco_joint_valid = transform_joint_to_other_db(coco_joint_valid, self.coco_joints_name, self.joints_name) coco_joint_trunc = transform_joint_to_other_db(coco_joint_trunc, self.coco_joints_name, self.joints_name) smplify_result = data['smplify_result'] if smplify_result is not None: # use fitted mesh smpl_param, cam_param = smplify_result['smpl_param'], smplify_result['cam_param'] smpl_mesh_cam, smpl_joint_cam, smpl_pose, smpl_shape = self.get_smpl_coord(smpl_param, cam_param, do_flip, img_shape) smpl_coord_cam = np.concatenate((smpl_mesh_cam, smpl_joint_cam)) smpl_coord_img = cam2pixel(smpl_coord_cam, cam_param['focal'], cam_param['princpt']) # x,y affine transform, root-relative depth smpl_coord_img_xy1 = np.concatenate((smpl_coord_img[:,:2], np.ones_like(smpl_coord_img[:,0:1])),1) smpl_coord_img[:,:2] = np.dot(img2bb_trans, smpl_coord_img_xy1.transpose(1,0)).transpose(1,0)[:,:2] smpl_coord_img[:,2] = smpl_coord_img[:,2] - smpl_coord_cam[self.vertex_num + self.root_joint_idx][2] smpl_coord_img[:,0] = smpl_coord_img[:,0] / cfg.input_img_shape[1] * cfg.output_hm_shape[2] smpl_coord_img[:,1] = smpl_coord_img[:,1] / cfg.input_img_shape[0] * cfg.output_hm_shape[1] smpl_coord_img[:,2] = (smpl_coord_img[:,2] / (cfg.bbox_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # check truncation smpl_trunc = ((smpl_coord_img[:,0] >= 0) * (smpl_coord_img[:,0] < cfg.output_hm_shape[2]) * \ (smpl_coord_img[:,1] >= 0) * (smpl_coord_img[:,1] < cfg.output_hm_shape[1]) * \ (smpl_coord_img[:,2] >= 0) * (smpl_coord_img[:,2] < cfg.output_hm_shape[0])).reshape(-1,1).astype(np.float32) # split mesh and joint coordinates smpl_mesh_img = smpl_coord_img[:self.vertex_num]; smpl_joint_img = smpl_coord_img[self.vertex_num:]; smpl_mesh_trunc = smpl_trunc[:self.vertex_num]; smpl_joint_trunc = smpl_trunc[self.vertex_num:]; # if fitted mesh is too far from h36m gt, discard it is_valid_fit = True error = self.get_fitting_error(_coco_joint_img, smpl_mesh_cam, cam_param, img2bb_trans, _coco_joint_valid) if error > self.fitting_thr: is_valid_fit = False else: smpl_joint_img = np.zeros((self.joint_num,3), dtype=np.float32) # dummy smpl_joint_cam = np.zeros((self.joint_num,3), dtype=np.float32) # dummy smpl_mesh_img = np.zeros((self.vertex_num,3), dtype=np.float32) # dummy smpl_pose = np.zeros((72), dtype=np.float32) # dummy smpl_shape = np.zeros((10), dtype=np.float32) # dummy smpl_joint_trunc = np.zeros((self.joint_num,1), dtype=np.float32) smpl_mesh_trunc = np.zeros((self.vertex_num,1), dtype=np.float32) is_valid_fit = False # 3D data rotation augmentation rot_aug_mat = np.array([[np.cos(np.deg2rad(-rot)), -np.sin(np.deg2rad(-rot)), 0], [np.sin(np.deg2rad(-rot)), np.cos(np.deg2rad(-rot)), 0], [0, 0, 1]], dtype=np.float32) # parameter smpl_pose = smpl_pose.reshape(-1,3) root_pose = smpl_pose[self.root_joint_idx,:] root_pose, _ = cv2.Rodrigues(root_pose) root_pose, _ = cv2.Rodrigues(np.dot(rot_aug_mat,root_pose)) smpl_pose[self.root_joint_idx] = root_pose.reshape(3) smpl_pose = smpl_pose.reshape(-1) # smpl coordinate smpl_joint_cam = smpl_joint_cam - smpl_joint_cam[self.root_joint_idx,None] # root-relative smpl_joint_cam = np.dot(rot_aug_mat, smpl_joint_cam.transpose(1,0)).transpose(1,0) inputs = {'img': img} targets = {'orig_joint_img': coco_joint_img, 'fit_joint_img': smpl_joint_img, 'fit_mesh_img': smpl_mesh_img, 'orig_joint_cam': coco_joint_cam, 'fit_joint_cam': smpl_joint_cam, 'pose_param': smpl_pose, 'shape_param': smpl_shape} meta_info = {'orig_joint_valid': coco_joint_valid, 'orig_joint_trunc': coco_joint_trunc, 'fit_joint_trunc': smpl_joint_trunc, 'fit_mesh_trunc': smpl_mesh_trunc, 'is_valid_fit': float(is_valid_fit), 'is_3D': float(False)} return inputs, targets, meta_info else: inputs = {'img': img} targets = {} meta_info = {'bb2img_trans': bb2img_trans} return inputs, targets, meta_info def evaluate(self, outs, cur_sample_idx): annots = self.datalist sample_num = len(outs) eval_result = {} for n in range(sample_num): annot = annots[cur_sample_idx + n] out = outs[n] # x,y: resize to input image space and perform bbox to image affine transform bb2img_trans = out['bb2img_trans'] mesh_out_img = out['mesh_coord_img'] mesh_out_img[:,0] = mesh_out_img[:,0] / cfg.output_hm_shape[2] * cfg.input_img_shape[1] mesh_out_img[:,1] = mesh_out_img[:,1] / cfg.output_hm_shape[1] * cfg.input_img_shape[0] mesh_out_img_xy1 = np.concatenate((mesh_out_img[:,:2], np.ones_like(mesh_out_img[:,:1])),1) mesh_out_img[:,:2] = np.dot(bb2img_trans, mesh_out_img_xy1.transpose(1,0)).transpose(1,0)[:,:2] # z: devoxelize and translate to absolute depth root_joint_depth = annot['root_joint_depth'] mesh_out_img[:,2] = (mesh_out_img[:,2] / cfg.output_hm_shape[0] * 2. - 1) * (cfg.bbox_3d_size * 1000 / 2) # change cfg.bbox_3d_size from meter to milimeter mesh_out_img[:,2] = mesh_out_img[:,2] + root_joint_depth # camera back-projection cam_param = annot['cam_param'] focal, princpt = cam_param['focal'], cam_param['princpt'] mesh_out_cam = pixel2cam(mesh_out_img, focal, princpt) if cfg.stage == 'param': mesh_out_cam = out['mesh_coord_cam'] vis = False if vis: filename = annot['img_path'].split('/')[-1][:-4] + '_' + str(n) img = load_img(annot['img_path'])[:,:,::-1] img = vis_mesh(img, mesh_out_img, 0.5) cv2.imwrite(filename + '.jpg', img) save_obj(mesh_out_cam, self.smpl.face, filename + '.obj') return eval_result def print_eval_result(self, eval_result): pass
[ "numpy.sum", "utils.transforms.cam2pixel", "numpy.tile", "os.path.join", "utils.transforms.transform_joint_to_other_db", "utils.vis.save_obj", "cv2.imwrite", "utils.preprocessing.process_bbox", "torch.FloatTensor", "utils.smpl.SMPL", "copy.deepcopy", "numpy.ones_like", "utils.preprocessing.load_img", "cv2.Rodrigues", "utils.preprocessing.augmentation", "numpy.dot", "numpy.concatenate", "utils.transforms.pixel2cam", "json.load", "numpy.deg2rad", "numpy.zeros", "utils.vis.vis_mesh", "numpy.array" ]
[((685, 727), 'os.path.join', 'osp.join', (['""".."""', '"""data"""', '"""MSCOCO"""', '"""images"""'], {}), "('..', 'data', 'MSCOCO', 'images')\n", (693, 727), True, 'import os.path as osp\n'), ((754, 801), 'os.path.join', 'osp.join', (['""".."""', '"""data"""', '"""MSCOCO"""', '"""annotations"""'], {}), "('..', 'data', 'MSCOCO', 'annotations')\n", (762, 801), True, 'import os.path as osp\n'), ((837, 922), 'os.path.join', 'osp.join', (['""".."""', '"""data"""', '"""MSCOCO"""', '"""rootnet_output"""', '"""bbox_root_coco_output.json"""'], {}), "('..', 'data', 'MSCOCO', 'rootnet_output', 'bbox_root_coco_output.json'\n )\n", (845, 922), True, 'import os.path as osp\n'), ((1727, 1733), 'utils.smpl.SMPL', 'SMPL', ([], {}), '()\n', (1731, 1733), False, 'from utils.smpl import SMPL\n'), ((2584, 2621), 'numpy.concatenate', 'np.concatenate', (['(joint_coord, pelvis)'], {}), '((joint_coord, pelvis))\n', (2598, 2621), True, 'import numpy as np\n'), ((7150, 7205), 'numpy.concatenate', 'np.concatenate', (['(smpl_joint_coord, smpl_face_kps_coord)'], {}), '((smpl_joint_coord, smpl_face_kps_coord))\n', (7164, 7205), True, 'import numpy as np\n'), ((8034, 8078), 'numpy.dot', 'np.dot', (['self.coco_joint_regressor', 'smpl_mesh'], {}), '(self.coco_joint_regressor, smpl_mesh)\n', (8040, 8078), True, 'import numpy as np\n'), ((8196, 8263), 'utils.transforms.cam2pixel', 'cam2pixel', (['coco_from_smpl', "cam_param['focal']", "cam_param['princpt']"], {}), "(coco_from_smpl, cam_param['focal'], cam_param['princpt'])\n", (8205, 8263), False, 'from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db\n'), ((9094, 9127), 'copy.deepcopy', 'copy.deepcopy', (['self.datalist[idx]'], {}), '(self.datalist[idx])\n', (9107, 9127), False, 'import copy\n'), ((9278, 9296), 'utils.preprocessing.load_img', 'load_img', (['img_path'], {}), '(img_path)\n', (9286, 9296), False, 'from utils.preprocessing import load_img, process_bbox, augmentation\n'), ((9353, 9393), 'utils.preprocessing.augmentation', 'augmentation', (['img', 'bbox', 'self.data_split'], {}), '(img, bbox, self.data_split)\n', (9365, 9393), False, 'from utils.preprocessing import load_img, process_bbox, augmentation\n'), ((1615, 1680), 'os.path.join', 'osp.join', (['""".."""', '"""data"""', '"""MSCOCO"""', '"""J_regressor_coco_hip_smpl.npy"""'], {}), "('..', 'data', 'MSCOCO', 'J_regressor_coco_hip_smpl.npy')\n", (1623, 1680), True, 'import os.path as osp\n'), ((2693, 2771), 'os.path.join', 'osp.join', (['self.annot_path', "('person_keypoints_' + self.data_split + '2017.json')"], {}), "(self.annot_path, 'person_keypoints_' + self.data_split + '2017.json')\n", (2701, 2771), True, 'import os.path as osp\n'), ((2882, 2894), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2891, 2894), False, 'import json\n'), ((11055, 11144), 'utils.transforms.transform_joint_to_other_db', 'transform_joint_to_other_db', (['coco_joint_img', 'self.coco_joints_name', 'self.joints_name'], {}), '(coco_joint_img, self.coco_joints_name, self.\n joints_name)\n', (11082, 11144), False, 'from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db\n'), ((11169, 11216), 'numpy.zeros', 'np.zeros', (['(self.joint_num, 3)'], {'dtype': 'np.float32'}), '((self.joint_num, 3), dtype=np.float32)\n', (11177, 11216), True, 'import numpy as np\n'), ((11255, 11346), 'utils.transforms.transform_joint_to_other_db', 'transform_joint_to_other_db', (['coco_joint_valid', 'self.coco_joints_name', 'self.joints_name'], {}), '(coco_joint_valid, self.coco_joints_name, self.\n joints_name)\n', (11282, 11346), False, 'from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db\n'), ((11373, 11464), 'utils.transforms.transform_joint_to_other_db', 'transform_joint_to_other_db', (['coco_joint_trunc', 'self.coco_joints_name', 'self.joints_name'], {}), '(coco_joint_trunc, self.coco_joints_name, self.\n joints_name)\n', (11400, 11464), False, 'from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db\n'), ((14853, 14877), 'cv2.Rodrigues', 'cv2.Rodrigues', (['root_pose'], {}), '(root_pose)\n', (14866, 14877), False, 'import cv2\n'), ((17406, 17445), 'utils.transforms.pixel2cam', 'pixel2cam', (['mesh_out_img', 'focal', 'princpt'], {}), '(mesh_out_img, focal, princpt)\n', (17415, 17445), False, 'from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db\n'), ((2791, 2844), 'os.path.join', 'osp.join', (['self.annot_path', '"""coco_smplifyx_train.json"""'], {}), "(self.annot_path, 'coco_smplifyx_train.json')\n", (2799, 2844), True, 'import os.path as osp\n'), ((3111, 3150), 'os.path.join', 'osp.join', (['"""train2017"""', "img['file_name']"], {}), "('train2017', img['file_name'])\n", (3119, 3150), True, 'import os.path as osp\n'), ((3178, 3210), 'os.path.join', 'osp.join', (['self.img_path', 'imgname'], {}), '(self.img_path, imgname)\n', (3186, 3210), True, 'import os.path as osp\n'), ((3446, 3486), 'utils.preprocessing.process_bbox', 'process_bbox', (["ann['bbox']", 'width', 'height'], {}), "(ann['bbox'], width, height)\n", (3458, 3486), False, 'from utils.preprocessing import load_img, process_bbox, augmentation\n'), ((4470, 4482), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4479, 4482), False, 'import json\n'), ((4810, 4847), 'os.path.join', 'osp.join', (['"""val2017"""', "img['file_name']"], {}), "('val2017', img['file_name'])\n", (4818, 4847), True, 'import os.path as osp\n'), ((4875, 4907), 'os.path.join', 'osp.join', (['self.img_path', 'imgname'], {}), '(self.img_path, imgname)\n', (4883, 4907), True, 'import os.path as osp\n'), ((5070, 5106), 'numpy.array', 'np.array', (['[fx, fy]'], {'dtype': 'np.float32'}), '([fx, fy], dtype=np.float32)\n', (5078, 5106), True, 'import numpy as np\n'), ((5118, 5154), 'numpy.array', 'np.array', (['[cx, cy]'], {'dtype': 'np.float32'}), '([cx, cy], dtype=np.float32)\n', (5126, 5154), True, 'import numpy as np\n'), ((5191, 5233), 'numpy.array', 'np.array', (["rootnet_output[i]['root_cam'][2]"], {}), "(rootnet_output[i]['root_cam'][2])\n", (5199, 5233), True, 'import numpy as np\n'), ((5859, 5882), 'torch.FloatTensor', 'torch.FloatTensor', (['pose'], {}), '(pose)\n', (5876, 5882), False, 'import torch\n'), ((5908, 5932), 'torch.FloatTensor', 'torch.FloatTensor', (['shape'], {}), '(shape)\n', (5925, 5932), False, 'import torch\n'), ((6026, 6050), 'torch.FloatTensor', 'torch.FloatTensor', (['trans'], {}), '(trans)\n', (6043, 6050), False, 'import torch\n'), ((8331, 8367), 'numpy.ones_like', 'np.ones_like', (['coco_from_smpl[:, 0:1]'], {}), '(coco_from_smpl[:, 0:1])\n', (8343, 8367), True, 'import numpy as np\n'), ((11867, 11914), 'numpy.concatenate', 'np.concatenate', (['(smpl_mesh_cam, smpl_joint_cam)'], {}), '((smpl_mesh_cam, smpl_joint_cam))\n', (11881, 11914), True, 'import numpy as np\n'), ((11948, 12015), 'utils.transforms.cam2pixel', 'cam2pixel', (['smpl_coord_cam', "cam_param['focal']", "cam_param['princpt']"], {}), "(smpl_coord_cam, cam_param['focal'], cam_param['princpt'])\n", (11957, 12015), False, 'from utils.transforms import world2cam, cam2pixel, pixel2cam, transform_joint_to_other_db\n'), ((13863, 13910), 'numpy.zeros', 'np.zeros', (['(self.joint_num, 3)'], {'dtype': 'np.float32'}), '((self.joint_num, 3), dtype=np.float32)\n', (13871, 13910), True, 'import numpy as np\n'), ((13951, 13998), 'numpy.zeros', 'np.zeros', (['(self.joint_num, 3)'], {'dtype': 'np.float32'}), '((self.joint_num, 3), dtype=np.float32)\n', (13959, 13998), True, 'import numpy as np\n'), ((14038, 14086), 'numpy.zeros', 'np.zeros', (['(self.vertex_num, 3)'], {'dtype': 'np.float32'}), '((self.vertex_num, 3), dtype=np.float32)\n', (14046, 14086), True, 'import numpy as np\n'), ((14122, 14152), 'numpy.zeros', 'np.zeros', (['(72)'], {'dtype': 'np.float32'}), '(72, dtype=np.float32)\n', (14130, 14152), True, 'import numpy as np\n'), ((14192, 14222), 'numpy.zeros', 'np.zeros', (['(10)'], {'dtype': 'np.float32'}), '(10, dtype=np.float32)\n', (14200, 14222), True, 'import numpy as np\n'), ((14268, 14315), 'numpy.zeros', 'np.zeros', (['(self.joint_num, 1)'], {'dtype': 'np.float32'}), '((self.joint_num, 1), dtype=np.float32)\n', (14276, 14315), True, 'import numpy as np\n'), ((14349, 14397), 'numpy.zeros', 'np.zeros', (['(self.vertex_num, 1)'], {'dtype': 'np.float32'}), '((self.vertex_num, 1), dtype=np.float32)\n', (14357, 14397), True, 'import numpy as np\n'), ((14919, 14949), 'numpy.dot', 'np.dot', (['rot_aug_mat', 'root_pose'], {}), '(rot_aug_mat, root_pose)\n', (14925, 14949), True, 'import numpy as np\n'), ((17745, 17777), 'utils.vis.vis_mesh', 'vis_mesh', (['img', 'mesh_out_img', '(0.5)'], {}), '(img, mesh_out_img, 0.5)\n', (17753, 17777), False, 'from utils.vis import vis_keypoints, vis_mesh, save_obj\n'), ((17794, 17829), 'cv2.imwrite', 'cv2.imwrite', (["(filename + '.jpg')", 'img'], {}), "(filename + '.jpg', img)\n", (17805, 17829), False, 'import cv2\n'), ((17847, 17904), 'utils.vis.save_obj', 'save_obj', (['mesh_out_cam', 'self.smpl.face', "(filename + '.obj')"], {}), "(mesh_out_cam, self.smpl.face, filename + '.obj')\n", (17855, 17904), False, 'from utils.vis import vis_keypoints, vis_mesh, save_obj\n'), ((8916, 8961), 'numpy.sum', 'np.sum', (['((coco_joint - coco_from_smpl) ** 2)', '(1)'], {}), '((coco_joint - coco_from_smpl) ** 2, 1)\n', (8922, 8961), True, 'import numpy as np\n'), ((10135, 10170), 'numpy.ones_like', 'np.ones_like', (['coco_joint_img[:, :1]'], {}), '(coco_joint_img[:, :1])\n', (10147, 10170), True, 'import numpy as np\n'), ((16728, 16761), 'numpy.ones_like', 'np.ones_like', (['mesh_out_img[:, :1]'], {}), '(mesh_out_img[:, :1])\n', (16740, 16761), True, 'import numpy as np\n'), ((17685, 17712), 'utils.preprocessing.load_img', 'load_img', (["annot['img_path']"], {}), "(annot['img_path'])\n", (17693, 17712), False, 'from utils.preprocessing import load_img, process_bbox, augmentation\n'), ((3611, 3655), 'numpy.array', 'np.array', (["ann['keypoints']"], {'dtype': 'np.float32'}), "(ann['keypoints'], dtype=np.float32)\n", (3619, 3655), True, 'import numpy as np\n'), ((5257, 5292), 'numpy.array', 'np.array', (["rootnet_output[i]['bbox']"], {}), "(rootnet_output[i]['bbox'])\n", (5265, 5292), True, 'import numpy as np\n'), ((8745, 8778), 'numpy.tile', 'np.tile', (['coco_joint_valid', '(1, 2)'], {}), '(coco_joint_valid, (1, 2))\n', (8752, 8778), True, 'import numpy as np\n'), ((8841, 8874), 'numpy.tile', 'np.tile', (['coco_joint_valid', '(1, 2)'], {}), '(coco_joint_valid, (1, 2))\n', (8848, 8874), True, 'import numpy as np\n'), ((12152, 12188), 'numpy.ones_like', 'np.ones_like', (['smpl_coord_img[:, 0:1]'], {}), '(smpl_coord_img[:, 0:1])\n', (12164, 12188), True, 'import numpy as np\n'), ((14535, 14551), 'numpy.deg2rad', 'np.deg2rad', (['(-rot)'], {}), '(-rot)\n', (14545, 14551), True, 'import numpy as np\n'), ((14606, 14622), 'numpy.deg2rad', 'np.deg2rad', (['(-rot)'], {}), '(-rot)\n', (14616, 14622), True, 'import numpy as np\n'), ((14632, 14648), 'numpy.deg2rad', 'np.deg2rad', (['(-rot)'], {}), '(-rot)\n', (14642, 14648), True, 'import numpy as np\n'), ((14562, 14578), 'numpy.deg2rad', 'np.deg2rad', (['(-rot)'], {}), '(-rot)\n', (14572, 14578), True, 'import numpy as np\n')]
import argparse import os import time import numpy as np import torch import torch.optim as optim import torch.nn as nn from torch.utils.data import DataLoader from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset from netArchitecture.VGG import VGGModel, VGGModel_2D from netArchitecture.ResNet import ResNet18_2D from visualize import Visualizations import logging logger = logging.getLogger("In train.py") logger.setLevel(logging.DEBUG) logger.disabled = True #parse parameters parser = argparse.ArgumentParser(description='train deep color extraction model') parser.add_argument('--mode', default=0, type=int) parser.add_argument('--backbone', default="vgg", type=str) parser.add_argument('--net_name', default="VGG+ASPP+2D", type=str) parser.add_argument('--trained_model_config', default="", type=str) # used for resuming to train network parser.add_argument('--cuda_device', default=3, type=int) parser.add_argument('--with_aspp', default=True, choices=('True','False')) parser.add_argument('--legend_width', default=256, type=int) parser.add_argument('--legend_height', default=10, type=int) parser.add_argument('--lr', default=1e-4, type=float) parser.add_argument('--train_bs',default=8, type=int) parser.add_argument('--num_epochs', default=15, type=int) parser.add_argument('--color_space', default="Lab", type=str) # possible value: "Lab", "Rgb" parser.add_argument('--is_label_normalized', default=True, choices=('True','False')) parser.add_argument('--loss_function', default="MSE", type=str) parser.add_argument('--prefix', default="", type=str) opt = parser.parse_args() IS_LABEL_NORMALIZED = opt.is_label_normalized == 'True' WITH_ASPP = opt.with_aspp == 'True' LEARNING_RATE = opt.lr BATCH_SIZE = opt.train_bs NUM_EPOCHS = opt.num_epochs NET_NAME = opt.net_name CUDA_DEVICE = opt.cuda_device MODE = opt.mode BACKBONE = opt.backbone COLOR_SPACE = opt.color_space TRAINED_MODEL_CONFIG = opt.trained_model_config TRAINED_EPOCH = 0 LOSS_FUNCTION = opt.loss_function PREFIX = opt.prefix # used in inference.py IS_NOT_DEBUG = True USE_VISDOM = True # if (MODE == 0): # lab 3D histogram IMAGE_WIDTH = 32 IMAGE_HEIGHT = 32 IMAGE_CHANNEL = 32 if (MODE == 1): # lab 2D histogram IMAGE_WIDTH = 128 IMAGE_HEIGHT = 128 IMAGE_CHANNEL = 1 elif (MODE == 2): # lab original images IMAGE_WIDTH = 256 IMAGE_HEIGHT = 128 IMAGE_CHANNEL = 3 LABEL_WIDTH = opt.legend_width LABEL_HEIGHT = opt.legend_height LABEL_CHANNEL = 3 config = "Net_{}__mode_{}__backbone_{}_colorspace_{}__labelnormalized_{}__lossfun_{}__woaspp_{}__lheight_{}__bs_{}__ep_{}__lr_{}".\ format(NET_NAME, MODE, BACKBONE, COLOR_SPACE, IS_LABEL_NORMALIZED, LOSS_FUNCTION, WITH_ASPP, LABEL_HEIGHT, BATCH_SIZE, NUM_EPOCHS, LEARNING_RATE ) \ if (TRAINED_MODEL_CONFIG == "") else TRAINED_MODEL_CONFIG # path for save and load netArchitecture model_dir = "models" if not os.path.exists(model_dir): os.makedirs(model_dir) model_path = os.path.join(model_dir, config) torch.cuda.set_device(CUDA_DEVICE) # define dataset # if MODE == 0: train_set = CSV_PNG_Dataset( label_paras ={'width':LABEL_WIDTH,'height':LABEL_HEIGHT,'channel':LABEL_CHANNEL}, image_paras={'width':IMAGE_WIDTH, 'height':IMAGE_HEIGHT, 'channel':IMAGE_CHANNEL}, is_label_normalized= IS_LABEL_NORMALIZED ) eval_set = CSV_PNG_Dataset( label_paras ={'width':LABEL_WIDTH,'height':LABEL_HEIGHT,'channel':LABEL_CHANNEL}, image_paras={'width':IMAGE_WIDTH, 'height':IMAGE_HEIGHT, 'channel':IMAGE_CHANNEL}, file_list="./dataset/evaluation.txt", is_label_normalized= IS_LABEL_NORMALIZED ) if MODE == 1: train_set = CSV_PNG_Dataset_2D( image_paras={'width':IMAGE_WIDTH,'height':IMAGE_HEIGHT,'channel':IMAGE_CHANNEL}, label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}, color_space=COLOR_SPACE, is_label_normalized=IS_LABEL_NORMALIZED) eval_set = CSV_PNG_Dataset_2D( file_list="./dataset/evaluation.txt", # here change to evaluation.txt image_paras={'width': IMAGE_WIDTH, 'height': IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}, label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}, color_space=COLOR_SPACE, is_label_normalized=IS_LABEL_NORMALIZED) elif MODE == 2: train_set = PNG_PNG_Dataset(label_paras ={'width':LABEL_WIDTH,'height':LABEL_HEIGHT,'channel':LABEL_CHANNEL}, color_space=COLOR_SPACE, is_label_normalized=IS_LABEL_NORMALIZED) eval_set = PNG_PNG_Dataset(label_paras ={'width':LABEL_WIDTH,'height':LABEL_HEIGHT,'channel':LABEL_CHANNEL},file_list="./dataset/evaluation.txt", color_space=COLOR_SPACE, is_label_normalized=IS_LABEL_NORMALIZED) train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=IS_NOT_DEBUG, num_workers=2, drop_last=True) eval_loader = DataLoader(eval_set, batch_size=1, shuffle=False) # define net, criterion and optimizer net = VGGModel(input_channel=IMAGE_CHANNEL, label_height=LABEL_HEIGHT, label_width=LABEL_WIDTH) if MODE == 2 or MODE == 1: if BACKBONE == "vgg": net = VGGModel_2D(input_channel=IMAGE_CHANNEL, label_height=LABEL_HEIGHT, label_width=LABEL_WIDTH, with_aspp=WITH_ASPP) elif BACKBONE == "resnet18": print("resnet18") net = ResNet18_2D(input_channel=IMAGE_CHANNEL, label_height=LABEL_HEIGHT, label_width=LABEL_WIDTH, with_aspp=WITH_ASPP) test_loss_for_each_epoch = [] # used for recording avg mean of each epoch in testing phrase loss_for_each_epoch = [] # used for recording avg mean of each epoch in training phrase time_used_cumulation = [] if TRAINED_MODEL_CONFIG != "": checkpoint = torch.load(model_path) net.load_state_dict(checkpoint['model_state_dict']) TRAINED_EPOCH = checkpoint['epoch'] + 1 time_used_cumulation = checkpoint['time_used'] loss_for_each_epoch = checkpoint['loss_for_each_epoch'] print('#netArchitecture parameters:', sum(param.numel() for param in net.parameters())) if torch.cuda.is_available(): if logger.isEnabledFor(logging.DEBUG): logger.debug(torch.cuda.current_device()) ts = time.time() net.cuda() print("finished loading netArchitecture params to cuda, time elapsed: {}".format(time.time() - ts)) optimizer = optim.Adam(net.parameters(), lr=LEARNING_RATE) vis = Visualizations(env=config) if LOSS_FUNCTION == "MSE": criterian = nn.MSELoss() elif LOSS_FUNCTION == "BCE": criterian = nn.BCELoss() sigmoid = torch.nn.Sigmoid() def train(): if len(time_used_cumulation) == 0: time_used = 0.0 else: time_used = time_used_cumulation[-1] iter_100_loss_values = [] for epoch in range(NUM_EPOCHS - TRAINED_EPOCH): tm_start_each_epoch = time.time() true_epoch = epoch + TRAINED_EPOCH net.train() loss_values = [] # used for visdom to visualize epoch_loss_value_in_one_epoch = [] # used for recording all loss values in an epoch and computing the mean of them for iter, batch in enumerate(train_loader): torch.autograd.set_detect_anomaly(True) images, labels = batch['image'], batch['label'] if torch.cuda.is_available(): images = images.cuda() labels = labels.cuda() preds = net(images) if IS_LABEL_NORMALIZED: preds = sigmoid(preds) if LOSS_FUNCTION == "MSE": loss = criterian(labels, preds) elif LOSS_FUNCTION == "BCE": loss = criterian(preds, labels.detach()) loss_values.append(loss.item()) epoch_loss_value_in_one_epoch.append(loss.item()) optimizer.zero_grad() with torch.autograd.detect_anomaly(): loss.backward() optimizer.step() if iter % 10 == 0: print("epoch{}, iter{}, loss: {}".format(true_epoch, iter, loss.item())) niter = true_epoch * len(train_loader) + iter if niter % 100 == 0: iter_100_loss_values.append(np.mean(loss_values)) if USE_VISDOM: vis.plot_loss(np.mean(loss_values), niter) vis.plot_ground_truth(labels, COLOR_SPACE, caption="groud_truth_in epoch{}, iter{}".format(true_epoch, iter)) vis.plot_test_pred(preds, COLOR_SPACE, caption="pred_in epoch{}, iter{}".format(true_epoch, iter)) if MODE == 2: vis.plot_ground_truth(images,COLOR_SPACE, win="original images", caption="image in epoch{}, iter{}".format(true_epoch, iter)) loss_values.clear() vis.save() time_used = time_used + time.time() - tm_start_each_epoch time_used_cumulation.append(time_used) loss_for_each_epoch.append(np.mean(epoch_loss_value_in_one_epoch)) epoch_loss_value_in_one_epoch.clear() torch.save({ 'epoch': true_epoch, 'model_state_dict': net.state_dict(), 'time_used': time_used_cumulation, 'loss_for_each_epoch':loss_for_each_epoch }, model_path) def eval(epoch): net.eval() loss_value_in_epoch = [] for iter, batch in enumerate(eval_loader): images, labels = batch['image'], batch['label'] if torch.cuda.is_available(): images = images.cuda() labels = labels.cuda() preds = net(images) if IS_LABEL_NORMALIZED: preds = sigmoid(preds) if LOSS_FUNCTION == "MSE": loss = criterian(labels, preds) elif LOSS_FUNCTION == "BCE": loss = criterian(preds, labels.detach()) loss_value_in_epoch.append(loss.item()) if USE_VISDOM: vis.plot_ground_truth(labels, COLOR_SPACE, win="evaluate_ground_truth") vis.plot_test_pred(preds, COLOR_SPACE, win="evaluate_test_pred") test_loss_for_each_epoch.append(np.mean(loss_value_in_epoch)) if __name__=="__main__": eval(0) train()
[ "argparse.ArgumentParser", "netArchitecture.VGG.VGGModel", "numpy.mean", "torch.autograd.set_detect_anomaly", "torch.cuda.current_device", "os.path.join", "data_loader.CSV_PNG_Dataset", "visualize.Visualizations", "torch.nn.MSELoss", "torch.nn.BCELoss", "torch.utils.data.DataLoader", "netArchitecture.ResNet.ResNet18_2D", "torch.load", "torch.autograd.detect_anomaly", "os.path.exists", "torch.cuda.set_device", "data_loader.CSV_PNG_Dataset_2D", "data_loader.PNG_PNG_Dataset", "torch.cuda.is_available", "torch.nn.Sigmoid", "os.makedirs", "netArchitecture.VGG.VGGModel_2D", "time.time", "logging.getLogger" ]
[((404, 436), 'logging.getLogger', 'logging.getLogger', (['"""In train.py"""'], {}), "('In train.py')\n", (421, 436), False, 'import logging\n'), ((519, 591), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""train deep color extraction model"""'}), "(description='train deep color extraction model')\n", (542, 591), False, 'import argparse\n'), ((2977, 3008), 'os.path.join', 'os.path.join', (['model_dir', 'config'], {}), '(model_dir, config)\n', (2989, 3008), False, 'import os\n'), ((3010, 3044), 'torch.cuda.set_device', 'torch.cuda.set_device', (['CUDA_DEVICE'], {}), '(CUDA_DEVICE)\n', (3031, 3044), False, 'import torch\n'), ((3092, 3333), 'data_loader.CSV_PNG_Dataset', 'CSV_PNG_Dataset', ([], {'label_paras': "{'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}", 'image_paras': "{'width': IMAGE_WIDTH, 'height': IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}", 'is_label_normalized': 'IS_LABEL_NORMALIZED'}), "(label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT,\n 'channel': LABEL_CHANNEL}, image_paras={'width': IMAGE_WIDTH, 'height':\n IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}, is_label_normalized=\n IS_LABEL_NORMALIZED)\n", (3107, 3333), False, 'from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset\n'), ((3344, 3623), 'data_loader.CSV_PNG_Dataset', 'CSV_PNG_Dataset', ([], {'label_paras': "{'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}", 'image_paras': "{'width': IMAGE_WIDTH, 'height': IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}", 'file_list': '"""./dataset/evaluation.txt"""', 'is_label_normalized': 'IS_LABEL_NORMALIZED'}), "(label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT,\n 'channel': LABEL_CHANNEL}, image_paras={'width': IMAGE_WIDTH, 'height':\n IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}, file_list=\n './dataset/evaluation.txt', is_label_normalized=IS_LABEL_NORMALIZED)\n", (3359, 3623), False, 'from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset\n'), ((4819, 4920), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': 'IS_NOT_DEBUG', 'num_workers': '(2)', 'drop_last': '(True)'}), '(train_set, batch_size=BATCH_SIZE, shuffle=IS_NOT_DEBUG,\n num_workers=2, drop_last=True)\n', (4829, 4920), False, 'from torch.utils.data import DataLoader\n'), ((4931, 4980), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_set'], {'batch_size': '(1)', 'shuffle': '(False)'}), '(eval_set, batch_size=1, shuffle=False)\n', (4941, 4980), False, 'from torch.utils.data import DataLoader\n'), ((5026, 5119), 'netArchitecture.VGG.VGGModel', 'VGGModel', ([], {'input_channel': 'IMAGE_CHANNEL', 'label_height': 'LABEL_HEIGHT', 'label_width': 'LABEL_WIDTH'}), '(input_channel=IMAGE_CHANNEL, label_height=LABEL_HEIGHT,\n label_width=LABEL_WIDTH)\n', (5034, 5119), False, 'from netArchitecture.VGG import VGGModel, VGGModel_2D\n'), ((6067, 6092), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6090, 6092), False, 'import torch\n'), ((6395, 6421), 'visualize.Visualizations', 'Visualizations', ([], {'env': 'config'}), '(env=config)\n', (6409, 6421), False, 'from visualize import Visualizations\n'), ((6548, 6566), 'torch.nn.Sigmoid', 'torch.nn.Sigmoid', ([], {}), '()\n', (6564, 6566), False, 'import torch\n'), ((2910, 2935), 'os.path.exists', 'os.path.exists', (['model_dir'], {}), '(model_dir)\n', (2924, 2935), False, 'import os\n'), ((2941, 2963), 'os.makedirs', 'os.makedirs', (['model_dir'], {}), '(model_dir)\n', (2952, 2963), False, 'import os\n'), ((3658, 3926), 'data_loader.CSV_PNG_Dataset_2D', 'CSV_PNG_Dataset_2D', ([], {'image_paras': "{'width': IMAGE_WIDTH, 'height': IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}", 'label_paras': "{'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}", 'color_space': 'COLOR_SPACE', 'is_label_normalized': 'IS_LABEL_NORMALIZED'}), "(image_paras={'width': IMAGE_WIDTH, 'height':\n IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}, label_paras={'width':\n LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL},\n color_space=COLOR_SPACE, is_label_normalized=IS_LABEL_NORMALIZED)\n", (3676, 3926), False, 'from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset\n'), ((3958, 4270), 'data_loader.CSV_PNG_Dataset_2D', 'CSV_PNG_Dataset_2D', ([], {'file_list': '"""./dataset/evaluation.txt"""', 'image_paras': "{'width': IMAGE_WIDTH, 'height': IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL}", 'label_paras': "{'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}", 'color_space': 'COLOR_SPACE', 'is_label_normalized': 'IS_LABEL_NORMALIZED'}), "(file_list='./dataset/evaluation.txt', image_paras={\n 'width': IMAGE_WIDTH, 'height': IMAGE_HEIGHT, 'channel': IMAGE_CHANNEL},\n label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel':\n LABEL_CHANNEL}, color_space=COLOR_SPACE, is_label_normalized=\n IS_LABEL_NORMALIZED)\n", (3976, 4270), False, 'from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset\n'), ((5740, 5762), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (5750, 5762), False, 'import torch\n'), ((6197, 6208), 'time.time', 'time.time', ([], {}), '()\n', (6206, 6208), False, 'import time\n'), ((6466, 6478), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (6476, 6478), True, 'import torch.nn as nn\n'), ((4360, 4536), 'data_loader.PNG_PNG_Dataset', 'PNG_PNG_Dataset', ([], {'label_paras': "{'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}", 'color_space': 'COLOR_SPACE', 'is_label_normalized': 'IS_LABEL_NORMALIZED'}), "(label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT,\n 'channel': LABEL_CHANNEL}, color_space=COLOR_SPACE, is_label_normalized\n =IS_LABEL_NORMALIZED)\n", (4375, 4536), False, 'from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset\n'), ((4571, 4784), 'data_loader.PNG_PNG_Dataset', 'PNG_PNG_Dataset', ([], {'label_paras': "{'width': LABEL_WIDTH, 'height': LABEL_HEIGHT, 'channel': LABEL_CHANNEL}", 'file_list': '"""./dataset/evaluation.txt"""', 'color_space': 'COLOR_SPACE', 'is_label_normalized': 'IS_LABEL_NORMALIZED'}), "(label_paras={'width': LABEL_WIDTH, 'height': LABEL_HEIGHT,\n 'channel': LABEL_CHANNEL}, file_list='./dataset/evaluation.txt',\n color_space=COLOR_SPACE, is_label_normalized=IS_LABEL_NORMALIZED)\n", (4586, 4784), False, 'from data_loader import CSV_PNG_Dataset, CSV_PNG_Dataset_2D, PNG_PNG_Dataset\n'), ((5183, 5300), 'netArchitecture.VGG.VGGModel_2D', 'VGGModel_2D', ([], {'input_channel': 'IMAGE_CHANNEL', 'label_height': 'LABEL_HEIGHT', 'label_width': 'LABEL_WIDTH', 'with_aspp': 'WITH_ASPP'}), '(input_channel=IMAGE_CHANNEL, label_height=LABEL_HEIGHT,\n label_width=LABEL_WIDTH, with_aspp=WITH_ASPP)\n', (5194, 5300), False, 'from netArchitecture.VGG import VGGModel, VGGModel_2D\n'), ((6524, 6536), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6534, 6536), True, 'import torch.nn as nn\n'), ((6812, 6823), 'time.time', 'time.time', ([], {}), '()\n', (6821, 6823), False, 'import time\n'), ((9424, 9449), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9447, 9449), False, 'import torch\n'), ((10054, 10082), 'numpy.mean', 'np.mean', (['loss_value_in_epoch'], {}), '(loss_value_in_epoch)\n', (10061, 10082), True, 'import numpy as np\n'), ((5370, 5487), 'netArchitecture.ResNet.ResNet18_2D', 'ResNet18_2D', ([], {'input_channel': 'IMAGE_CHANNEL', 'label_height': 'LABEL_HEIGHT', 'label_width': 'LABEL_WIDTH', 'with_aspp': 'WITH_ASPP'}), '(input_channel=IMAGE_CHANNEL, label_height=LABEL_HEIGHT,\n label_width=LABEL_WIDTH, with_aspp=WITH_ASPP)\n', (5381, 5487), False, 'from netArchitecture.ResNet import ResNet18_2D\n'), ((6158, 6185), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (6183, 6185), False, 'import torch\n'), ((7133, 7172), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (7166, 7172), False, 'import torch\n'), ((7250, 7275), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7273, 7275), False, 'import torch\n'), ((8933, 8971), 'numpy.mean', 'np.mean', (['epoch_loss_value_in_one_epoch'], {}), '(epoch_loss_value_in_one_epoch)\n', (8940, 8971), True, 'import numpy as np\n'), ((6309, 6320), 'time.time', 'time.time', ([], {}), '()\n', (6318, 6320), False, 'import time\n'), ((7810, 7841), 'torch.autograd.detect_anomaly', 'torch.autograd.detect_anomaly', ([], {}), '()\n', (7839, 7841), False, 'import torch\n'), ((8817, 8828), 'time.time', 'time.time', ([], {}), '()\n', (8826, 8828), False, 'import time\n'), ((8172, 8192), 'numpy.mean', 'np.mean', (['loss_values'], {}), '(loss_values)\n', (8179, 8192), True, 'import numpy as np\n'), ((8259, 8279), 'numpy.mean', 'np.mean', (['loss_values'], {}), '(loss_values)\n', (8266, 8279), True, 'import numpy as np\n')]
import getpass if getpass.getuser()=='RGCGroup': import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"] = "-1" #Run with CPU only import pandas as pd import numpy as np from keras.layers import Dense,BatchNormalization,Dropout from keras.models import Sequential from keras.utils import plot_model from sklearn.ensemble import RandomForestRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error,mean_absolute_error import matplotlib.pyplot as plt from xgboost import XGBRegressor import time import os from helper import find_csv,find_sigma import csv linewidth = 3 fontsize = 14 figsize = [10,8] font = {'family' : 'monospace', 'weight' : 'bold', 'size' : fontsize } plt.rc('font', **font) # pass in the font dict as kwargs import random random.seed(1) import tensorflow as tf tf.random.set_seed(1) np.random.seed(1) def read_feature(file_name = 'Analysis.csv'): data = pd.read_csv(file_name) data = data.fillna(0.0) features = data[['Log10scanRate','Log10keq','Log10kf']] targets = data[['peak flux','half peak potential']] return features,targets def create_model(data=None,output_shape=0,optimizer='Adam',loss='mean_absolute_error'): model = Sequential() model.add(Dense(256,input_dim =data.shape[1] ,activation='relu')) model.add(Dense(128,activation='relu')) model.add(Dense(64,activation='relu')) model.add(Dense(output_shape,activation='linear')) model.compile(optimizer=optimizer,loss=loss,metrics=['mean_squared_error','mean_absolute_error']) return model """def create_model(data=None,optimizer='Adam',loss='mean_absolute_error'): model = Sequential() model.add(Dense(32,input_dim =data.shape[1] ,activation='relu')) model.add(BatchNormalization()) model.add(Dense(16,activation='relu')) model.add(BatchNormalization()) #model.add(Dense(16,activation='relu')) model.add(Dense(1,activation='linear')) model.compile(optimizer=optimizer,loss=loss,metrics=['mean_squared_error','mean_absolute_error']) return model""" def extract(df,sigma): df_forward = df[:int(len(df)/2)] forward_peak = df_forward[0].iloc[df_forward[1].idxmin()] #Forward peak potential df_backward = df[int(len(df)/2):] df_backward = df_backward.reset_index(drop=True) #Use drop to discard the old index backward_peak = df_backward[0].iloc[df_backward[1].idxmax()] #Backward Peak Potential #Randles-Sevcik Prediction forward_flux = df_forward[1].min() backward_flux = df_backward[1].max() #Find the half peak potential half_peak_potential_index = (df_forward[1]-forward_flux/2.0).abs().argsort()[0] half_peak_potential = df_forward[0].iloc[half_peak_potential_index] return[forward_flux,half_peak_potential] """ #fig = plt.figure() df.plot(x='Theta',y='Flux',label='Cyclic Voltammogram') plt.scatter(range1,points1,label='Forward Scan Features') plt.scatter(range3,points3,label='Reverse Scan Features') plt.legend(loc=0) plt.show() time.sleep(1) #plt.close(fig)""" if __name__ == "__main__": start = time.perf_counter() features,targets = read_feature() data_train,data_test,target_train,target_test = train_test_split(features,targets,test_size=0.2) """ print(data.dtypes) print(target.head()) print(data.head()) """ #Fit with NN model = create_model(data=data_train,output_shape=targets.shape[1]) plot_model(model,to_file='Predict Flux and Half Peak Potential.png',show_shapes=True,show_layer_names=True,dpi=400) epochs=20000 if not os.path.exists('./weights/Predict Flux and half peak potential.h5'): model.fit(data_train,target_train,epochs=epochs,batch_size=32,validation_split=0.2,verbose=1) model.save_weights('./weights/Predict Flux and half peak potential.h5') else: model.load_weights('./weights/Predict Flux and half peak potential.h5') pred = model.predict(data_test) print(pred[0]) print('predicted value',pred,'actual value',target_test) #Fit with RandomForest RFregressor = RandomForestRegressor() RFregressor.fit(data_train,target_train) RFPredicted = RFregressor.predict(data_test) #Fit with LinearRegression regressor = LinearRegression() regressor.fit(data_train,target_train) LRPredicted = regressor.predict(data_test) """ #Fit with XGBRegressor xgbregreesor = XGBRegressor() xgbregreesor.fit(data_train,target_train.iloc[:,0]) XGBpredicted = xgbregreesor.predict(data_test)""" NNerror = mean_squared_error(target_test,pred) RFerror = mean_squared_error(target_test,RFPredicted) LRerror = mean_squared_error(target_test,LRPredicted) NNABSerror = mean_absolute_error(target_test,pred) RFABSerror = mean_absolute_error(target_test,RFPredicted) LRABSerror = mean_absolute_error(target_test,LRPredicted) #XGBerror = mean_squared_error(target_test,XGBpredicted) #XGBABSerror = mean_absolute_error(target_test,XGBpredicted) print('NN Error',NNerror,NNABSerror) print('Random Forest Error',RFerror,RFABSerror) print('Linear Regression error',LRerror,LRABSerror) #print('XGB Predicted error',XGBerror,XGBABSerror) fig = plt.figure(figsize=(16,9)) ax1 = fig.add_subplot(2,2,1) plt.scatter(pred.reshape(-1),target_test) x = np.linspace(-15,10,100) plt.title(f'Neural Network, Train {epochs} times') plt.plot(x,x,'-r') plt.xlabel('Predicted value') plt.ylabel('Actual Value') ax2 = fig.add_subplot(2,2,2) plt.scatter(RFPredicted.reshape(-1),target_test) x = np.linspace(-15,10,100) plt.title('Random Forest Prediction') plt.plot(x,x,'-r') plt.xlabel('Predicted value') plt.ylabel('Actual Value') ax3 = fig.add_subplot(2,2,3) plt.scatter(LRPredicted.reshape(-1),target_test) x = np.linspace(-15,10,100) plt.title('Linear Prediction') plt.plot(x,x,'-r') plt.xlabel('Predicted value') plt.ylabel('Actual Value') """ ax4 = fig.add_subplot(2,2,4) plt.scatter(XGBpredicted.reshape(-1),target_test) x = np.linspace(-15,10,100) plt.title('XGBoost Prediction') plt.plot(x,x,'-r') plt.xlabel('Predicted value') plt.ylabel('Actual Value') print('time consuming:',time.perf_counter()-start) """ fig.savefig('Four Model Results') plt.show() print() #visualization of one test sample path_to_dir = './Test Data' Test_CVs=find_csv(path_to_dir=path_to_dir) with open('test_summary.csv',newline='',mode='w') as writer: csvwriter = csv.writer(writer) csvwriter.writerow(['log10scanRate','log10keq','log10kf','Flux','Predicted Flux','Half Peak Potential','Predicted Half Peak Potential','Predicted Flux Error','Predicted Half Peak Potential Error']) fig_flux_all,ax_flux_all = plt.subplots(figsize=(16,9)) fig_potential_all,ax_potential_all = plt.subplots(figsize=(16,9)) for index, test_cv in enumerate(Test_CVs): print(f'Testing {index} of {len(Test_CVs)-1} ') sigma,keq,kf = find_sigma(test_cv) filename = test_cv.replace('.csv','') #if kf/keq > 1e9: # continue df = pd.read_csv(f'{path_to_dir}/{test_cv}',header=None) #if df[1].min()>-0.01: # continue #df.iloc[:,1] = df.iloc[:,1] + 0.001*np.random.randn(df.shape[0]) + df.iloc[:,1]*1e-3*np.random.randn(df.shape[0]) range_all = extract(df.copy(),sigma) fig = plt.figure(figsize=(16,18)) ax = plt.subplot(2,1,1) test_feature = np.array([[sigma,keq,kf]]) test_feature = np.log10(test_feature) target = model.predict(test_feature) print(target.shape) error = np.average((target[0]-range_all)/range_all) csvwriter.writerow([np.log10(sigma),np.log10(keq),np.log10(kf),range_all[0],target[0,0],range_all[1],target[0,1],((target[0]-range_all))[0],((target[0]-range_all))[1]]) #csvwriter.writerow([sigma,np.log10(keq),np.log10(kf),error,list(range_all)]) #csvwriter.writerow([sigma,np.log10(keq),np.log10(kf),error,list(target[0])]) plt.plot(np.arange(-10,10),np.arange(-10,10)) plt.scatter(target[0,0],range_all[0],label='Peak Flux',color='r') plt.scatter(target[0,1],range_all[1],label='Half Peak Potential',color='b') plt.title('Test Results: Neural Network',fontsize='large') ax.legend(loc=0,fontsize='large') ax.tick_params(labelsize='large') ax.set_xlabel(r"Predicted Values", fontweight = "bold",fontsize='large') ax.set_ylabel(r"True Values", fontweight = "bold",fontsize='large') #plt.show() ax = plt.subplot(2,1,2) RFtarget = RFregressor.predict(test_feature) plt.plot(np.arange(-10,10),np.arange(-10,10)) plt.scatter(RFtarget[0,0],range_all[0],label='Peak Flux',color='r') plt.scatter(RFtarget[0,1],range_all[1],label='Half Peak Potential',color='b') plt.title('Test Results: Random Forest',fontsize='large') ax.legend(loc=0,fontsize='large') ax.tick_params(labelsize='large') ax.set_xlabel(r"Predicted Values", fontweight = "bold",fontsize='large') ax.set_ylabel(r"True Values", fontweight = "bold",fontsize='large') fig.savefig(f'{path_to_dir}/{filename} Prediction.png') plt.close() #plt.show() ax_flux_all.scatter(target[0,0],range_all[0],label='Peak Flux',color='r') ax_potential_all.scatter(target[0,1],range_all[1],label='Half Peak Potential',color='b') ax_flux_all.plot(np.arange(-1.0,1.0),np.arange(-1.0,1.0)) ax_flux_all.set_xlabel('Predicted Values') ax_flux_all.set_ylabel('True Values') ax_potential_all.plot(np.arange(-10.0,10.0),np.arange(-10.0,10.0)) ax_potential_all.set_xlabel('Predicted Values') ax_potential_all.set_ylabel('True Values') fig_flux_all.savefig(f'{path_to_dir}/Flux All.png',dpi=400) fig_potential_all.savefig(f'{path_to_dir}/Potential All.png',dpi=400) writer.close() #Visualization of one test sample # = find_csv()
[ "tensorflow.random.set_seed", "matplotlib.pyplot.title", "numpy.random.seed", "getpass.getuser", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.metrics.mean_absolute_error", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.close", "os.path.exists", "helper.find_sigma", "keras.utils.plot_model", "random.seed", "matplotlib.pyplot.rc", "numpy.linspace", "numpy.log10", "matplotlib.pyplot.subplots", "sklearn.metrics.mean_squared_error", "helper.find_csv", "matplotlib.pyplot.show", "csv.writer", "numpy.average", "time.perf_counter", "sklearn.ensemble.RandomForestRegressor", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.subplot", "matplotlib.pyplot.plot", "matplotlib.pyplot.scatter", "keras.layers.Dense", "numpy.array", "keras.models.Sequential", "matplotlib.pyplot.xlabel" ]
[((945, 967), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **font)\n", (951, 967), True, 'import matplotlib.pyplot as plt\n'), ((1019, 1033), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (1030, 1033), False, 'import random\n'), ((1058, 1079), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(1)'], {}), '(1)\n', (1076, 1079), True, 'import tensorflow as tf\n'), ((1080, 1097), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (1094, 1097), True, 'import numpy as np\n'), ((18, 35), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (33, 35), False, 'import getpass\n'), ((1158, 1180), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {}), '(file_name)\n', (1169, 1180), True, 'import pandas as pd\n'), ((1464, 1476), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1474, 1476), False, 'from keras.models import Sequential\n'), ((3369, 3388), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3386, 3388), False, 'import time\n'), ((3480, 3530), 'sklearn.model_selection.train_test_split', 'train_test_split', (['features', 'targets'], {'test_size': '(0.2)'}), '(features, targets, test_size=0.2)\n', (3496, 3530), False, 'from sklearn.model_selection import train_test_split\n'), ((3717, 3840), 'keras.utils.plot_model', 'plot_model', (['model'], {'to_file': '"""Predict Flux and Half Peak Potential.png"""', 'show_shapes': '(True)', 'show_layer_names': '(True)', 'dpi': '(400)'}), "(model, to_file='Predict Flux and Half Peak Potential.png',\n show_shapes=True, show_layer_names=True, dpi=400)\n", (3727, 3840), False, 'from keras.utils import plot_model\n'), ((4365, 4388), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {}), '()\n', (4386, 4388), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((4531, 4549), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (4547, 4549), False, 'from sklearn.linear_model import LinearRegression\n'), ((4845, 4882), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['target_test', 'pred'], {}), '(target_test, pred)\n', (4863, 4882), False, 'from sklearn.metrics import mean_squared_error, mean_absolute_error\n'), ((4896, 4940), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['target_test', 'RFPredicted'], {}), '(target_test, RFPredicted)\n', (4914, 4940), False, 'from sklearn.metrics import mean_squared_error, mean_absolute_error\n'), ((4954, 4998), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['target_test', 'LRPredicted'], {}), '(target_test, LRPredicted)\n', (4972, 4998), False, 'from sklearn.metrics import mean_squared_error, mean_absolute_error\n'), ((5015, 5053), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['target_test', 'pred'], {}), '(target_test, pred)\n', (5034, 5053), False, 'from sklearn.metrics import mean_squared_error, mean_absolute_error\n'), ((5070, 5115), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['target_test', 'RFPredicted'], {}), '(target_test, RFPredicted)\n', (5089, 5115), False, 'from sklearn.metrics import mean_squared_error, mean_absolute_error\n'), ((5132, 5177), 'sklearn.metrics.mean_absolute_error', 'mean_absolute_error', (['target_test', 'LRPredicted'], {}), '(target_test, LRPredicted)\n', (5151, 5177), False, 'from sklearn.metrics import mean_squared_error, mean_absolute_error\n'), ((5525, 5552), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (5535, 5552), True, 'import matplotlib.pyplot as plt\n'), ((5639, 5664), 'numpy.linspace', 'np.linspace', (['(-15)', '(10)', '(100)'], {}), '(-15, 10, 100)\n', (5650, 5664), True, 'import numpy as np\n'), ((5667, 5717), 'matplotlib.pyplot.title', 'plt.title', (['f"""Neural Network, Train {epochs} times"""'], {}), "(f'Neural Network, Train {epochs} times')\n", (5676, 5717), True, 'import matplotlib.pyplot as plt\n'), ((5722, 5742), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'x', '"""-r"""'], {}), "(x, x, '-r')\n", (5730, 5742), True, 'import matplotlib.pyplot as plt\n'), ((5745, 5774), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted value"""'], {}), "('Predicted value')\n", (5755, 5774), True, 'import matplotlib.pyplot as plt\n'), ((5779, 5805), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Actual Value"""'], {}), "('Actual Value')\n", (5789, 5805), True, 'import matplotlib.pyplot as plt\n'), ((5905, 5930), 'numpy.linspace', 'np.linspace', (['(-15)', '(10)', '(100)'], {}), '(-15, 10, 100)\n', (5916, 5930), True, 'import numpy as np\n'), ((5933, 5970), 'matplotlib.pyplot.title', 'plt.title', (['"""Random Forest Prediction"""'], {}), "('Random Forest Prediction')\n", (5942, 5970), True, 'import matplotlib.pyplot as plt\n'), ((5975, 5995), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'x', '"""-r"""'], {}), "(x, x, '-r')\n", (5983, 5995), True, 'import matplotlib.pyplot as plt\n'), ((5998, 6027), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted value"""'], {}), "('Predicted value')\n", (6008, 6027), True, 'import matplotlib.pyplot as plt\n'), ((6032, 6058), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Actual Value"""'], {}), "('Actual Value')\n", (6042, 6058), True, 'import matplotlib.pyplot as plt\n'), ((6155, 6180), 'numpy.linspace', 'np.linspace', (['(-15)', '(10)', '(100)'], {}), '(-15, 10, 100)\n', (6166, 6180), True, 'import numpy as np\n'), ((6183, 6213), 'matplotlib.pyplot.title', 'plt.title', (['"""Linear Prediction"""'], {}), "('Linear Prediction')\n", (6192, 6213), True, 'import matplotlib.pyplot as plt\n'), ((6218, 6238), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'x', '"""-r"""'], {}), "(x, x, '-r')\n", (6226, 6238), True, 'import matplotlib.pyplot as plt\n'), ((6241, 6270), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted value"""'], {}), "('Predicted value')\n", (6251, 6270), True, 'import matplotlib.pyplot as plt\n'), ((6275, 6301), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Actual Value"""'], {}), "('Actual Value')\n", (6285, 6301), True, 'import matplotlib.pyplot as plt\n'), ((6661, 6671), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6669, 6671), True, 'import matplotlib.pyplot as plt\n'), ((6772, 6805), 'helper.find_csv', 'find_csv', ([], {'path_to_dir': 'path_to_dir'}), '(path_to_dir=path_to_dir)\n', (6780, 6805), False, 'from helper import find_csv, find_sigma\n'), ((1491, 1545), 'keras.layers.Dense', 'Dense', (['(256)'], {'input_dim': 'data.shape[1]', 'activation': '"""relu"""'}), "(256, input_dim=data.shape[1], activation='relu')\n", (1496, 1545), False, 'from keras.layers import Dense, BatchNormalization, Dropout\n'), ((1561, 1590), 'keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (1566, 1590), False, 'from keras.layers import Dense, BatchNormalization, Dropout\n'), ((1605, 1633), 'keras.layers.Dense', 'Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (1610, 1633), False, 'from keras.layers import Dense, BatchNormalization, Dropout\n'), ((1648, 1688), 'keras.layers.Dense', 'Dense', (['output_shape'], {'activation': '"""linear"""'}), "(output_shape, activation='linear')\n", (1653, 1688), False, 'from keras.layers import Dense, BatchNormalization, Dropout\n'), ((3861, 3928), 'os.path.exists', 'os.path.exists', (['"""./weights/Predict Flux and half peak potential.h5"""'], {}), "('./weights/Predict Flux and half peak potential.h5')\n", (3875, 3928), False, 'import os\n'), ((6892, 6910), 'csv.writer', 'csv.writer', (['writer'], {}), '(writer)\n', (6902, 6910), False, 'import csv\n'), ((7152, 7181), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (7164, 7181), True, 'import matplotlib.pyplot as plt\n'), ((7226, 7255), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (7238, 7255), True, 'import matplotlib.pyplot as plt\n'), ((7394, 7413), 'helper.find_sigma', 'find_sigma', (['test_cv'], {}), '(test_cv)\n', (7404, 7413), False, 'from helper import find_csv, find_sigma\n'), ((7544, 7596), 'pandas.read_csv', 'pd.read_csv', (['f"""{path_to_dir}/{test_cv}"""'], {'header': 'None'}), "(f'{path_to_dir}/{test_cv}', header=None)\n", (7555, 7596), True, 'import pandas as pd\n'), ((7855, 7883), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 18)'}), '(figsize=(16, 18))\n', (7865, 7883), True, 'import matplotlib.pyplot as plt\n'), ((7900, 7920), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (7911, 7920), True, 'import matplotlib.pyplot as plt\n'), ((7947, 7975), 'numpy.array', 'np.array', (['[[sigma, keq, kf]]'], {}), '([[sigma, keq, kf]])\n', (7955, 7975), True, 'import numpy as np\n'), ((8001, 8023), 'numpy.log10', 'np.log10', (['test_feature'], {}), '(test_feature)\n', (8009, 8023), True, 'import numpy as np\n'), ((8126, 8173), 'numpy.average', 'np.average', (['((target[0] - range_all) / range_all)'], {}), '((target[0] - range_all) / range_all)\n', (8136, 8173), True, 'import numpy as np\n'), ((8602, 8671), 'matplotlib.pyplot.scatter', 'plt.scatter', (['target[0, 0]', 'range_all[0]'], {'label': '"""Peak Flux"""', 'color': '"""r"""'}), "(target[0, 0], range_all[0], label='Peak Flux', color='r')\n", (8613, 8671), True, 'import matplotlib.pyplot as plt\n'), ((8680, 8759), 'matplotlib.pyplot.scatter', 'plt.scatter', (['target[0, 1]', 'range_all[1]'], {'label': '"""Half Peak Potential"""', 'color': '"""b"""'}), "(target[0, 1], range_all[1], label='Half Peak Potential', color='b')\n", (8691, 8759), True, 'import matplotlib.pyplot as plt\n'), ((8768, 8827), 'matplotlib.pyplot.title', 'plt.title', (['"""Test Results: Neural Network"""'], {'fontsize': '"""large"""'}), "('Test Results: Neural Network', fontsize='large')\n", (8777, 8827), True, 'import matplotlib.pyplot as plt\n'), ((9128, 9148), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (9139, 9148), True, 'import matplotlib.pyplot as plt\n'), ((9274, 9345), 'matplotlib.pyplot.scatter', 'plt.scatter', (['RFtarget[0, 0]', 'range_all[0]'], {'label': '"""Peak Flux"""', 'color': '"""r"""'}), "(RFtarget[0, 0], range_all[0], label='Peak Flux', color='r')\n", (9285, 9345), True, 'import matplotlib.pyplot as plt\n'), ((9354, 9439), 'matplotlib.pyplot.scatter', 'plt.scatter', (['RFtarget[0, 1]', 'range_all[1]'], {'label': '"""Half Peak Potential"""', 'color': '"""b"""'}), "(RFtarget[0, 1], range_all[1], label='Half Peak Potential',\n color='b')\n", (9365, 9439), True, 'import matplotlib.pyplot as plt\n'), ((9444, 9502), 'matplotlib.pyplot.title', 'plt.title', (['"""Test Results: Random Forest"""'], {'fontsize': '"""large"""'}), "('Test Results: Random Forest', fontsize='large')\n", (9453, 9502), True, 'import matplotlib.pyplot as plt\n'), ((9840, 9851), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9849, 9851), True, 'import matplotlib.pyplot as plt\n'), ((10100, 10120), 'numpy.arange', 'np.arange', (['(-1.0)', '(1.0)'], {}), '(-1.0, 1.0)\n', (10109, 10120), True, 'import numpy as np\n'), ((10120, 10140), 'numpy.arange', 'np.arange', (['(-1.0)', '(1.0)'], {}), '(-1.0, 1.0)\n', (10129, 10140), True, 'import numpy as np\n'), ((10268, 10290), 'numpy.arange', 'np.arange', (['(-10.0)', '(10.0)'], {}), '(-10.0, 10.0)\n', (10277, 10290), True, 'import numpy as np\n'), ((10290, 10312), 'numpy.arange', 'np.arange', (['(-10.0)', '(10.0)'], {}), '(-10.0, 10.0)\n', (10299, 10312), True, 'import numpy as np\n'), ((8553, 8571), 'numpy.arange', 'np.arange', (['(-10)', '(10)'], {}), '(-10, 10)\n', (8562, 8571), True, 'import numpy as np\n'), ((8571, 8589), 'numpy.arange', 'np.arange', (['(-10)', '(10)'], {}), '(-10, 10)\n', (8580, 8589), True, 'import numpy as np\n'), ((9225, 9243), 'numpy.arange', 'np.arange', (['(-10)', '(10)'], {}), '(-10, 10)\n', (9234, 9243), True, 'import numpy as np\n'), ((9243, 9261), 'numpy.arange', 'np.arange', (['(-10)', '(10)'], {}), '(-10, 10)\n', (9252, 9261), True, 'import numpy as np\n'), ((8202, 8217), 'numpy.log10', 'np.log10', (['sigma'], {}), '(sigma)\n', (8210, 8217), True, 'import numpy as np\n'), ((8218, 8231), 'numpy.log10', 'np.log10', (['keq'], {}), '(keq)\n', (8226, 8231), True, 'import numpy as np\n'), ((8232, 8244), 'numpy.log10', 'np.log10', (['kf'], {}), '(kf)\n', (8240, 8244), True, 'import numpy as np\n')]
import numpy as np from PIL import Image import numbers from collections.abc import Sequence from typing import Tuple, List, Optional import random import torch from torchvision import transforms as T from torchvision.transforms import functional as F def _check_sequence_input(x, name, req_sizes): msg = req_sizes[0] if len(req_sizes) < 2 else " or ".join([str(s) for s in req_sizes]) if not isinstance(x, Sequence): raise TypeError("{} should be a sequence of length {}.".format(name, msg)) if len(x) not in req_sizes: raise ValueError("{} should be sequence of length {}.".format(name, msg)) def _setup_angle(x, name, req_sizes=(2, )): if isinstance(x, numbers.Number): if x < 0: raise ValueError("If {} is a single number, it must be positive.".format(name)) x = [-x, x] else: _check_sequence_input(x, name, req_sizes) return [float(d) for d in x] def pad_if_smaller(img, size, fill=0): min_size = min(img.size) if min_size < size: ow, oh = img.size padh = size - oh if oh < size else 0 padw = size - ow if ow < size else 0 img = F.pad(img, (0, 0, padw, padh), fill=fill) return img class Compose(object): def __init__(self, transforms): self.transforms = transforms def __call__(self, image, target): for t in self.transforms: image, target = t(image, target) return image, target class RandomResize(object): def __init__(self, min_size, max_size=None): self.min_size = min_size if max_size is None: max_size = min_size self.max_size = max_size def __call__(self, image, target): size = random.randint(self.min_size, self.max_size) image = F.resize(image, size) target = F.resize(target, size, interpolation=Image.NEAREST) return image, target class RandomHorizontalFlip(object): def __init__(self, flip_prob): self.flip_prob = flip_prob def __call__(self, image, target): if random.random() < self.flip_prob: image = F.hflip(image) target = F.hflip(target) return image, target class RandomCrop(object): def __init__(self, size): self.size = size def __call__(self, image, target): image = pad_if_smaller(image, self.size) target = pad_if_smaller(target, self.size, fill=255) crop_params = T.RandomCrop.get_params(image, (self.size, self.size)) image = F.crop(image, *crop_params) target = F.crop(target, *crop_params) return image, target class CenterCrop(object): def __init__(self, size): self.size = size def __call__(self, image, target): image = F.center_crop(image, self.size) target = F.center_crop(target, self.size) return image, target class ToTensor(object): def __call__(self, image, target): image = F.to_tensor(image) target = torch.as_tensor(np.array(target), dtype=torch.int64) return image, target class Normalize(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, image, target): image = F.normalize(image, mean=self.mean, std=self.std) return image, target class RandomRotation(object): def __init__(self, degrees, interpolation=Image.NEAREST, expand=False, center=None, fill=0, resample=None): self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2, )) self.center = center self.resample = self.interpolation = interpolation self.expand = expand if fill is None: fill = 0 elif not isinstance(fill, (Sequence, numbers.Number)): raise TypeError("Fill should be either a sequence or a number.") self.fill = fill @staticmethod def get_params(degrees: List[float]) -> float: angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item()) return angle def __call__(self, image, target): fill = self.fill if torch.is_tensor(image): if isinstance(fill, (int, float)): fill = [float(fill)] * 3 else: fill = [float(f) for f in fill] angle = self.get_params(self.degrees) image = F.rotate(image, angle, self.resample, self.expand, self.center, fill) return image, target class ColorJitter(object): def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): self.brightness = self._check_input(brightness, 'brightness') self.contrast = self._check_input(contrast, 'contrast') self.saturation = self._check_input(saturation, 'saturation') self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5), clip_first_on_zero=False) @staticmethod def get_params(brightness: Optional[List[float]], contrast: Optional[List[float]], saturation: Optional[List[float]], hue: Optional[List[float]] ) -> Tuple[torch.Tensor, Optional[float], Optional[float], Optional[float], Optional[float]]: fn_idx = torch.randperm(4) b = None if brightness is None else float(torch.empty(1).uniform_(brightness[0], brightness[1])) c = None if contrast is None else float(torch.empty(1).uniform_(contrast[0], contrast[1])) s = None if saturation is None else float(torch.empty(1).uniform_(saturation[0], saturation[1])) h = None if hue is None else float(torch.empty(1).uniform_(hue[0], hue[1])) return fn_idx, b, c, s, h def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True): if isinstance(value, numbers.Number): if value < 0: raise ValueError("If {} is a single number, it must be non negative.".format(name)) value = [center - float(value), center + float(value)] if clip_first_on_zero: value[0] = max(value[0], 0.0) elif isinstance(value, (tuple, list)) and len(value) == 2: if not bound[0] <= value[0] <= value[1] <= bound[1]: raise ValueError("{} values should be between {}".format(name, bound)) else: raise TypeError("{} should be a single number or a list/tuple with length 2.".format(name)) # if value is 0 or (1., 1.) for brightness/contrast/saturation # or (0., 0.) for hue, do nothing if value[0] == value[1] == center: value = None return value def __call__(self, image, target): fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params(self.brightness, self.contrast, self.saturation, self.hue) for fn_id in fn_idx: if fn_id == 0 and brightness_factor is not None: image = F.adjust_brightness(image, brightness_factor) elif fn_id == 1 and contrast_factor is not None: image = F.adjust_contrast(image, contrast_factor) elif fn_id == 2 and saturation_factor is not None: image = F.adjust_saturation(image, saturation_factor) elif fn_id == 3 and hue_factor is not None: image = F.adjust_hue(image, hue_factor) return image, target class ColorJitterGrid(object): def __init__(self, brightness=0, contrast=0, saturation=0, hue=0, grid_size=20): self.brightness = brightness self.contrast = contrast self.saturation = saturation self.hue = hue self.grid_size = grid_size def __call__(self, image, target): img_tensor, _ = ToTensor()(image, target) img_size = (img_tensor.shape[1], img_tensor.shape[2]) portion_size = (self.grid_size, self.grid_size) x1 = random.randint(0, img_size[0]-portion_size[0]-1) y1 = random.randint(0, img_size[1]-portion_size[1]-1) x2, y2 = x1+portion_size[0], y1+portion_size[1] grid = torch.clone(img_tensor[:, x1:x2, y1:y2]) jitter = ColorJitter(contrast=(self.contrast, self.contrast)) grid, _ = jitter(grid, target) img_tensor[:, x1:x2, y1:y2] = grid from torchvision import transforms image = transforms.ToPILImage()(img_tensor).convert("RGB") return image, target
[ "torchvision.transforms.functional.to_tensor", "torch.empty", "torchvision.transforms.functional.adjust_saturation", "torch.clone", "torchvision.transforms.functional.center_crop", "random.randint", "torchvision.transforms.functional.hflip", "torchvision.transforms.ToPILImage", "torchvision.transforms.functional.crop", "torch.is_tensor", "torchvision.transforms.functional.adjust_hue", "torchvision.transforms.functional.adjust_contrast", "torchvision.transforms.functional.resize", "random.random", "torch.randperm", "torchvision.transforms.functional.adjust_brightness", "torchvision.transforms.functional.normalize", "torchvision.transforms.functional.rotate", "torchvision.transforms.functional.pad", "numpy.array", "torchvision.transforms.RandomCrop.get_params" ]
[((1155, 1196), 'torchvision.transforms.functional.pad', 'F.pad', (['img', '(0, 0, padw, padh)'], {'fill': 'fill'}), '(img, (0, 0, padw, padh), fill=fill)\n', (1160, 1196), True, 'from torchvision.transforms import functional as F\n'), ((1719, 1763), 'random.randint', 'random.randint', (['self.min_size', 'self.max_size'], {}), '(self.min_size, self.max_size)\n', (1733, 1763), False, 'import random\n'), ((1780, 1801), 'torchvision.transforms.functional.resize', 'F.resize', (['image', 'size'], {}), '(image, size)\n', (1788, 1801), True, 'from torchvision.transforms import functional as F\n'), ((1819, 1870), 'torchvision.transforms.functional.resize', 'F.resize', (['target', 'size'], {'interpolation': 'Image.NEAREST'}), '(target, size, interpolation=Image.NEAREST)\n', (1827, 1870), True, 'from torchvision.transforms import functional as F\n'), ((2449, 2503), 'torchvision.transforms.RandomCrop.get_params', 'T.RandomCrop.get_params', (['image', '(self.size, self.size)'], {}), '(image, (self.size, self.size))\n', (2472, 2503), True, 'from torchvision import transforms as T\n'), ((2520, 2547), 'torchvision.transforms.functional.crop', 'F.crop', (['image', '*crop_params'], {}), '(image, *crop_params)\n', (2526, 2547), True, 'from torchvision.transforms import functional as F\n'), ((2565, 2593), 'torchvision.transforms.functional.crop', 'F.crop', (['target', '*crop_params'], {}), '(target, *crop_params)\n', (2571, 2593), True, 'from torchvision.transforms import functional as F\n'), ((2762, 2793), 'torchvision.transforms.functional.center_crop', 'F.center_crop', (['image', 'self.size'], {}), '(image, self.size)\n', (2775, 2793), True, 'from torchvision.transforms import functional as F\n'), ((2811, 2843), 'torchvision.transforms.functional.center_crop', 'F.center_crop', (['target', 'self.size'], {}), '(target, self.size)\n', (2824, 2843), True, 'from torchvision.transforms import functional as F\n'), ((2954, 2972), 'torchvision.transforms.functional.to_tensor', 'F.to_tensor', (['image'], {}), '(image)\n', (2965, 2972), True, 'from torchvision.transforms import functional as F\n'), ((3238, 3286), 'torchvision.transforms.functional.normalize', 'F.normalize', (['image'], {'mean': 'self.mean', 'std': 'self.std'}), '(image, mean=self.mean, std=self.std)\n', (3249, 3286), True, 'from torchvision.transforms import functional as F\n'), ((4125, 4147), 'torch.is_tensor', 'torch.is_tensor', (['image'], {}), '(image)\n', (4140, 4147), False, 'import torch\n'), ((4365, 4434), 'torchvision.transforms.functional.rotate', 'F.rotate', (['image', 'angle', 'self.resample', 'self.expand', 'self.center', 'fill'], {}), '(image, angle, self.resample, self.expand, self.center, fill)\n', (4373, 4434), True, 'from torchvision.transforms import functional as F\n'), ((5227, 5244), 'torch.randperm', 'torch.randperm', (['(4)'], {}), '(4)\n', (5241, 5244), False, 'import torch\n'), ((7903, 7955), 'random.randint', 'random.randint', (['(0)', '(img_size[0] - portion_size[0] - 1)'], {}), '(0, img_size[0] - portion_size[0] - 1)\n', (7917, 7955), False, 'import random\n'), ((7965, 8017), 'random.randint', 'random.randint', (['(0)', '(img_size[1] - portion_size[1] - 1)'], {}), '(0, img_size[1] - portion_size[1] - 1)\n', (7979, 8017), False, 'import random\n'), ((8085, 8125), 'torch.clone', 'torch.clone', (['img_tensor[:, x1:x2, y1:y2]'], {}), '(img_tensor[:, x1:x2, y1:y2])\n', (8096, 8125), False, 'import torch\n'), ((2059, 2074), 'random.random', 'random.random', ([], {}), '()\n', (2072, 2074), False, 'import random\n'), ((2113, 2127), 'torchvision.transforms.functional.hflip', 'F.hflip', (['image'], {}), '(image)\n', (2120, 2127), True, 'from torchvision.transforms import functional as F\n'), ((2149, 2164), 'torchvision.transforms.functional.hflip', 'F.hflip', (['target'], {}), '(target)\n', (2156, 2164), True, 'from torchvision.transforms import functional as F\n'), ((3006, 3022), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (3014, 3022), True, 'import numpy as np\n'), ((6950, 6995), 'torchvision.transforms.functional.adjust_brightness', 'F.adjust_brightness', (['image', 'brightness_factor'], {}), '(image, brightness_factor)\n', (6969, 6995), True, 'from torchvision.transforms import functional as F\n'), ((7081, 7122), 'torchvision.transforms.functional.adjust_contrast', 'F.adjust_contrast', (['image', 'contrast_factor'], {}), '(image, contrast_factor)\n', (7098, 7122), True, 'from torchvision.transforms import functional as F\n'), ((8340, 8363), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (8361, 8363), False, 'from torchvision import transforms\n'), ((5296, 5310), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (5307, 5310), False, 'import torch\n'), ((5399, 5413), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (5410, 5413), False, 'import torch\n'), ((5500, 5514), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (5511, 5514), False, 'import torch\n'), ((5598, 5612), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (5609, 5612), False, 'import torch\n'), ((7210, 7255), 'torchvision.transforms.functional.adjust_saturation', 'F.adjust_saturation', (['image', 'saturation_factor'], {}), '(image, saturation_factor)\n', (7229, 7255), True, 'from torchvision.transforms import functional as F\n'), ((3958, 3972), 'torch.empty', 'torch.empty', (['(1)'], {}), '(1)\n', (3969, 3972), False, 'import torch\n'), ((7336, 7367), 'torchvision.transforms.functional.adjust_hue', 'F.adjust_hue', (['image', 'hue_factor'], {}), '(image, hue_factor)\n', (7348, 7367), True, 'from torchvision.transforms import functional as F\n')]
from process_lap_data import ProcessData,Evaluate from lstm_crf import BiLSTM_CRF import torch from config import * import torch.nn as nn import numpy as np torch.manual_seed(seed) # 为CPU设置随机种子 torch.cuda.manual_seed(seed) # 为当前GPU设置随机种子 torch.cuda.manual_seed_all(seed) # 为所有GPU设置随机种子 np.random.seed(np_seed) if __name__=="__main__": process_utils = ProcessData() process_utils.read_vocab("C:\\Users\\11415\\Desktop\\Google_Deep_Learning\\Google_NLP_DL\\9.11\\tor\\vocab\\word_vocab.txt") test_texts,test_words,test_labels = process_utils.read_data( \ "C:\\Users\\11415\\Desktop\\Google_Deep_Learning\\Google_NLP_DL\\9.11\\tor\\data_plain\\test.txt") test_words_ids, test_labels_ids= process_utils.convert_to_vocab(test_words,test_labels) texts,words,labels = process_utils.read_data( \ "C:\\Users\\11415\\Desktop\\Google_Deep_Learning\\Google_NLP_DL\\9.11\\tor\\data_plain\\train.txt") words_ids, labels_ids = process_utils.convert_to_vocab(words,labels) datas = [[texts[i],words[i],words_ids[i],labels_ids[i]] for i in range(len(texts))] test_datas = [[test_texts[i],test_words[i],test_words_ids[i],test_labels_ids[i]] for i in range(len(test_texts))] val_sample_ids = np.random.choice(len(datas), int(len(datas) * 0.1), replace=False) train_datas,train_labels = [],[] dev_datas,dev_labels = [],[] for i,data in enumerate(datas): if i in val_sample_ids: dev_datas.append(data) dev_labels.append(labels_ids[i]) else: train_datas.append(data) train_labels.append(labels_ids[i]) print("train_dev_splited..") word_embedding_matrix = process_utils.loadEmbMatrix(\ "C:\\Users\\11415\\Desktop\\Google_Deep_Learning\\Google_NLP_DL\\9.11\\tor\\data_plain\\aets_embedding.txt", embedding_size, bina=False) print("embedding..") model = BiLSTM_CRF( tag_to_ix = labels_dict, \ embedding_dim = embedding_size, hidden_dim = lstm_hidding_dim, word_embedding_matrix = word_embedding_matrix) optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) loss_func = nn.NLLLoss() train_epoch_loss = 0.0 train_batches = process_utils.batch_iter(train_datas, train_labels, batch_size, embedding_size) each_epoch_batch_number = int(len(train_datas) / batch_size) train_epoch_reals = [] train_epoch_results = [] train_epoch_words = [] evalute_utils = Evaluate() dev_max_f1 = 0.0 for k, train_batch in enumerate(train_batches): model.train() train_texts_batch, train_words_batch, train_words_ids_batch, train_aspect_labels_batch = zip(*train_batch) train_aspect_labels_batch = np.array(train_aspect_labels_batch) x_train = torch.from_numpy(np.array(train_words_ids_batch)) ## b,83 # debug x_train = x_train.long() out, predict_sample = model(x_train)#b,83,13, out = out.view(-1,classfy_number) train_aspect_labels_batch_reshape = np.reshape(train_aspect_labels_batch,[-1]) batch_loss = loss_func(out, torch.from_numpy(train_aspect_labels_batch_reshape).long()) optimizer.zero_grad() batch_loss.backward() optimizer.step() train_epoch_loss += batch_loss.item() train_epoch_reals.extend(train_aspect_labels_batch) train_epoch_results.extend(predict_sample.numpy().tolist()) train_epoch_words.extend(train_words_batch) if (k + 1) % each_epoch_batch_number == 0 and k != 0: model.adjust_learning_rate(learning_rate, optimizer, int((k + 1) / each_epoch_batch_number )) print(int((k + 1) / each_epoch_batch_number )," epoch , train_loss:", train_epoch_loss) train_epoch_loss = 0.0 train_precison, train_recall, train_f1 = evalute_utils.calculate(train_epoch_words, train_epoch_results,train_epoch_reals, ) train_epoch_reals = [] train_epoch_results = [] train_epoch_words = [] model.eval() dev_batches = process_utils.batch_iter(dev_datas, dev_labels, 500, 1, False) dev_epoch_reals,dev_epoch_predict,dev_epoch_words = [],[],[] for m, dev_batch in enumerate(dev_batches): dev_texts_batch, dev_words_batch, dev_words_ids_batch, dev_aspect_labels_batch = zip(*dev_batch) dev_aspect_labels_batch = np.array(dev_aspect_labels_batch) x_dev = torch.from_numpy(np.array(dev_words_ids_batch)) x_dev = x_dev.long() out, predict_sample = model(x_dev) dev_epoch_reals.extend(dev_aspect_labels_batch) dev_epoch_predict.extend(predict_sample.numpy().tolist()) dev_epoch_words.extend(dev_words_batch) dev_precison, dev_recall, dev_f1 = evalute_utils.calculate(dev_epoch_words, dev_epoch_predict,dev_epoch_reals, ) if dev_f1>dev_max_f1: dev_max_f1 = dev_f1 print("dev evaluating...", dev_precison, dev_recall, dev_f1) #######test model.eval() test_batches = process_utils.batch_iter(test_datas, test_labels, 500, 1, False) test_epoch_reals, test_epoch_predict, test_epoch_words = [], [], [] for p, test_batch in enumerate(test_batches): test_texts_batch, test_words_batch, test_words_ids_batch, test_aspect_labels_batch = zip(*test_batch) test_aspect_labels_batch = np.array(test_aspect_labels_batch) x_test = torch.from_numpy(np.array(test_words_ids_batch)) x_test = x_test.long() out, predict_sample = model(x_test) test_epoch_reals.extend(test_aspect_labels_batch) test_epoch_predict.extend(predict_sample.numpy().tolist()) test_epoch_words.extend(test_words_batch) test_precison, test_recall, test_f1 = evalute_utils.calculate(test_epoch_words,test_epoch_predict, test_epoch_reals, ) print("test evaluating...",test_precison, test_recall, test_f1)
[ "numpy.random.seed", "torch.manual_seed", "process_lap_data.ProcessData", "torch.cuda.manual_seed", "lstm_crf.BiLSTM_CRF", "torch.nn.NLLLoss", "process_lap_data.Evaluate", "torch.cuda.manual_seed_all", "numpy.array", "numpy.reshape", "torch.from_numpy" ]
[((157, 180), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (174, 180), False, 'import torch\n'), ((205, 233), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (227, 233), False, 'import torch\n'), ((255, 287), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (281, 287), False, 'import torch\n'), ((305, 328), 'numpy.random.seed', 'np.random.seed', (['np_seed'], {}), '(np_seed)\n', (319, 328), True, 'import numpy as np\n'), ((376, 389), 'process_lap_data.ProcessData', 'ProcessData', ([], {}), '()\n', (387, 389), False, 'from process_lap_data import ProcessData, Evaluate\n'), ((1905, 2047), 'lstm_crf.BiLSTM_CRF', 'BiLSTM_CRF', ([], {'tag_to_ix': 'labels_dict', 'embedding_dim': 'embedding_size', 'hidden_dim': 'lstm_hidding_dim', 'word_embedding_matrix': 'word_embedding_matrix'}), '(tag_to_ix=labels_dict, embedding_dim=embedding_size, hidden_dim=\n lstm_hidding_dim, word_embedding_matrix=word_embedding_matrix)\n', (1915, 2047), False, 'from lstm_crf import BiLSTM_CRF\n'), ((2151, 2163), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (2161, 2163), True, 'import torch.nn as nn\n'), ((2459, 2469), 'process_lap_data.Evaluate', 'Evaluate', ([], {}), '()\n', (2467, 2469), False, 'from process_lap_data import ProcessData, Evaluate\n'), ((2716, 2751), 'numpy.array', 'np.array', (['train_aspect_labels_batch'], {}), '(train_aspect_labels_batch)\n', (2724, 2751), True, 'import numpy as np\n'), ((3018, 3061), 'numpy.reshape', 'np.reshape', (['train_aspect_labels_batch', '[-1]'], {}), '(train_aspect_labels_batch, [-1])\n', (3028, 3061), True, 'import numpy as np\n'), ((2787, 2818), 'numpy.array', 'np.array', (['train_words_ids_batch'], {}), '(train_words_ids_batch)\n', (2795, 2818), True, 'import numpy as np\n'), ((4492, 4525), 'numpy.array', 'np.array', (['dev_aspect_labels_batch'], {}), '(dev_aspect_labels_batch)\n', (4500, 4525), True, 'import numpy as np\n'), ((3097, 3148), 'torch.from_numpy', 'torch.from_numpy', (['train_aspect_labels_batch_reshape'], {}), '(train_aspect_labels_batch_reshape)\n', (3113, 3148), False, 'import torch\n'), ((4567, 4596), 'numpy.array', 'np.array', (['dev_words_ids_batch'], {}), '(dev_words_ids_batch)\n', (4575, 4596), True, 'import numpy as np\n'), ((5697, 5731), 'numpy.array', 'np.array', (['test_aspect_labels_batch'], {}), '(test_aspect_labels_batch)\n', (5705, 5731), True, 'import numpy as np\n'), ((5778, 5808), 'numpy.array', 'np.array', (['test_words_ids_batch'], {}), '(test_words_ids_batch)\n', (5786, 5808), True, 'import numpy as np\n')]
""" Script to synthesize observational data from ground truth factors. """ import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import numpy as np import os from disentanglement_lib.data.ground_truth import dsprites, norb, cars3d, shapes3d from absl import app from absl import flags FLAGS = flags.FLAGS flags.DEFINE_enum('data_type', 'dsprites', ['dsprites', 'smallnorb', 'cars3d', 'shapes3d'], 'Data set type.') flags.DEFINE_string('factors_path', '', 'Path to where factors are saved.') flags.DEFINE_string('out_dir', '', 'Directory to where to save data to.') flags.DEFINE_integer('seed', 42, 'Random seed.') def create_data(factors): """ :param factors: underlying factors of variation :return: data: obervational data from underlying factors """ if FLAGS.data_type == "dsprites": dsp = dsprites.DSprites() elif FLAGS.data_type == "smallnorb": snb = norb.SmallNORB() elif FLAGS.data_type == "cars3d": cars = cars3d.Cars3D() elif FLAGS.data_type == "shapes3d": shp = shapes3d.Shapes3D() random_state = np.random.RandomState(FLAGS.seed) factors_train = np.transpose(factors['factors_train'], (0,2,1)) factors_test = np.transpose(factors['factors_test'], (0,2,1)) N_train = factors_train.shape[0] N_test = factors_test.shape[0] time_len = factors_train.shape[1] if FLAGS.data_type in ["dsprites", "smallnorb"]: data_train = np.zeros([N_train, time_len, 64 * 64]) data_test = np.zeros([N_test, time_len, 64 * 64]) elif FLAGS.data_type in ["cars3d", "shapes3d"]: data_train = np.zeros([N_train, time_len, 64 * 64 * 3]) data_test = np.zeros([N_test, time_len, 64 * 64 * 3]) # Training data for i in range(N_train): if FLAGS.data_type == "dsprites": data_point_train = np.squeeze(dsp.sample_observations_from_factors_no_color( factors=factors_train[i, :, :], random_state=random_state)) data_train_reshape = data_point_train.reshape(data_point_train.shape[0], 64 * 64) elif FLAGS.data_type == "smallnorb": data_point_train = np.squeeze(snb.sample_observations_from_factors( factors=factors_train[i, :, :], random_state=random_state)) data_train_reshape = data_point_train.reshape(data_point_train.shape[0], 64 * 64) elif FLAGS.data_type == "cars3d": data_point_train = cars.sample_observations_from_factors( factors=factors_train[i, :, :], random_state=random_state) data_train_reshape = data_point_train.reshape(data_point_train.shape[0], 64 * 64 * 3) elif FLAGS.data_type == "shapes3d": data_point_train = shp.sample_observations_from_factors( factors=factors_train[i, :, :], random_state=random_state) data_train_reshape = data_point_train.reshape(data_point_train.shape[0], 64 * 64 * 3) data_train[i, :, :] = data_train_reshape # Test data for i in range(N_test): if FLAGS.data_type == "dsprites": data_point_test = np.squeeze(dsp.sample_observations_from_factors_no_color( factors=factors_test[i, :, :], random_state=random_state)) data_test_reshape = data_point_test.reshape(data_point_test.shape[0], 64 * 64) elif FLAGS.data_type == "smallnorb": data_point_test = np.squeeze(snb.sample_observations_from_factors( factors=factors_test[i, :, :], random_state=random_state)) data_test_reshape = data_point_test.reshape(data_point_test.shape[0], 64 * 64) elif FLAGS.data_type == "cars3d": data_point_test = cars.sample_observations_from_factors( factors=factors_test[i, :, :], random_state=random_state) data_test_reshape = data_point_test.reshape(data_point_test.shape[0], 64 * 64 * 3) elif FLAGS.data_type == "shapes3d": data_point_test = shp.sample_observations_from_factors( factors=factors_test[i, :, :], random_state=random_state) data_test_reshape = data_point_test.reshape(data_point_test.shape[0], 64 * 64 * 3) data_test[i, :, :] = data_test_reshape return data_train.astype('float32'), data_test.astype('float32') def main(argv): del argv if FLAGS.out_dir == '': out_dir = FLAGS.data_type else: out_dir = FLAGS.out_dir if FLAGS.factors_path == '': factors_path = os.path.join(FLAGS.data_type, F'factors_{FLAGS.data_type}.npz') else: factors_path = FLAGS.factors_path # Load factors factors_full = np.load(factors_path) # Synthesize observational data from factors data_train, data_test = create_data(factors_full) # Save data save_path = os.path.join(out_dir, F'{FLAGS.data_type}.npz') np.savez(save_path, x_train_full=data_train, x_train_miss=data_train, m_train_miss=np.zeros_like(data_train), x_test_full=data_test, x_test_miss=data_test, m_test_miss=np.zeros_like(data_test)) print(F'Data set successfully created and saved at: {save_path}') if __name__ == '__main__': app.run(main)
[ "disentanglement_lib.data.ground_truth.norb.SmallNORB", "numpy.load", "numpy.zeros_like", "warnings.simplefilter", "os.path.join", "disentanglement_lib.data.ground_truth.cars3d.Cars3D", "disentanglement_lib.data.ground_truth.dsprites.DSprites", "numpy.transpose", "numpy.zeros", "numpy.random.RandomState", "disentanglement_lib.data.ground_truth.shapes3d.Shapes3D", "absl.flags.DEFINE_string", "absl.app.run", "absl.flags.DEFINE_integer", "absl.flags.DEFINE_enum" ]
[((91, 153), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (112, 153), False, 'import warnings\n'), ((334, 447), 'absl.flags.DEFINE_enum', 'flags.DEFINE_enum', (['"""data_type"""', '"""dsprites"""', "['dsprites', 'smallnorb', 'cars3d', 'shapes3d']", '"""Data set type."""'], {}), "('data_type', 'dsprites', ['dsprites', 'smallnorb',\n 'cars3d', 'shapes3d'], 'Data set type.')\n", (351, 447), False, 'from absl import flags\n'), ((444, 519), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""factors_path"""', '""""""', '"""Path to where factors are saved."""'], {}), "('factors_path', '', 'Path to where factors are saved.')\n", (463, 519), False, 'from absl import flags\n'), ((520, 593), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""out_dir"""', '""""""', '"""Directory to where to save data to."""'], {}), "('out_dir', '', 'Directory to where to save data to.')\n", (539, 593), False, 'from absl import flags\n'), ((594, 642), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""seed"""', '(42)', '"""Random seed."""'], {}), "('seed', 42, 'Random seed.')\n", (614, 642), False, 'from absl import flags\n'), ((1107, 1140), 'numpy.random.RandomState', 'np.random.RandomState', (['FLAGS.seed'], {}), '(FLAGS.seed)\n', (1128, 1140), True, 'import numpy as np\n'), ((1162, 1211), 'numpy.transpose', 'np.transpose', (["factors['factors_train']", '(0, 2, 1)'], {}), "(factors['factors_train'], (0, 2, 1))\n", (1174, 1211), True, 'import numpy as np\n'), ((1229, 1277), 'numpy.transpose', 'np.transpose', (["factors['factors_test']", '(0, 2, 1)'], {}), "(factors['factors_test'], (0, 2, 1))\n", (1241, 1277), True, 'import numpy as np\n'), ((4723, 4744), 'numpy.load', 'np.load', (['factors_path'], {}), '(factors_path)\n', (4730, 4744), True, 'import numpy as np\n'), ((4880, 4927), 'os.path.join', 'os.path.join', (['out_dir', 'f"""{FLAGS.data_type}.npz"""'], {}), "(out_dir, f'{FLAGS.data_type}.npz')\n", (4892, 4927), False, 'import os\n'), ((5256, 5269), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (5263, 5269), False, 'from absl import app\n'), ((852, 871), 'disentanglement_lib.data.ground_truth.dsprites.DSprites', 'dsprites.DSprites', ([], {}), '()\n', (869, 871), False, 'from disentanglement_lib.data.ground_truth import dsprites, norb, cars3d, shapes3d\n'), ((1462, 1500), 'numpy.zeros', 'np.zeros', (['[N_train, time_len, 64 * 64]'], {}), '([N_train, time_len, 64 * 64])\n', (1470, 1500), True, 'import numpy as np\n'), ((1521, 1558), 'numpy.zeros', 'np.zeros', (['[N_test, time_len, 64 * 64]'], {}), '([N_test, time_len, 64 * 64])\n', (1529, 1558), True, 'import numpy as np\n'), ((4568, 4631), 'os.path.join', 'os.path.join', (['FLAGS.data_type', 'f"""factors_{FLAGS.data_type}.npz"""'], {}), "(FLAGS.data_type, f'factors_{FLAGS.data_type}.npz')\n", (4580, 4631), False, 'import os\n'), ((927, 943), 'disentanglement_lib.data.ground_truth.norb.SmallNORB', 'norb.SmallNORB', ([], {}), '()\n', (941, 943), False, 'from disentanglement_lib.data.ground_truth import dsprites, norb, cars3d, shapes3d\n'), ((1632, 1674), 'numpy.zeros', 'np.zeros', (['[N_train, time_len, 64 * 64 * 3]'], {}), '([N_train, time_len, 64 * 64 * 3])\n', (1640, 1674), True, 'import numpy as np\n'), ((1695, 1736), 'numpy.zeros', 'np.zeros', (['[N_test, time_len, 64 * 64 * 3]'], {}), '([N_test, time_len, 64 * 64 * 3])\n', (1703, 1736), True, 'import numpy as np\n'), ((5028, 5053), 'numpy.zeros_like', 'np.zeros_like', (['data_train'], {}), '(data_train)\n', (5041, 5053), True, 'import numpy as np\n'), ((5126, 5150), 'numpy.zeros_like', 'np.zeros_like', (['data_test'], {}), '(data_test)\n', (5139, 5150), True, 'import numpy as np\n'), ((997, 1012), 'disentanglement_lib.data.ground_truth.cars3d.Cars3D', 'cars3d.Cars3D', ([], {}), '()\n', (1010, 1012), False, 'from disentanglement_lib.data.ground_truth import dsprites, norb, cars3d, shapes3d\n'), ((1067, 1086), 'disentanglement_lib.data.ground_truth.shapes3d.Shapes3D', 'shapes3d.Shapes3D', ([], {}), '()\n', (1084, 1086), False, 'from disentanglement_lib.data.ground_truth import dsprites, norb, cars3d, shapes3d\n')]
import os import ubelt as ub import numpy as np import netharn as nh import torch import torchvision import itertools as it import utool as ut import glob from collections import OrderedDict import parse def _auto_argparse(func): """ Transform a function with a Google Style Docstring into an `argparse.ArgumentParser`. Custom utility. Not sure where it goes yet. """ from xdoctest import docscrape_google as scrape import argparse import inspect # Parse default values from the function dynamically spec = inspect.getargspec(func) kwdefaults = dict(zip(spec.args[-len(spec.defaults):], spec.defaults)) # Parse help and description information from a google-style docstring docstr = func.__doc__ description = scrape.split_google_docblocks(docstr)[0][1][0].strip() google_args = {argdict['name']: argdict for argdict in scrape.parse_google_args(docstr)} # Create the argument parser and register each argument parser = argparse.ArgumentParser( description=description, formatter_class=argparse.ArgumentDefaultsHelpFormatter ) for arg in spec.args: argkw = {} if arg in kwdefaults: argkw['default'] = kwdefaults[arg] if arg in google_args: garg = google_args[arg] argkw['help'] = garg['desc'] try: argkw['type'] = eval(garg['type'], {}) except Exception: pass parser.add_argument('--' + arg, **argkw) return parser def fit(dbname='PZ_MTEST', nice='untitled', dim=416, bsize=6, bstep=4, lr=0.001, decay=0.0005, workers=0, xpu='cpu', epoch='best', thres=0.5): """ Train a siamese chip descriptor for animal identification. Args: dbname (str): Name of IBEIS database to use nice (str): Custom tag for this run dim (int): Width and height of the network input bsize (int): Base batch size. Number of examples in GPU at any time. bstep (int): Multiply by bsize to simulate a larger batches. lr (float): Base learning rate decay (float): Weight decay (L2 regularization) workers (int): Number of parallel data loader workers xpu (str): Device to train on. Can be either `'cpu'`, `'gpu'`, a number indicating a GPU (e.g. `0`), or a list of numbers (e.g. `[0,1,2]`) indicating multiple GPUs # epoch (int): epoch number to evaluate on # thres (float): threshold for accuracy and mcc calculation """ # There has to be a good way to use argparse and specify params only once. # Pass all args down to comparable_vamp import inspect kw = ub.dict_subset(locals(), inspect.getargspec(fit).args) comparable_vamp(**kw) def comparable_vamp(**kwargs): import parse import glob from ibeis.algo.verif import vsone parse.log.setLevel(30) from netharn.examples.siam_ibeis import randomized_ibeis_dset from netharn.examples.siam_ibeis import SiameseLP, SiamHarness, setup_harness dbname = ub.argval('--db', default='GZ_Master1') nice = ub.argval('--nice',default='untitled') # thres = ub.argval('--thres',default=0.5) dim = 512 datasets = randomized_ibeis_dset(dbname, dim=dim) class_names = ['diff', 'same'] workdir = ub.ensuredir(os.path.expanduser( '~/data/work/siam-ibeis2/' + dbname)) task_name = 'binary_match' datasets['test'].pccs datasets['train'].pccs # pblm = vsone.OneVsOneProblem.from_empty('PZ_MTEST') ibs = datasets['train'].infr.ibs labeled_aid_pairs = [datasets['train'].get_aidpair(i) for i in range(len(datasets['train']))] pblm_train = vsone.OneVsOneProblem.from_labeled_aidpairs( ibs, labeled_aid_pairs, class_names=class_names, task_name=task_name, ) test_labeled_aid_pairs = [datasets['test'].get_aidpair(i) for i in range(len(datasets['test']))] pblm_test = vsone.OneVsOneProblem.from_labeled_aidpairs( ibs, test_labeled_aid_pairs, class_names=class_names, task_name=task_name, ) harn = setup_harness(dbname=dbname) harn.initialize() margin = harn.hyper.criterion_params['margin'] vamp_res = vamp(pblm_train, workdir, pblm_test) # ---------------------------- # Evaluate the siamese dataset pretrained = 'resnet50' branch = getattr(torchvision.models, pretrained)(pretrained=False) model = SiameseLP(p=2, branch=branch, input_shape=(1, 3, dim, dim)) #if torch.cuda.is_available(): xpu = nh.XPU.cast(kwargs.get('xpu','cpu'))#xpu_device.XPU.from_argv() print('Preparing to predict {} on {}'.format(model.__class__.__name__,xpu)) xpu.move(model) train_dpath ='/home/angelasu/work/siam-ibeis2/' + dbname + '/fit/nice/' + nice print(train_dpath) epoch = ub.argval('--epoch', default=None) epoch = int(epoch) if epoch is not None and epoch != 'best' and epoch != 'recent' and epoch != 'all' else epoch max_roc = 0 siam_res_arr = [] dist_arr_ret = [] if epoch == 'all': # max_roc = 0 # siam_res_arr = [] for file in sorted(glob.glob(train_dpath + '/*/_epoch_*.pt')): print(file) load_path = file dist_arr, max_roc, siam_res_arr = siam(load_path, xpu, model, pblm_test, datasets, margin, max_roc, siam_res_arr, dist_arr_ret) siam_res = siam_res_arr[-1] else: load_path = get_snapshot(train_dpath, epoch=epoch) dist_arr, siam_res = siam(load_path, xpu, model, pblm_test, datasets, margin, max_roc, siam_res_arr, dist_arr_ret) thres = ub.argval('--thres', default=0.5) thres = float(thres) thres_range = np.linspace(thres-0.05, thres+0.05,41) for val in thres_range: print('threshold value = {!r}'.format(val)) p_same = torch.sigmoid(torch.Tensor(-(dist_arr-margin))).numpy()-(val-0.5) p_diff = 1 - p_same # y_pred = (dist_arr <= 4) import pandas as pd pd.set_option("display.max_rows", None) # hack probabilities probs_df = pd.DataFrame( # np.array([dist_arr,p_same]).T, np.array([p_diff,p_same]).T, # np.array([y_pred,y_pred]).T, columns=class_names, index=pblm_test.samples['binary_match'].indicator_df.index ) sorted_df = probs_df.sort_index() # sorted_df = probs_df.sort_values(by='same', ascending=False) sorted_df = sorted_df.iloc[:,1:2] #0:2 # sorted_df.info() siam_res = vsone.clf_helpers.ClfResult() siam_res.probs_df = probs_df siam_res.probhats_df = None siam_res.data_key = 'SiamL2' siam_res.feat_dims = None siam_res.class_names = class_names siam_res.task_name = task_name siam_res.target_bin_df = pblm_test.samples['binary_match'].indicator_df siam_res.target_enc_df = pblm_test.samples['binary_match'].encoded_df target_sort = siam_res.target_bin_df.sort_index().iloc[:,1:2] result = pd.concat([sorted_df, target_sort],axis=1) siam_report = siam_res.extended_clf_report() print('siam roc = {}'.format(siam_res.roc_score())) print(nice) print('--- SIAM ---') print('epoch = {!r}'.format(epoch)) print('margin= {!r}'.format(margin)) print('threshold = {!r}'.format(thres)) siam_report = siam_res.extended_clf_report() # NOQA print('siam roc = {}'.format(siam_res.roc_score())) # siam_res.show_roc('same') # ut.show_if_requested() # siam_res.show_roc('diff') # ut.show_if_requested() #from sklearn import metrics #/ print('mcc {}'.format(metrics.matthews_corrcoef(siam_res.target_bin_df, probs_df))) print('--- VAMP ---') vamp_report = vamp_res.extended_clf_report() # NOQA print('vamp roc = {}'.format(vamp_res.roc_score())) def get_snapshot(train_dpath, epoch='recent'): """ Get a path to a particular epoch or the most recent one """ snapshots = sorted(glob.glob(train_dpath + '/*/_epoch_*.pt')) if epoch is None: epoch = 'recent' if epoch == 'best': snapshots = sorted(glob.glob(train_dpath + '/best_snapshot.pt')) load_path = snapshots[0] elif epoch == 'recent': load_path = snapshots[-1] else: snapshot_nums = [parse.parse('{}_epoch_{num:d}.pt', path).named['num'] for path in snapshots] load_path = dict(zip(snapshot_nums, snapshots))[epoch] print('load path: ',load_path) return load_path def siam(load_path, xpu, model, pblm_test, datasets,margin, max_roc, siam_res_arr, dist_arr_ret): from netharn.examples.siam_ibeis import randomized_ibeis_dset from netharn.examples.siam_ibeis import SiameseLP, SiamHarness, setup_harness from ibeis.algo.verif import vsone parse.log.setLevel(30) dbname = ub.argval('--db', default='GZ_Master1') nice = ub.argval('--nice',default='untitled') # thres = ub.argval('--thres',default=0.5) dim = 512 class_names = ['diff', 'same'] workdir = ub.ensuredir(os.path.expanduser( '~/data/work/siam-ibeis2/' + dbname)) task_name = 'binary_match' # pblm = vsone.OneVsOneProblem.from_empty('PZ_MTEST') # print('Preparing to predict {} on {}'.format(model.__class__.__name__,xpu)) xpu.move(model) # ---------------------------- # Evaluate the siamese dataset thres = ub.argval('--thres', default=0.5) thres = float(thres) # print('Loading snapshot onto {}'.format(xpu)) 'pretrained model' snapshot = torch.load(load_path, map_location= lambda storage, loc:storage) #map_location = xpu.map_location()) #map_location={'cuda:1': 'cpu'}) new_pretrained_state = OrderedDict() for k, v in snapshot['model_state_dict'].items(): layer_name = k.replace("module.", "") new_pretrained_state[layer_name] = v model.load_state_dict(new_pretrained_state) del snapshot model.train(False) dists = [] dataset = datasets['test'] #for aid1, aid2 in ub.ProgIter(pblm_train.samples.index, label='training set'): # print(aid1, aid2) # for aid1, aid2 in ub.ProgIter(pblm_test.samples.index, label='predicting'): for aid1, aid2 in ub.ProgIter(pblm_test.samples.index, label='predicting'): img1, img2 = dataset.load_from_edge(aid1, aid2) img1 = torch.FloatTensor(img1.transpose(2, 0, 1)) img2 = torch.FloatTensor(img2.transpose(2, 0, 1)) #img1, img2 = xpu.variables(*inputs) img1 = xpu.variable(img1) img2 = xpu.variable(img2) dist_tensor = model(img1[None, :], img2[None, :]) dist = dist_tensor.data.cpu().numpy() dists.append(dist) dist_arr= np.squeeze(np.array(dists)) #p_same = np.exp(-dist_arr) #p_diff = 1 - p_same thres = ub.argval('--thres', default=0.5) thres = float(thres) p_same = torch.sigmoid(torch.Tensor(-(dist_arr-margin))).numpy()-(thres-0.5) p_diff = 1 - p_same # y_pred = (dist_arr <= 4) import pandas as pd pd.set_option("display.max_rows", None) # hack probabilities probs_df = pd.DataFrame( # np.array([dist_arr,p_same]).T, np.array([p_diff,p_same]).T, # np.array([y_pred,y_pred]).T, columns=class_names, index=pblm_test.samples['binary_match'].indicator_df.index ) sorted_df = probs_df.sort_index() # sorted_df = probs_df.sort_values(by='same', ascending=False) sorted_df = sorted_df.iloc[:,1:2] #0:2 #print(sorted_df) # sorted_df.info() siam_res = vsone.clf_helpers.ClfResult() siam_res.probs_df = probs_df siam_res.probhats_df = None siam_res.data_key = 'SiamL2' siam_res.feat_dims = None siam_res.class_names = class_names siam_res.task_name = task_name siam_res.target_bin_df = pblm_test.samples['binary_match'].indicator_df siam_res.target_enc_df = pblm_test.samples['binary_match'].encoded_df target_sort = siam_res.target_bin_df.sort_index().iloc[:,1:2] result = pd.concat([sorted_df, target_sort],axis=1,sort=True) #print(result) epoch = ub.argval('--epoch',default=None) if epoch == 'all': print('siam roc = {}'.format(siam_res.roc_score())) if siam_res.roc_score() > max_roc: max_roc = siam_res.roc_score() # siam_res_arr = [] siam_res_arr.append(siam_res) dist_arr_ret.append(dist_arr) return dist_arr, max_roc, siam_res_arr else: return dist_arr, siam_res def vamp(pblm_train, workdir, pblm_test): # ---------------------------- # Build a VAMP classifier using the siamese training dataset pblm_train.load_features() pblm_train.samples.print_info() pblm_train.build_feature_subsets() pblm_train.samples.print_featinfo() pblm_train.learn_deploy_classifiers(task_keys=['binary_match']) clf_dpath = ub.ensuredir((workdir, 'clf')) classifiers = pblm_train.ensure_deploy_classifiers(dpath=clf_dpath) ibs_clf = classifiers['binary_match'] clf = ibs_clf.clf # ---------------------------- # Evaluate the VAMP classifier on the siamese testing dataset pblm_test.load_features() pblm_test.samples.print_info() pblm_test.build_feature_subsets() pblm_test.samples.print_featinfo() data_key = pblm_train.default_data_key task_key = 'binary_match' vamp_res = pblm_test._external_classifier_result(clf, task_key, data_key) vamp_report = vamp_res.extended_clf_report() # NOQA print('vamp roc = {}'.format(vamp_res.roc_score())) return vamp_res def main(): parser = _auto_argparse(fit) args, unknown = parser.parse_known_args() ns = args.__dict__.copy() fit(**ns) if __name__ == '__main__': main()
[ "ubelt.ProgIter", "argparse.ArgumentParser", "glob.glob", "pandas.set_option", "torch.load", "torch.Tensor", "numpy.linspace", "ubelt.ensuredir", "pandas.concat", "parse.log.setLevel", "ubelt.argval", "xdoctest.docscrape_google.split_google_docblocks", "netharn.examples.siam_ibeis.setup_harness", "netharn.examples.siam_ibeis.randomized_ibeis_dset", "parse.parse", "netharn.examples.siam_ibeis.SiameseLP", "ibeis.algo.verif.vsone.OneVsOneProblem.from_labeled_aidpairs", "inspect.getargspec", "numpy.array", "collections.OrderedDict", "os.path.expanduser", "ibeis.algo.verif.vsone.clf_helpers.ClfResult", "xdoctest.docscrape_google.parse_google_args" ]
[((545, 569), 'inspect.getargspec', 'inspect.getargspec', (['func'], {}), '(func)\n', (563, 569), False, 'import inspect\n'), ((1006, 1115), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(description=description, formatter_class=argparse.\n ArgumentDefaultsHelpFormatter)\n', (1029, 1115), False, 'import argparse\n'), ((2907, 2929), 'parse.log.setLevel', 'parse.log.setLevel', (['(30)'], {}), '(30)\n', (2925, 2929), False, 'import parse\n'), ((3091, 3130), 'ubelt.argval', 'ub.argval', (['"""--db"""'], {'default': '"""GZ_Master1"""'}), "('--db', default='GZ_Master1')\n", (3100, 3130), True, 'import ubelt as ub\n'), ((3142, 3181), 'ubelt.argval', 'ub.argval', (['"""--nice"""'], {'default': '"""untitled"""'}), "('--nice', default='untitled')\n", (3151, 3181), True, 'import ubelt as ub\n'), ((3261, 3299), 'netharn.examples.siam_ibeis.randomized_ibeis_dset', 'randomized_ibeis_dset', (['dbname'], {'dim': 'dim'}), '(dbname, dim=dim)\n', (3282, 3299), False, 'from netharn.examples.siam_ibeis import randomized_ibeis_dset\n'), ((3750, 3867), 'ibeis.algo.verif.vsone.OneVsOneProblem.from_labeled_aidpairs', 'vsone.OneVsOneProblem.from_labeled_aidpairs', (['ibs', 'labeled_aid_pairs'], {'class_names': 'class_names', 'task_name': 'task_name'}), '(ibs, labeled_aid_pairs,\n class_names=class_names, task_name=task_name)\n', (3793, 3867), False, 'from ibeis.algo.verif import vsone\n'), ((4035, 4157), 'ibeis.algo.verif.vsone.OneVsOneProblem.from_labeled_aidpairs', 'vsone.OneVsOneProblem.from_labeled_aidpairs', (['ibs', 'test_labeled_aid_pairs'], {'class_names': 'class_names', 'task_name': 'task_name'}), '(ibs, test_labeled_aid_pairs,\n class_names=class_names, task_name=task_name)\n', (4078, 4157), False, 'from ibeis.algo.verif import vsone\n'), ((4190, 4218), 'netharn.examples.siam_ibeis.setup_harness', 'setup_harness', ([], {'dbname': 'dbname'}), '(dbname=dbname)\n', (4203, 4218), False, 'from netharn.examples.siam_ibeis import SiameseLP, SiamHarness, setup_harness\n'), ((4529, 4588), 'netharn.examples.siam_ibeis.SiameseLP', 'SiameseLP', ([], {'p': '(2)', 'branch': 'branch', 'input_shape': '(1, 3, dim, dim)'}), '(p=2, branch=branch, input_shape=(1, 3, dim, dim))\n', (4538, 4588), False, 'from netharn.examples.siam_ibeis import SiameseLP, SiamHarness, setup_harness\n'), ((4917, 4951), 'ubelt.argval', 'ub.argval', (['"""--epoch"""'], {'default': 'None'}), "('--epoch', default=None)\n", (4926, 4951), True, 'import ubelt as ub\n'), ((5705, 5738), 'ubelt.argval', 'ub.argval', (['"""--thres"""'], {'default': '(0.5)'}), "('--thres', default=0.5)\n", (5714, 5738), True, 'import ubelt as ub\n'), ((5782, 5825), 'numpy.linspace', 'np.linspace', (['(thres - 0.05)', '(thres + 0.05)', '(41)'], {}), '(thres - 0.05, thres + 0.05, 41)\n', (5793, 5825), True, 'import numpy as np\n'), ((8892, 8914), 'parse.log.setLevel', 'parse.log.setLevel', (['(30)'], {}), '(30)\n', (8910, 8914), False, 'import parse\n'), ((8928, 8967), 'ubelt.argval', 'ub.argval', (['"""--db"""'], {'default': '"""GZ_Master1"""'}), "('--db', default='GZ_Master1')\n", (8937, 8967), True, 'import ubelt as ub\n'), ((8979, 9018), 'ubelt.argval', 'ub.argval', (['"""--nice"""'], {'default': '"""untitled"""'}), "('--nice', default='untitled')\n", (8988, 9018), True, 'import ubelt as ub\n'), ((9483, 9516), 'ubelt.argval', 'ub.argval', (['"""--thres"""'], {'default': '(0.5)'}), "('--thres', default=0.5)\n", (9492, 9516), True, 'import ubelt as ub\n'), ((9631, 9695), 'torch.load', 'torch.load', (['load_path'], {'map_location': '(lambda storage, loc: storage)'}), '(load_path, map_location=lambda storage, loc: storage)\n', (9641, 9695), False, 'import torch\n'), ((9801, 9814), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9812, 9814), False, 'from collections import OrderedDict\n'), ((10318, 10374), 'ubelt.ProgIter', 'ub.ProgIter', (['pblm_test.samples.index'], {'label': '"""predicting"""'}), "(pblm_test.samples.index, label='predicting')\n", (10329, 10374), True, 'import ubelt as ub\n'), ((10911, 10944), 'ubelt.argval', 'ub.argval', (['"""--thres"""'], {'default': '(0.5)'}), "('--thres', default=0.5)\n", (10920, 10944), True, 'import ubelt as ub\n'), ((11134, 11173), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', 'None'], {}), "('display.max_rows', None)\n", (11147, 11173), True, 'import pandas as pd\n'), ((11654, 11683), 'ibeis.algo.verif.vsone.clf_helpers.ClfResult', 'vsone.clf_helpers.ClfResult', ([], {}), '()\n', (11681, 11683), False, 'from ibeis.algo.verif import vsone\n'), ((12116, 12170), 'pandas.concat', 'pd.concat', (['[sorted_df, target_sort]'], {'axis': '(1)', 'sort': '(True)'}), '([sorted_df, target_sort], axis=1, sort=True)\n', (12125, 12170), True, 'import pandas as pd\n'), ((12201, 12235), 'ubelt.argval', 'ub.argval', (['"""--epoch"""'], {'default': 'None'}), "('--epoch', default=None)\n", (12210, 12235), True, 'import ubelt as ub\n'), ((12984, 13014), 'ubelt.ensuredir', 'ub.ensuredir', (["(workdir, 'clf')"], {}), "((workdir, 'clf'))\n", (12996, 13014), True, 'import ubelt as ub\n'), ((3363, 3418), 'os.path.expanduser', 'os.path.expanduser', (["('~/data/work/siam-ibeis2/' + dbname)"], {}), "('~/data/work/siam-ibeis2/' + dbname)\n", (3381, 3418), False, 'import os\n'), ((6079, 6118), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', 'None'], {}), "('display.max_rows', None)\n", (6092, 6118), True, 'import pandas as pd\n'), ((6596, 6625), 'ibeis.algo.verif.vsone.clf_helpers.ClfResult', 'vsone.clf_helpers.ClfResult', ([], {}), '()\n', (6623, 6625), False, 'from ibeis.algo.verif import vsone\n'), ((7098, 7141), 'pandas.concat', 'pd.concat', (['[sorted_df, target_sort]'], {'axis': '(1)'}), '([sorted_df, target_sort], axis=1)\n', (7107, 7141), True, 'import pandas as pd\n'), ((8063, 8104), 'glob.glob', 'glob.glob', (["(train_dpath + '/*/_epoch_*.pt')"], {}), "(train_dpath + '/*/_epoch_*.pt')\n", (8072, 8104), False, 'import glob\n'), ((9142, 9197), 'os.path.expanduser', 'os.path.expanduser', (["('~/data/work/siam-ibeis2/' + dbname)"], {}), "('~/data/work/siam-ibeis2/' + dbname)\n", (9160, 9197), False, 'import os\n'), ((10819, 10834), 'numpy.array', 'np.array', (['dists'], {}), '(dists)\n', (10827, 10834), True, 'import numpy as np\n'), ((898, 930), 'xdoctest.docscrape_google.parse_google_args', 'scrape.parse_google_args', (['docstr'], {}), '(docstr)\n', (922, 930), True, 'from xdoctest import docscrape_google as scrape\n'), ((2742, 2765), 'inspect.getargspec', 'inspect.getargspec', (['fit'], {}), '(fit)\n', (2760, 2765), False, 'import inspect\n'), ((5228, 5269), 'glob.glob', 'glob.glob', (["(train_dpath + '/*/_epoch_*.pt')"], {}), "(train_dpath + '/*/_epoch_*.pt')\n", (5237, 5269), False, 'import glob\n'), ((8204, 8248), 'glob.glob', 'glob.glob', (["(train_dpath + '/best_snapshot.pt')"], {}), "(train_dpath + '/best_snapshot.pt')\n", (8213, 8248), False, 'import glob\n'), ((11276, 11302), 'numpy.array', 'np.array', (['[p_diff, p_same]'], {}), '([p_diff, p_same])\n', (11284, 11302), True, 'import numpy as np\n'), ((6225, 6251), 'numpy.array', 'np.array', (['[p_diff, p_same]'], {}), '([p_diff, p_same])\n', (6233, 6251), True, 'import numpy as np\n'), ((10997, 11031), 'torch.Tensor', 'torch.Tensor', (['(-(dist_arr - margin))'], {}), '(-(dist_arr - margin))\n', (11009, 11031), False, 'import torch\n'), ((765, 802), 'xdoctest.docscrape_google.split_google_docblocks', 'scrape.split_google_docblocks', (['docstr'], {}), '(docstr)\n', (794, 802), True, 'from xdoctest import docscrape_google as scrape\n'), ((5932, 5966), 'torch.Tensor', 'torch.Tensor', (['(-(dist_arr - margin))'], {}), '(-(dist_arr - margin))\n', (5944, 5966), False, 'import torch\n'), ((8380, 8420), 'parse.parse', 'parse.parse', (['"""{}_epoch_{num:d}.pt"""', 'path'], {}), "('{}_epoch_{num:d}.pt', path)\n", (8391, 8420), False, 'import parse\n')]
import numpy as np from opt_einsum import contract from ..symbol import Symbols from ..base import simplify a, b, c = Symbols("abc") def test_einsum(): contract("i->", np.array([a, b]), backend="qop") simplify( contract( "ijk,i->jk", c * np.ones([3, 3, 3]), np.array([a, b, c]), backend="qop" ) )
[ "numpy.array", "numpy.ones" ]
[((175, 191), 'numpy.array', 'np.array', (['[a, b]'], {}), '([a, b])\n', (183, 191), True, 'import numpy as np\n'), ((289, 308), 'numpy.array', 'np.array', (['[a, b, c]'], {}), '([a, b, c])\n', (297, 308), True, 'import numpy as np\n'), ((269, 287), 'numpy.ones', 'np.ones', (['[3, 3, 3]'], {}), '([3, 3, 3])\n', (276, 287), True, 'import numpy as np\n')]
""" 该DCGAN结构更加符合论文 """ import math import matplotlib.pyplot as plt import numpy as np from data_loader import DataLoader from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, \ Flatten, Dropout from keras.models import Sequential, Model from keras.optimizers import Adam import keras.backend as K from keras.backend.tensorflow_backend import set_session import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True set_session(tf.Session(config=config)) def discriminator_loss(y_true, y_pred): return y_true * K.mean(K.maximum(1. - y_pred, 0.), axis=-1) \ + (1. - y_true) * K.mean(K.maximum(1. + y_pred, 0.), axis=-1) def generator_loss(_, y_pred): return - K.mean(y_pred) class DCGAN: def __init__(self, image_shape=(64, 64, 1), dataset_name='mnist', latent_dim=100, gf_dim=64, df_dim=64): self.img_rows, self.img_cols, self.channels = self.img_shape = image_shape self.latent_dim = latent_dim self.gf_dim = gf_dim self.df_dim = df_dim self.dataset_name = dataset_name self.data_loader = DataLoader(dataset_name) optimizer = Adam(0.0002, 0.5) # Build discriminator self.discriminator = self.build_discriminator() self.discriminator.compile(optimizer=optimizer, loss=discriminator_loss, metrics=["accuracy"]) # Build generator self.generator = self.build_generator() z = Input(shape=(self.latent_dim,)) gen_img = self.generator(z) # For the combined model we will only train the generator self.discriminator.trainable = False # The discriminator takes generated images as input and determines validity valid = self.discriminator(gen_img) # The combined model (stacked generator and discriminator) # Trains the generator to fool the discriminator self.combined = Model(z, valid) self.combined.compile(optimizer=optimizer, loss=generator_loss) def build_generator(self): s_h, s_w = self.img_rows, self.img_cols s_h16, s_w16 = math.ceil(s_h / 16), math.ceil(s_w / 16) model = Sequential() model.add(Dense(self.gf_dim * 8 * s_h16 * s_h16, input_dim=self.latent_dim)) model.add(Reshape((s_h16, s_w16, self.gf_dim * 8))) model.add(BatchNormalization(momentum=0.8)) model.add(ReLU()) model.add(UpSampling2D()) model.add(Conv2D(self.gf_dim * 4, kernel_size=5, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(ReLU()) model.add(UpSampling2D()) model.add(Conv2D(self.gf_dim * 2, kernel_size=5, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(ReLU()) model.add(UpSampling2D()) model.add(Conv2D(self.gf_dim * 1, kernel_size=5, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(ReLU()) model.add(UpSampling2D()) model.add(Conv2D(self.channels, kernel_size=5, padding="same")) model.add(Activation('tanh')) print("Structure: generator") model.summary() noise = Input(shape=(self.latent_dim,)) img = model(noise) return Model(noise, img) def build_discriminator(self): model = Sequential() model.add(Conv2D(self.df_dim * 1, kernel_size=5, strides=2, input_shape=self.img_shape, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(self.df_dim * 2, kernel_size=5, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(self.df_dim * 4, kernel_size=5, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(self.df_dim * 8, kernel_size=5, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU()) model.add(Flatten()) model.add(Dense(1, activation=None)) print("Structure: discriminator") model.summary() img = Input(shape=self.img_shape) validity = model(img) return Model(img, validity) def train(self, epochs, batch_size=128, save_interval=50): valid = np.ones((batch_size, 1)) fake = np.zeros((batch_size, 1)) for epoch in range(epochs): imgs = self.data_loader.load_data(batch_size) # Train discriminator noise = np.random.normal(0, 1, (batch_size, self.latent_dim)) gen_imgs = self.generator.predict(noise) d_loss_real = self.discriminator.train_on_batch(imgs, valid) d_loss_fake = self.discriminator.train_on_batch(gen_imgs, fake) d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) # Train generator g_loss = self.combined.train_on_batch(noise, valid) # Plot the progress print("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100 * d_loss[1], g_loss)) # If at save interval => save generated image samples if epoch % save_interval == 0: self.save_imgs(epoch) def save_imgs(self, epoch): r, c = 5, 5 noise = np.random.normal(0, 1, (r * c, self.latent_dim)) gen_imgs = self.generator.predict(noise) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(r, c) cnt = 0 for i in range(r): for j in range(c): axs[i, j].imshow(gen_imgs[cnt, :, :, 0], cmap='gray') axs[i, j].axis('off') cnt += 1 fig.savefig(f"images/{self.dataset_name}/{epoch}.png") plt.close() if __name__ == '__main__': dcgan = DCGAN() dcgan.train(epochs=4000, batch_size=32, save_interval=50)
[ "numpy.ones", "keras.models.Model", "tensorflow.ConfigProto", "numpy.random.normal", "keras.layers.Input", "keras.layers.Reshape", "matplotlib.pyplot.close", "keras.layers.Flatten", "data_loader.DataLoader", "numpy.add", "matplotlib.pyplot.subplots", "keras.layers.LeakyReLU", "math.ceil", "tensorflow.Session", "keras.optimizers.Adam", "keras.layers.ReLU", "keras.layers.UpSampling2D", "keras.layers.Conv2D", "keras.backend.maximum", "keras.layers.BatchNormalization", "keras.layers.Activation", "numpy.zeros", "keras.layers.Dense", "keras.backend.mean", "keras.models.Sequential" ]
[((460, 476), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (474, 476), True, 'import tensorflow as tf\n'), ((528, 553), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (538, 553), True, 'import tensorflow as tf\n'), ((782, 796), 'keras.backend.mean', 'K.mean', (['y_pred'], {}), '(y_pred)\n', (788, 796), True, 'import keras.backend as K\n'), ((1169, 1193), 'data_loader.DataLoader', 'DataLoader', (['dataset_name'], {}), '(dataset_name)\n', (1179, 1193), False, 'from data_loader import DataLoader\n'), ((1215, 1232), 'keras.optimizers.Adam', 'Adam', (['(0.0002)', '(0.5)'], {}), '(0.0002, 0.5)\n', (1219, 1232), False, 'from keras.optimizers import Adam\n'), ((1511, 1542), 'keras.layers.Input', 'Input', ([], {'shape': '(self.latent_dim,)'}), '(shape=(self.latent_dim,))\n', (1516, 1542), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((1970, 1985), 'keras.models.Model', 'Model', (['z', 'valid'], {}), '(z, valid)\n', (1975, 1985), False, 'from keras.models import Sequential, Model\n'), ((2249, 2261), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2259, 2261), False, 'from keras.models import Sequential, Model\n'), ((3268, 3299), 'keras.layers.Input', 'Input', ([], {'shape': '(self.latent_dim,)'}), '(shape=(self.latent_dim,))\n', (3273, 3299), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3344, 3361), 'keras.models.Model', 'Model', (['noise', 'img'], {}), '(noise, img)\n', (3349, 3361), False, 'from keras.models import Sequential, Model\n'), ((3414, 3426), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3424, 3426), False, 'from keras.models import Sequential, Model\n'), ((4310, 4337), 'keras.layers.Input', 'Input', ([], {'shape': 'self.img_shape'}), '(shape=self.img_shape)\n', (4315, 4337), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4384, 4404), 'keras.models.Model', 'Model', (['img', 'validity'], {}), '(img, validity)\n', (4389, 4404), False, 'from keras.models import Sequential, Model\n'), ((4486, 4510), 'numpy.ones', 'np.ones', (['(batch_size, 1)'], {}), '((batch_size, 1))\n', (4493, 4510), True, 'import numpy as np\n'), ((4526, 4551), 'numpy.zeros', 'np.zeros', (['(batch_size, 1)'], {}), '((batch_size, 1))\n', (4534, 4551), True, 'import numpy as np\n'), ((5473, 5521), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(r * c, self.latent_dim)'], {}), '(0, 1, (r * c, self.latent_dim))\n', (5489, 5521), True, 'import numpy as np\n'), ((5663, 5681), 'matplotlib.pyplot.subplots', 'plt.subplots', (['r', 'c'], {}), '(r, c)\n', (5675, 5681), True, 'import matplotlib.pyplot as plt\n'), ((5960, 5971), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5969, 5971), True, 'import matplotlib.pyplot as plt\n'), ((2191, 2210), 'math.ceil', 'math.ceil', (['(s_h / 16)'], {}), '(s_h / 16)\n', (2200, 2210), False, 'import math\n'), ((2212, 2231), 'math.ceil', 'math.ceil', (['(s_w / 16)'], {}), '(s_w / 16)\n', (2221, 2231), False, 'import math\n'), ((2280, 2345), 'keras.layers.Dense', 'Dense', (['(self.gf_dim * 8 * s_h16 * s_h16)'], {'input_dim': 'self.latent_dim'}), '(self.gf_dim * 8 * s_h16 * s_h16, input_dim=self.latent_dim)\n', (2285, 2345), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2365, 2405), 'keras.layers.Reshape', 'Reshape', (['(s_h16, s_w16, self.gf_dim * 8)'], {}), '((s_h16, s_w16, self.gf_dim * 8))\n', (2372, 2405), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2425, 2457), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (2443, 2457), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2477, 2483), 'keras.layers.ReLU', 'ReLU', ([], {}), '()\n', (2481, 2483), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2503, 2517), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {}), '()\n', (2515, 2517), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2537, 2591), 'keras.layers.Conv2D', 'Conv2D', (['(self.gf_dim * 4)'], {'kernel_size': '(5)', 'padding': '"""same"""'}), "(self.gf_dim * 4, kernel_size=5, padding='same')\n", (2543, 2591), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2611, 2643), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (2629, 2643), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2663, 2669), 'keras.layers.ReLU', 'ReLU', ([], {}), '()\n', (2667, 2669), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2689, 2703), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {}), '()\n', (2701, 2703), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2723, 2777), 'keras.layers.Conv2D', 'Conv2D', (['(self.gf_dim * 2)'], {'kernel_size': '(5)', 'padding': '"""same"""'}), "(self.gf_dim * 2, kernel_size=5, padding='same')\n", (2729, 2777), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2797, 2829), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (2815, 2829), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2849, 2855), 'keras.layers.ReLU', 'ReLU', ([], {}), '()\n', (2853, 2855), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2875, 2889), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {}), '()\n', (2887, 2889), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2909, 2963), 'keras.layers.Conv2D', 'Conv2D', (['(self.gf_dim * 1)'], {'kernel_size': '(5)', 'padding': '"""same"""'}), "(self.gf_dim * 1, kernel_size=5, padding='same')\n", (2915, 2963), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((2983, 3015), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (3001, 3015), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3035, 3041), 'keras.layers.ReLU', 'ReLU', ([], {}), '()\n', (3039, 3041), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3061, 3075), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {}), '()\n', (3073, 3075), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3095, 3147), 'keras.layers.Conv2D', 'Conv2D', (['self.channels'], {'kernel_size': '(5)', 'padding': '"""same"""'}), "(self.channels, kernel_size=5, padding='same')\n", (3101, 3147), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3168, 3186), 'keras.layers.Activation', 'Activation', (['"""tanh"""'], {}), "('tanh')\n", (3178, 3186), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3445, 3543), 'keras.layers.Conv2D', 'Conv2D', (['(self.df_dim * 1)'], {'kernel_size': '(5)', 'strides': '(2)', 'input_shape': 'self.img_shape', 'padding': '"""same"""'}), "(self.df_dim * 1, kernel_size=5, strides=2, input_shape=self.\n img_shape, padding='same')\n", (3451, 3543), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3558, 3590), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (3576, 3590), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3610, 3630), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (3619, 3630), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3650, 3715), 'keras.layers.Conv2D', 'Conv2D', (['(self.df_dim * 2)'], {'kernel_size': '(5)', 'strides': '(2)', 'padding': '"""same"""'}), "(self.df_dim * 2, kernel_size=5, strides=2, padding='same')\n", (3656, 3715), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3735, 3767), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (3753, 3767), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3787, 3807), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (3796, 3807), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3827, 3892), 'keras.layers.Conv2D', 'Conv2D', (['(self.df_dim * 4)'], {'kernel_size': '(5)', 'strides': '(2)', 'padding': '"""same"""'}), "(self.df_dim * 4, kernel_size=5, strides=2, padding='same')\n", (3833, 3892), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3912, 3944), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (3930, 3944), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((3964, 3984), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (3973, 3984), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4004, 4069), 'keras.layers.Conv2D', 'Conv2D', (['(self.df_dim * 8)'], {'kernel_size': '(5)', 'strides': '(2)', 'padding': '"""same"""'}), "(self.df_dim * 8, kernel_size=5, strides=2, padding='same')\n", (4010, 4069), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4089, 4121), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'momentum': '(0.8)'}), '(momentum=0.8)\n', (4107, 4121), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4141, 4152), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {}), '()\n', (4150, 4152), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4172, 4181), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4179, 4181), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4201, 4226), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': 'None'}), '(1, activation=None)\n', (4206, 4226), False, 'from keras.layers import Dense, Reshape, Conv2D, UpSampling2D, BatchNormalization, ReLU, Activation, Input, LeakyReLU, Flatten, Dropout\n'), ((4702, 4755), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(batch_size, self.latent_dim)'], {}), '(0, 1, (batch_size, self.latent_dim))\n', (4718, 4755), True, 'import numpy as np\n'), ((624, 652), 'keras.backend.maximum', 'K.maximum', (['(1.0 - y_pred)', '(0.0)'], {}), '(1.0 - y_pred, 0.0)\n', (633, 652), True, 'import keras.backend as K\n'), ((699, 727), 'keras.backend.maximum', 'K.maximum', (['(1.0 + y_pred)', '(0.0)'], {}), '(1.0 + y_pred, 0.0)\n', (708, 727), True, 'import keras.backend as K\n'), ((4985, 5017), 'numpy.add', 'np.add', (['d_loss_real', 'd_loss_fake'], {}), '(d_loss_real, d_loss_fake)\n', (4991, 5017), True, 'import numpy as np\n')]
#imports from extra import common import time import csv,cv2, os import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import NearestNeighbors import pandas as pd os_path = str(os.path) if 'posix' in os_path: import posixpath as path elif 'nt' in os_path: import ntpath as path try: import tkinter as tk # for python 3 except: import Tkinter as tk # for python 2 def KNNTracker(self,frames, firstImage, smoothingmethod, segMeth, exp_parameter, updateconvax, progessbar, timelapse, tmp_dir, thre): """ K-Nearest Neighbor tracker """ startProcessingTime = time.clock() # initialize some variabiles trajectoriesX, trajectoriesY, cellIDs, frameID, t, track_history, CellMorph, ControlledVocabulary, \ track_age, consecutiveInvisibleCount, totalVisibleCount, lostTracks, frameTime = [ ], [], [], [], [], [], [], [], [], [], [], [], [] # do preprocessing followed by segmentation old_gray = common.call_preprocessing(firstImage, smoothingmethod) initialpoints, boxes, _, _, CellInfo = common.call_segmentation(segMeth, preImage=old_gray, rawImg=firstImage, minAreaSize=exp_parameter[2], maxAreaSize=exp_parameter[3], fixscale=exp_parameter[4], minDistance=exp_parameter[5], cellEstimate=exp_parameter[1], color=int(exp_parameter[6]), thre=thre) # if initialpoints.shape != (len(initialpoints), 1, 2): initialpoints = np.vstack(initialpoints) initialpoints = initialpoints.reshape(len(initialpoints), 1, 2) Initialtime = int(timelapse) noFrames = len(frames) # initialize track ids that corresponds to a detection/track firstDetections, updatedTrackIdx, updateDetections, old_trackIdx = [], [], [], [] for indi, row in enumerate(initialpoints): g, d = row.ravel() firstDetections.append([g, d]) updatedTrackIdx.append(indi) old_trackIdx.append(indi) # training a knn model for with K == 1 firstDetections = np.vstack(firstDetections) updateDetections = firstDetections neigh = NearestNeighbors(n_neighbors=2) neigh.fit(firstDetections) for i, frame in enumerate(frames): try: frameProcessingTime = time.clock() # images should be resized if graph-based segmentation method is # chosen if segMeth == 6: frame = resizeImage(frame) imagePlot = frame.copy() oldFrame = frame.copy() # show the progress bar progessbar.step(i * 2) good_new, morphImage, nextFrame = [], [], [] nextFrame = common.call_preprocessing(frame, smoothingmethod) p1, boxes, _, morphImage, CellInfo = common.call_segmentation(segMeth, preImage=nextFrame, rawImg=oldFrame, minAreaSize=exp_parameter[2], maxAreaSize=exp_parameter[3], fixscale=exp_parameter[4], minDistance=exp_parameter[5], cellEstimate=exp_parameter[1], color=int(exp_parameter[6]), thre=int(thre)) # different algorithms produce data with different shape and # formats p1 = np.array(p1) if p1.shape != (len(p1), 1, 2): if len(p1) > 1: p1 = np.vstack(p1) p1 = p1.reshape(len(p1), 1, 2) for _, row in enumerate(p1): C2, D2 = row.ravel() good_new.append([C2, D2]) # format a detection matrix to easy access good_new = np.vstack(good_new) # remove lost tracks if lostTracks: for lost in lostTracks: updateDetections[lost] = np.hstack([0, 0]) secondDetections = [] secondDetections = updateDetections neigh = NearestNeighbors(n_neighbors=2) neigh.fit(updateDetections) updatedTrackIdx = [] for tt, row in enumerate(good_new): z, y = row.ravel() test = np.hstack([z, y]) # find the closet point in the training data for a given data # points nearestpoint = neigh.kneighbors(np.array([test])) trackID = int(nearestpoint[1][0][0]) distance = nearestpoint[0][0][0] distance = np.float32(distance) if distance > int(exp_parameter[0]): new_idx = old_trackIdx[-1] + 1 updatedTrackIdx.append(new_idx) old_trackIdx.append(new_idx) updateDetections = np.vstack([updateDetections, test]) else: updatedTrackIdx.append(trackID) updateDetections[trackID] = np.hstack(test) secondDetections = np.int32(np.vstack(secondDetections)) for ii, (new, old) in enumerate(zip(good_new, secondDetections)): cellIdx = int(updatedTrackIdx[ii]) a, b = new.ravel() track_history.append([i, cellIdx, a, b, Initialtime]) # find a track age, remove tracks that has been lost for more # than 15 frames if CellInfo: tmp_inf = CellInfo[ii] tmpList = list(common.concatenateList([i, int(cellIdx), tmp_inf])) CellMorph.append(tmpList) # display some info to the user interface common.displayCoordinates(self,ii, a, b, Initialtime) dataFrame = pd.DataFrame(track_history, columns=[ 'frame_idx', 'track_no', 'x', 'y', 'time']) # review tracking common.drawStr(imagePlot, (20, 20), 'track count: %d' % len(good_new)) common.drawStr(morphImage, (20, 20), 'track count: %d' % len(good_new)) if dataFrame is not None: index_Values = dataFrame["track_no"] x_Values = dataFrame["x"] y_values = dataFrame["y"] frameIDx = dataFrame["frame_idx"] timeSeries = dataFrame["time"] # create a figure fig = plt.figure() plt.imshow(cv2.cvtColor(imagePlot, cv2.COLOR_BGR2RGB)) for _, value in enumerate(np.unique(index_Values)): tr_index = dataFrame.track_no[dataFrame.track_no == int(value)].index.tolist() xCoord = x_Values[tr_index] yCoord = y_values[tr_index] tmpFrameID = frameIDx[tr_index] timeStamp = timeSeries[tr_index] timeStamp = np.int32(timeStamp) tmpFrameID = np.int32(tmpFrameID) tmp_x = np.int32(xCoord) tmp_y = np.int32(yCoord) # smooth trajectories using gaussian filter sigma = 4 tmp_x = gaussian_filter1d(tmp_x, sigma) tmp_y = gaussian_filter1d(tmp_y, sigma) xx = tmp_x[-1] yy = tmp_y[-1] # remove tracks with that only appear a few times in the # entire dataset if i == noFrames - 1 and int(tmp_x.shape[0]) < 10: del tmp_x del tmp_y else: # plt.contour(secondlargestcontour, (0,), colors='g', linewidths=2) plt.text(xx, yy, "[%d]" % int(value), fontsize=5, color='yellow') cv2.putText(morphImage, "%d" % int(value), (int(xx) - 10, int(yy)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 3) plt.plot(tmp_x, tmp_y, 'r-', linewidth=1) if i == noFrames - 1 or i == noFrames: for _, (xx, yy, idx, tmx) in enumerate(zip(tmp_x, tmp_y, tmpFrameID, timeStamp)): trajectoriesX.append(xx) trajectoriesY.append(yy) cellIDs.append(value) frameID.append(idx) t.append(tmx) # check for lost tracks if i > 6: delTrack = common.deleteLostTracks(value, tmpFrameID, i) if delTrack: lostTracks.append(delTrack) plt.axis('off') mng = plt.get_current_fig_manager() mng.full_screen_toggle() tmp_img = path.join(str(tmp_dir[1]), 'frame{}.png'.format(i)) cv2.imwrite(path.join(str(tmp_dir[1]), 'morph{}.png'.format(i)), morphImage) fig.savefig(tmp_img, bbox_inches='tight') if i == noFrames - 1 or i == noFrames: fig.savefig(path.join(str(tmp_dir[0]), 'frame{}.png'.format(i)), bbox_inches='tight') cv2.imwrite(path.join(str(tmp_dir[1]), 'morph{}.png'.format(i)), morphImage) del fig # Now update the previous frame and previous points old_gray = nextFrame.copy() # handle image in the displace panel img = cv2.imread(tmp_img) r = 600.0 / img.shape[1] dim = (600, int(img.shape[0] * r)) # perform the actual resizing of the image and display it to the # panel resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) common.save_image(tmp_dir[3], '%d.gif' % i, resized) displayImage = tk.PhotoImage(file=str(path.join(tmp_dir[3], '%d.gif' % i))) updateconvax.displayImage = displayImage imagesprite = updateconvax.create_image( 266, 189, image=displayImage) updateconvax.update_idletasks() # Force redraw updateconvax.delete(imagesprite) if i == noFrames - 1 or i == noFrames: displayImage = tk.PhotoImage(file=str(path.join(tmp_dir[3], '%d.gif' % i))) updateconvax.displayImage = displayImage imagesprite = updateconvax.create_image( 263, 187, image=displayImage) ControlledVocabulary.append(CellMorph) Initialtime += int(timelapse) # time computation frameEndTime = time.clock() endTime = frameEndTime - frameProcessingTime frameTime.append([i, endTime]) except EOFError: continue # timelapse += Initialtime unpacked = zip(frameID, cellIDs, trajectoriesX, trajectoriesY, t) with open(path.join(tmp_dir[2], 'tracks.csv'), 'wt') as f1: writer = csv.writer(f1, lineterminator='\n') writer.writerow(('frameID', 'track_no', 'x', "y", "t",)) for value in unpacked: writer.writerow(value) f1.close() with open(path.join(tmp_dir[2], 'MorphFeatures.csv'), 'wt') as f2: writer = csv.writer(f2, lineterminator='\n') writer.writerow( ('frameID', 'detection_no', 'aspectRatio', 'extent', 'solidity', 'equivalentCellDiameter', 'integratedIntensity', 'meanIntensity', 'stdIntensity', 'maxIntensity', 'minIntensity', 'majorAxisLengthEllipse', 'minorAxisLengthEllipse', 'area', 'hullArea', 'perimeter', 'eccentricityEllipse', 'roundnessEllipse', 'circularity', 'areaPerimeterRatio', 'majorAxisLengthMoment', 'minorAxisLengthMoment', 'eccentricityMoment', 'roundnessMoment')) for value in CellMorph: writer.writerow(value) f2.close() tmp_endProcessingTime = time.time() endProcessingTime = tmp_endProcessingTime - startProcessingTime unpacked = zip(frameTime) with open(path.join(tmp_dir[2], 'timePerFrame.csv'), 'wt') as f3: writer = csv.writer(f3, lineterminator='\n') writer.writerow(('frameID', 'time',)) for value in frameTime: writer.writerow(value) f3.close() # write the feature extraction and tracking time lapse # opens file with name of "totalProcessingTime.txt" f = open("totalProcessingTime.txt", "w") f.write(str(endProcessingTime)) f.close()
[ "scipy.ndimage.gaussian_filter1d", "matplotlib.pyplot.figure", "extra.common.save_image", "numpy.unique", "pandas.DataFrame", "cv2.cvtColor", "time.clock", "sklearn.neighbors.NearestNeighbors", "numpy.int32", "cv2.resize", "ntpath.join", "csv.writer", "extra.common.displayCoordinates", "numpy.hstack", "numpy.vstack", "extra.common.deleteLostTracks", "matplotlib.pyplot.plot", "matplotlib.pyplot.get_current_fig_manager", "numpy.float32", "matplotlib.pyplot.axis", "time.time", "cv2.imread", "numpy.array", "extra.common.call_preprocessing" ]
[((655, 667), 'time.clock', 'time.clock', ([], {}), '()\n', (665, 667), False, 'import time\n'), ((1020, 1074), 'extra.common.call_preprocessing', 'common.call_preprocessing', (['firstImage', 'smoothingmethod'], {}), '(firstImage, smoothingmethod)\n', (1045, 1074), False, 'from extra import common\n'), ((2131, 2155), 'numpy.vstack', 'np.vstack', (['initialpoints'], {}), '(initialpoints)\n', (2140, 2155), True, 'import numpy as np\n'), ((2687, 2713), 'numpy.vstack', 'np.vstack', (['firstDetections'], {}), '(firstDetections)\n', (2696, 2713), True, 'import numpy as np\n'), ((2765, 2796), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', ([], {'n_neighbors': '(2)'}), '(n_neighbors=2)\n', (2781, 2796), False, 'from sklearn.neighbors import NearestNeighbors\n'), ((13032, 13043), 'time.time', 'time.time', ([], {}), '()\n', (13041, 13043), False, 'import time\n'), ((12114, 12149), 'csv.writer', 'csv.writer', (['f1'], {'lineterminator': '"""\n"""'}), "(f1, lineterminator='\\n')\n", (12124, 12149), False, 'import csv, cv2, os\n'), ((12386, 12421), 'csv.writer', 'csv.writer', (['f2'], {'lineterminator': '"""\n"""'}), "(f2, lineterminator='\\n')\n", (12396, 12421), False, 'import csv, cv2, os\n'), ((13230, 13265), 'csv.writer', 'csv.writer', (['f3'], {'lineterminator': '"""\n"""'}), "(f3, lineterminator='\\n')\n", (13240, 13265), False, 'import csv, cv2, os\n'), ((2915, 2927), 'time.clock', 'time.clock', ([], {}), '()\n', (2925, 2927), False, 'import time\n'), ((3324, 3373), 'extra.common.call_preprocessing', 'common.call_preprocessing', (['frame', 'smoothingmethod'], {}), '(frame, smoothingmethod)\n', (3349, 3373), False, 'from extra import common\n'), ((4520, 4532), 'numpy.array', 'np.array', (['p1'], {}), '(p1)\n', (4528, 4532), True, 'import numpy as np\n'), ((4898, 4917), 'numpy.vstack', 'np.vstack', (['good_new'], {}), '(good_new)\n', (4907, 4917), True, 'import numpy as np\n'), ((5185, 5216), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', ([], {'n_neighbors': '(2)'}), '(n_neighbors=2)\n', (5201, 5216), False, 'from sklearn.neighbors import NearestNeighbors\n'), ((6928, 7013), 'pandas.DataFrame', 'pd.DataFrame', (['track_history'], {'columns': "['frame_idx', 'track_no', 'x', 'y', 'time']"}), "(track_history, columns=['frame_idx', 'track_no', 'x', 'y', 'time']\n )\n", (6940, 7013), True, 'import pandas as pd\n'), ((9856, 9871), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (9864, 9871), True, 'import matplotlib.pyplot as plt\n'), ((9890, 9919), 'matplotlib.pyplot.get_current_fig_manager', 'plt.get_current_fig_manager', ([], {}), '()\n', (9917, 9919), True, 'import matplotlib.pyplot as plt\n'), ((10612, 10631), 'cv2.imread', 'cv2.imread', (['tmp_img'], {}), '(tmp_img)\n', (10622, 10631), False, 'import csv, cv2, os\n'), ((10836, 10886), 'cv2.resize', 'cv2.resize', (['img', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(img, dim, interpolation=cv2.INTER_AREA)\n', (10846, 10886), False, 'import csv, cv2, os\n'), ((10899, 10951), 'extra.common.save_image', 'common.save_image', (['tmp_dir[3]', "('%d.gif' % i)", 'resized'], {}), "(tmp_dir[3], '%d.gif' % i, resized)\n", (10916, 10951), False, 'from extra import common\n'), ((11759, 11771), 'time.clock', 'time.clock', ([], {}), '()\n', (11769, 11771), False, 'import time\n'), ((12047, 12082), 'ntpath.join', 'path.join', (['tmp_dir[2]', '"""tracks.csv"""'], {}), "(tmp_dir[2], 'tracks.csv')\n", (12056, 12082), True, 'import ntpath as path\n'), ((12312, 12354), 'ntpath.join', 'path.join', (['tmp_dir[2]', '"""MorphFeatures.csv"""'], {}), "(tmp_dir[2], 'MorphFeatures.csv')\n", (12321, 12354), True, 'import ntpath as path\n'), ((13157, 13198), 'ntpath.join', 'path.join', (['tmp_dir[2]', '"""timePerFrame.csv"""'], {}), "(tmp_dir[2], 'timePerFrame.csv')\n", (13166, 13198), True, 'import ntpath as path\n'), ((5398, 5415), 'numpy.hstack', 'np.hstack', (['[z, y]'], {}), '([z, y])\n', (5407, 5415), True, 'import numpy as np\n'), ((5714, 5734), 'numpy.float32', 'np.float32', (['distance'], {}), '(distance)\n', (5724, 5734), True, 'import numpy as np\n'), ((6195, 6222), 'numpy.vstack', 'np.vstack', (['secondDetections'], {}), '(secondDetections)\n', (6204, 6222), True, 'import numpy as np\n'), ((6849, 6903), 'extra.common.displayCoordinates', 'common.displayCoordinates', (['self', 'ii', 'a', 'b', 'Initialtime'], {}), '(self, ii, a, b, Initialtime)\n', (6874, 6903), False, 'from extra import common\n'), ((7552, 7564), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7562, 7564), True, 'import matplotlib.pyplot as plt\n'), ((4634, 4647), 'numpy.vstack', 'np.vstack', (['p1'], {}), '(p1)\n', (4643, 4647), True, 'import numpy as np\n'), ((5064, 5081), 'numpy.hstack', 'np.hstack', (['[0, 0]'], {}), '([0, 0])\n', (5073, 5081), True, 'import numpy as np\n'), ((5567, 5583), 'numpy.array', 'np.array', (['[test]'], {}), '([test])\n', (5575, 5583), True, 'import numpy as np\n'), ((5980, 6015), 'numpy.vstack', 'np.vstack', (['[updateDetections, test]'], {}), '([updateDetections, test])\n', (5989, 6015), True, 'import numpy as np\n'), ((6138, 6153), 'numpy.hstack', 'np.hstack', (['test'], {}), '(test)\n', (6147, 6153), True, 'import numpy as np\n'), ((7593, 7635), 'cv2.cvtColor', 'cv2.cvtColor', (['imagePlot', 'cv2.COLOR_BGR2RGB'], {}), '(imagePlot, cv2.COLOR_BGR2RGB)\n', (7605, 7635), False, 'import csv, cv2, os\n'), ((7680, 7703), 'numpy.unique', 'np.unique', (['index_Values'], {}), '(index_Values)\n', (7689, 7703), True, 'import numpy as np\n'), ((8038, 8057), 'numpy.int32', 'np.int32', (['timeStamp'], {}), '(timeStamp)\n', (8046, 8057), True, 'import numpy as np\n'), ((8091, 8111), 'numpy.int32', 'np.int32', (['tmpFrameID'], {}), '(tmpFrameID)\n', (8099, 8111), True, 'import numpy as np\n'), ((8140, 8156), 'numpy.int32', 'np.int32', (['xCoord'], {}), '(xCoord)\n', (8148, 8156), True, 'import numpy as np\n'), ((8185, 8201), 'numpy.int32', 'np.int32', (['yCoord'], {}), '(yCoord)\n', (8193, 8201), True, 'import numpy as np\n'), ((8325, 8356), 'scipy.ndimage.gaussian_filter1d', 'gaussian_filter1d', (['tmp_x', 'sigma'], {}), '(tmp_x, sigma)\n', (8342, 8356), False, 'from scipy.ndimage import gaussian_filter1d\n'), ((8385, 8416), 'scipy.ndimage.gaussian_filter1d', 'gaussian_filter1d', (['tmp_y', 'sigma'], {}), '(tmp_y, sigma)\n', (8402, 8416), False, 'from scipy.ndimage import gaussian_filter1d\n'), ((9113, 9154), 'matplotlib.pyplot.plot', 'plt.plot', (['tmp_x', 'tmp_y', '"""r-"""'], {'linewidth': '(1)'}), "(tmp_x, tmp_y, 'r-', linewidth=1)\n", (9121, 9154), True, 'import matplotlib.pyplot as plt\n'), ((9705, 9750), 'extra.common.deleteLostTracks', 'common.deleteLostTracks', (['value', 'tmpFrameID', 'i'], {}), '(value, tmpFrameID, i)\n', (9728, 9750), False, 'from extra import common\n'), ((11003, 11038), 'ntpath.join', 'path.join', (['tmp_dir[3]', "('%d.gif' % i)"], {}), "(tmp_dir[3], '%d.gif' % i)\n", (11012, 11038), True, 'import ntpath as path\n'), ((11404, 11439), 'ntpath.join', 'path.join', (['tmp_dir[3]', "('%d.gif' % i)"], {}), "(tmp_dir[3], '%d.gif' % i)\n", (11413, 11439), True, 'import ntpath as path\n')]
from .IO import read as _read from .QC import qc as _qc from .normalization import normalize as _normalize from .imputation import impute as _impute from .reshaping import reshape as _reshape from .modeling import buildmodel as _buildmodel from .interpretation import explain as _explain import pandas as pd import numpy as np import torch try: from captum.attr import visualization as viz except: import sys print("The module 'captum' is not found, please install first.") print("\tconda install captum -c pytorch") sys.exit(0) def _is_df(a): return True if type(a) is pd.DataFrame else False def dataset_split(dataset, labels, train_proportion=0.7): n_all = len(labels) n_select = round(n_all * train_proportion) idx_all = range(n_all) idx_train = np.random.choice(n_all, size=n_select, replace=False) idx_test = list(set(idx_all) - set(idx_train)) return dataset[idx_train], labels[idx_train], dataset[idx_test], labels[idx_test], idx_test class MData: def __init__(self): self.full_data = None self.train_data = None self.test_data = None self.full_X = None self.full_y = None self.train_X = None self.train_y = None self.test_X = None self.test_y = None self.model = None self.attributions = None self.features = None self.num2label = {} self.label2num = {} self.importances = None self.full_y_sample_id = None self.test_y_sample_id = None def __repr__(self) -> str: if _is_df(self.full_data): print(self.full_data) return str(self.full_data.shape) if _is_df(self.train_data): print(self.train_data) if _is_df(self.test_data): print(self.test_data) return 'Train: '+str(self.train_data.shape)+'; Test: '+str(self.test_data.shape) return '0' def read(self, fname, role='all', group_col='Group'): if role=='all': self.full_data = _read(fname) self.full_y = self.full_data[group_col] self.full_X = self.full_data.drop(columns=group_col) self.full_data = self.full_data elif role=='train': self.train_data = _read(fname) self.train_y = self.train_data[group_col] self.train_X = self.train_data.drop(columns=group_col) self.train_data = self.train_data elif role=='test': self.test_data = _read(fname) self.test_y = self.test_data[group_col] self.test_X = self.test_data.drop(columns=group_col) self.test_data = self.test_data else: print(f"Illegal role: {role}!") def qc(self, obs=0.3): bf, af = 0, 0 if _is_df(self.full_data): bf = len(list(self.full_X)) self.full_X = _qc(self.full_X, obs) af = len(list(self.full_X)) if _is_df(self.train_data): if _is_df(self.test_data): combined_X = pd.concat([self.train_X, self.test_X], sort=False) bf = len(list(combined_X)) combined_X = _qc(combined_X, obs) af = len(list(combined_X)) self.train_X = combined_X.loc[self.train_y.index,:] self.test_X = combined_X.loc[self.test_y.index,:] print(f'Number of features: from {bf} to {af}.') def normalize(self, method='log2p'): if _is_df(self.full_data): self.full_X = _normalize(self.full_X, method) if _is_df(self.train_data): if _is_df(self.test_data): self.train_X = _normalize(self.train_X, method) self.test_X = _normalize(self.test_X, method) def impute(self, method='none'): if _is_df(self.full_data): self.full_X = _impute(self.full_X, method) if _is_df(self.train_data): if _is_df(self.test_data): self.train_X = _impute(self.train_X, method) self.test_X = _impute(self.test_X, method) def reshape(self, method='auto', train_proportion=0.7): if _is_df(self.full_data): full_X, self.features = _reshape(self.full_X, method) uniq_label = list(set(self.full_y)) self.full_y_sample_id = self.full_y.index self.full_y = np.array([uniq_label.index(i) for i in self.full_y]) for i, v in enumerate(uniq_label): self.num2label[i] = v self.label2num[v] = i self.train_X, self.train_y, self.test_X, self.test_y, test_sample_index = dataset_split(full_X, self.full_y, train_proportion) self.test_y_sample_id = self.full_y_sample_id[test_sample_index] if _is_df(self.train_data): if _is_df(self.test_data): self.train_X, self.features = _reshape(self.train_X, method) self.test_X, self.features = _reshape(self.test_X, method) self.test_y_sample_id = self.test_y.index uniq_label = list(set(self.train_y)) self.train_y = np.array([uniq_label.index(i) for i in self.train_y]) self.test_y = np.array([uniq_label.index(i) for i in self.test_y]) for i, v in enumerate(uniq_label): self.num2label[i] = v self.label2num[v] = i def buildmodel(self, method='default', epochs=5): self.model = _buildmodel(self.train_X, self.train_y, self.test_X, self.test_y, method, self.train_X.shape[-1], len(self.num2label), epochs) def explain(self, target, method='IntegratedGradients'): if type(self.model) is not None: self.attributions = _explain(self.model, self.test_X, method, target=self.label2num[target]) attr = self.attributions.numpy() n_sample, n_width = attr.shape[0], attr.shape[-1] attr = attr.reshape(n_sample, n_width**2) imp = pd.DataFrame(data=attr, index=self.test_y_sample_id, columns=self.features) self.importances = imp cols = imp.apply(np.mean).abs().sort_values(ascending=False).head(20).index imp[cols].apply(np.mean).plot.bar().get_figure().savefig('TOP20_KeyFeatures.pdf', dpi=300) def save(self): self.importances.to_csv('FeatureImportance.tsv', sep='\t') attr_ig = np.transpose(self.attributions.squeeze().cpu().detach().numpy(), (1,2,0)) viz.visualize_image_attr(attr_ig, sign="all", cmap="viridis", show_colorbar=True, title="", alpha_overlay=1)[0].savefig('FeatureImportances.pdf', dpi=300)
[ "pandas.DataFrame", "captum.attr.visualization.visualize_image_attr", "numpy.random.choice", "pandas.concat", "sys.exit" ]
[((794, 847), 'numpy.random.choice', 'np.random.choice', (['n_all'], {'size': 'n_select', 'replace': '(False)'}), '(n_all, size=n_select, replace=False)\n', (810, 847), True, 'import numpy as np\n'), ((539, 550), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (547, 550), False, 'import sys\n'), ((6035, 6110), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'attr', 'index': 'self.test_y_sample_id', 'columns': 'self.features'}), '(data=attr, index=self.test_y_sample_id, columns=self.features)\n', (6047, 6110), True, 'import pandas as pd\n'), ((3081, 3131), 'pandas.concat', 'pd.concat', (['[self.train_X, self.test_X]'], {'sort': '(False)'}), '([self.train_X, self.test_X], sort=False)\n', (3090, 3131), True, 'import pandas as pd\n'), ((6513, 6626), 'captum.attr.visualization.visualize_image_attr', 'viz.visualize_image_attr', (['attr_ig'], {'sign': '"""all"""', 'cmap': '"""viridis"""', 'show_colorbar': '(True)', 'title': '""""""', 'alpha_overlay': '(1)'}), "(attr_ig, sign='all', cmap='viridis', show_colorbar\n =True, title='', alpha_overlay=1)\n", (6537, 6626), True, 'from captum.attr import visualization as viz\n')]
import librosa import pathlib import numpy as np from sklearn.model_selection import train_test_split def get_log_mel_spectrogram(path, n_fft, hop_length, n_mels): """ Extract log mel spectrogram 1) The length of the raw audio used is 8s long, 2) and then get the MelSpectrogram, 2) finally perform logarithmic operation to MelSpectrogram. Return: log_mel_spectrogram: """ y, sr = librosa.load(path, sr=16000, duration=8) file_length = np.size(y) if file_length != 128000: y = np.concatenate((y, np.zeros(128000-file_length)), axis=0) mel_spectrogram = librosa.feature.melspectrogram(y, sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels) log_mel_spectrogram = librosa.amplitude_to_db(mel_spectrogram) log_mel_spectrogram = log_mel_spectrogram.reshape((-1,)) return log_mel_spectrogram def classify_files(path): """ Classify emotion files and count them. Position 6 of emotion file name represent emotion which according to the label as follow: ( Emotion label letter used german word.) ---------------------------- letter | emotion(En) ------------+--------------- W | anger L | boredom E | disgust A | anxiety/fear F | happiness T | sadness ------------+--------------- Dataset preprocessing. Dataset data are divided into Return: dataset_dict: a dict structure with 'total' used to count all file number, and a sub-dict named 'file_dict' which including three keys, """ dataset_dict = { 'total': 0, 'file_dict': { 'W': {'represent': 0, 'count': 0, 'all_data': []}, 'L': {'represent': 1, 'count': 0, 'all_data': []}, 'E': {'represent': 2, 'count': 0, 'all_data': []}, 'A': {'represent': 3, 'count': 0, 'all_data': []}, 'F': {'represent': 4, 'count': 0, 'all_data': []}, 'T': {'represent': 5, 'count': 0, 'all_data': []}, 'N': {'represent': 6, 'count': 0, 'all_data': []} } } wav_path = pathlib.Path(path+'/wav') emotion_file_list = [str(file_name) for file_name in wav_path.glob('*.wav')] p = len(str(wav_path)) emotion_label_list = dataset_dict['file_dict'].keys() for emotion_label in emotion_label_list: emotion_classify_file_list = [letter for letter in emotion_file_list if letter[p + 6] == emotion_label] files_count = len(emotion_classify_file_list) dataset_dict['file_dict'][emotion_label]['count'] = files_count dataset_dict['total'] = dataset_dict['total'] + files_count emotion_data = [get_log_mel_spectrogram(path, n_fft=2048, hop_length=512, n_mels=128) for path in emotion_classify_file_list] dataset_dict['file_dict'][emotion_label]['all_data'] = emotion_data return dataset_dict def load_data(path): """ Returns: train_data_x, train_data_y: The emotion data and label of train data, which account for 80% in all. validation_data_x, validation_data_y: The emotion data and label of validation data, which account for 80% in train data. test_data_x, test_data_y: The emotion data and label of test data, which account for 20% in all. """ train_data_x = [] train_data_y = [] validation_data_x = [] validation_data_y = [] test_data_x = [] test_data_y = [] dataset_dict = classify_files(path) '''Split data set''' emotion_label_list = dataset_dict['file_dict'].keys() for emotion_label in emotion_label_list: x = dataset_dict['file_dict'][emotion_label]['all_data'] count = dataset_dict['file_dict'][emotion_label]['count'] y = np.full(count, dataset_dict['file_dict'][emotion_label]['represent']) x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8) x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, train_size=0.8) train_data_x = np.append(train_data_x, x_train) train_data_y = np.append(train_data_y, y_train) validation_data_x = np.append(validation_data_x, x_val) validation_data_y = np.append(validation_data_y, y_val) test_data_x = np.append(test_data_x, x_test) test_data_y = np.append(test_data_y, y_test) '''Reshape all data''' train_data_x = np.array(train_data_x).reshape(-1, 128, 251, 1) train_data_y = np.array(train_data_y) validation_data_x = np.array(validation_data_x).reshape(-1, 128, 251, 1) validation_data_y = np.array(validation_data_y) test_data_x = np.array(test_data_x).reshape(-1, 128, 251, 1) test_data_y = np.array(test_data_y) return train_data_x, train_data_y, validation_data_x, validation_data_y, test_data_x, test_data_y
[ "numpy.full", "numpy.size", "sklearn.model_selection.train_test_split", "numpy.zeros", "numpy.append", "pathlib.Path", "librosa.load", "numpy.array", "librosa.amplitude_to_db", "librosa.feature.melspectrogram" ]
[((436, 476), 'librosa.load', 'librosa.load', (['path'], {'sr': '(16000)', 'duration': '(8)'}), '(path, sr=16000, duration=8)\n', (448, 476), False, 'import librosa\n'), ((496, 506), 'numpy.size', 'np.size', (['y'], {}), '(y)\n', (503, 506), True, 'import numpy as np\n'), ((630, 722), 'librosa.feature.melspectrogram', 'librosa.feature.melspectrogram', (['y', 'sr'], {'n_fft': 'n_fft', 'hop_length': 'hop_length', 'n_mels': 'n_mels'}), '(y, sr, n_fft=n_fft, hop_length=hop_length,\n n_mels=n_mels)\n', (660, 722), False, 'import librosa\n'), ((745, 785), 'librosa.amplitude_to_db', 'librosa.amplitude_to_db', (['mel_spectrogram'], {}), '(mel_spectrogram)\n', (768, 785), False, 'import librosa\n'), ((2229, 2256), 'pathlib.Path', 'pathlib.Path', (["(path + '/wav')"], {}), "(path + '/wav')\n", (2241, 2256), False, 'import pathlib\n'), ((4631, 4653), 'numpy.array', 'np.array', (['train_data_y'], {}), '(train_data_y)\n', (4639, 4653), True, 'import numpy as np\n'), ((4755, 4782), 'numpy.array', 'np.array', (['validation_data_y'], {}), '(validation_data_y)\n', (4763, 4782), True, 'import numpy as np\n'), ((4866, 4887), 'numpy.array', 'np.array', (['test_data_y'], {}), '(test_data_y)\n', (4874, 4887), True, 'import numpy as np\n'), ((3922, 3991), 'numpy.full', 'np.full', (['count', "dataset_dict['file_dict'][emotion_label]['represent']"], {}), "(count, dataset_dict['file_dict'][emotion_label]['represent'])\n", (3929, 3991), True, 'import numpy as np\n'), ((4036, 4074), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'train_size': '(0.8)'}), '(x, y, train_size=0.8)\n', (4052, 4074), False, 'from sklearn.model_selection import train_test_split\n'), ((4117, 4167), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x_train', 'y_train'], {'train_size': '(0.8)'}), '(x_train, y_train, train_size=0.8)\n', (4133, 4167), False, 'from sklearn.model_selection import train_test_split\n'), ((4192, 4224), 'numpy.append', 'np.append', (['train_data_x', 'x_train'], {}), '(train_data_x, x_train)\n', (4201, 4224), True, 'import numpy as np\n'), ((4248, 4280), 'numpy.append', 'np.append', (['train_data_y', 'y_train'], {}), '(train_data_y, y_train)\n', (4257, 4280), True, 'import numpy as np\n'), ((4310, 4345), 'numpy.append', 'np.append', (['validation_data_x', 'x_val'], {}), '(validation_data_x, x_val)\n', (4319, 4345), True, 'import numpy as np\n'), ((4374, 4409), 'numpy.append', 'np.append', (['validation_data_y', 'y_val'], {}), '(validation_data_y, y_val)\n', (4383, 4409), True, 'import numpy as np\n'), ((4433, 4463), 'numpy.append', 'np.append', (['test_data_x', 'x_test'], {}), '(test_data_x, x_test)\n', (4442, 4463), True, 'import numpy as np\n'), ((4486, 4516), 'numpy.append', 'np.append', (['test_data_y', 'y_test'], {}), '(test_data_y, y_test)\n', (4495, 4516), True, 'import numpy as np\n'), ((4564, 4586), 'numpy.array', 'np.array', (['train_data_x'], {}), '(train_data_x)\n', (4572, 4586), True, 'import numpy as np\n'), ((4678, 4705), 'numpy.array', 'np.array', (['validation_data_x'], {}), '(validation_data_x)\n', (4686, 4705), True, 'import numpy as np\n'), ((4801, 4822), 'numpy.array', 'np.array', (['test_data_x'], {}), '(test_data_x)\n', (4809, 4822), True, 'import numpy as np\n'), ((568, 598), 'numpy.zeros', 'np.zeros', (['(128000 - file_length)'], {}), '(128000 - file_length)\n', (576, 598), True, 'import numpy as np\n')]
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. """ import os import numpy as np import matplotlib.pyplot as plt import logging from typing import * from typing import List from ilp_common_classes import * logger = logging.getLogger('matplotlib') logger.setLevel(logging.WARNING) def visulaize_results(path_to_output_data: str, var_param: List[float], results: np.array, results_name: str, var_name: EvalParam): ''' Plots figures representing the evaluation results of the ILP pipeline. ''' fig, ax = plt.subplots(1,1, figsize=(8,4)) #replace None weight_approx_resolution values with 0 if None in var_param: var_param = np.array(var_param) var_param = np.where(var_param == None, 0.0, var_param) #plot evaluation results ax.plot(var_param, np.mean(results, axis=-1), linestyle='--', marker='o') #customize figure plt.title(str(len(var_param))+' '+var_name.value+' vs. '+str(results_name)+' for '+str(len(results[0]))+ ' vois', y=1.08) plt.xlabel(var_name.value, color = 'red') plt.ylabel(str(results_name), color='red') plt.xticks(var_param.astype(np.double), color='blue') plt.grid(True) #save plot to output path fig.savefig(os.path.join(path_to_output_data, results_name+'_vs_'+var_name.value+'_plot.png'), bbox_inches='tight',dpi=300) plt.close(fig)
[ "os.path.join", "matplotlib.pyplot.close", "numpy.where", "numpy.array", "numpy.mean", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots", "logging.getLogger", "matplotlib.pyplot.grid" ]
[((243, 274), 'logging.getLogger', 'logging.getLogger', (['"""matplotlib"""'], {}), "('matplotlib')\n", (260, 274), False, 'import logging\n'), ((546, 580), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(8, 4)'}), '(1, 1, figsize=(8, 4))\n', (558, 580), True, 'import matplotlib.pyplot as plt\n'), ((1032, 1071), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['var_name.value'], {'color': '"""red"""'}), "(var_name.value, color='red')\n", (1042, 1071), True, 'import matplotlib.pyplot as plt\n'), ((1183, 1197), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (1191, 1197), True, 'import matplotlib.pyplot as plt\n'), ((1361, 1375), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (1370, 1375), True, 'import matplotlib.pyplot as plt\n'), ((683, 702), 'numpy.array', 'np.array', (['var_param'], {}), '(var_param)\n', (691, 702), True, 'import numpy as np\n'), ((723, 766), 'numpy.where', 'np.where', (['(var_param == None)', '(0.0)', 'var_param'], {}), '(var_param == None, 0.0, var_param)\n', (731, 766), True, 'import numpy as np\n'), ((824, 849), 'numpy.mean', 'np.mean', (['results'], {'axis': '(-1)'}), '(results, axis=-1)\n', (831, 849), True, 'import numpy as np\n'), ((1245, 1336), 'os.path.join', 'os.path.join', (['path_to_output_data', "(results_name + '_vs_' + var_name.value + '_plot.png')"], {}), "(path_to_output_data, results_name + '_vs_' + var_name.value +\n '_plot.png')\n", (1257, 1336), False, 'import os\n')]
#!/usr/bin/env python3 # # Author: <NAME> # Copyright 2015-present, NASA-JPL/Caltech # import os import glob import datetime import numpy as np import isce, isceobj import mroipac from mroipac.ampcor.Ampcor import Ampcor from isceobj.Alos2Proc.Alos2ProcPublic import topo from isceobj.Alos2Proc.Alos2ProcPublic import geo2rdr from isceobj.Alos2Proc.Alos2ProcPublic import waterBodyRadar from isceobj.Alos2Proc.Alos2ProcPublic import reformatGeometricalOffset from isceobj.Alos2Proc.Alos2ProcPublic import writeOffset from isceobj.Alos2Proc.Alos2ProcPublic import cullOffsets from isceobj.Alos2Proc.Alos2ProcPublic import computeOffsetFromOrbit from StackPulic import loadTrack from StackPulic import stackDateStatistics from StackPulic import acquisitionModesAlos2 def cmdLineParse(): ''' command line parser. ''' import sys import argparse parser = argparse.ArgumentParser(description='estimate offset between a pair of SLCs for a number of dates') parser.add_argument('-idir', dest='idir', type=str, required=True, help = 'input directory where data of each date (YYMMDD) is located. only folders are recognized') parser.add_argument('-ref_date', dest='ref_date', type=str, required=True, help = 'reference date. format: YYMMDD') parser.add_argument('-sec_date', dest='sec_date', type=str, nargs='+', default=[], help = 'a number of secondary dates seperated by blanks. format: YYMMDD YYMMDD YYMMDD. If provided, only estimate offsets of these dates') parser.add_argument('-wbd', dest='wbd', type=str, default=None, help = 'water body used to determine number of offsets in range and azimuth') parser.add_argument('-dem', dest='dem', type=str, default=None, help = 'if water body is provided, dem file must also be provided') parser.add_argument('-use_wbd_offset', dest='use_wbd_offset', action='store_true', default=False, help='use water body to dertermine number of matching offsets') parser.add_argument('-num_rg_offset', dest='num_rg_offset', type=int, nargs='+', action='append', default=[], help = 'number of offsets in range. format (e.g. 2 frames, 3 swaths): -num_rg_offset 11 12 13 -num_rg_offset 14 15 16') parser.add_argument('-num_az_offset', dest='num_az_offset', type=int, nargs='+', action='append', default=[], help = 'number of offsets in azimuth. format (e.g. 2 frames, 3 swaths): -num_az_offset 11 12 13 -num_az_offset 14 15 16') if len(sys.argv) <= 1: print('') parser.print_help() sys.exit(1) else: return parser.parse_args() if __name__ == '__main__': inps = cmdLineParse() #get user parameters from input idir = inps.idir dateReference = inps.ref_date dateSecondary = inps.sec_date wbd = inps.wbd dem = inps.dem useWbdForNumberOffsets = inps.use_wbd_offset numberOfOffsetsRangeInput = inps.num_rg_offset numberOfOffsetsAzimuthInput = inps.num_az_offset if wbd is not None: wbdFile = os.path.abspath(wbd) else: wbdFile = None if dem is not None: demFile = os.path.abspath(dem) else: demFile = None ####################################################### spotlightModes, stripmapModes, scansarNominalModes, scansarWideModes, scansarModes = acquisitionModesAlos2() warningMessage = '' #get date statistics dateDirs, dates, frames, swaths, dateIndexReference = stackDateStatistics(idir, dateReference) ndate = len(dates) nframe = len(frames) nswath = len(swaths) #load reference track referenceTrack = loadTrack(dateDirs[dateIndexReference], dates[dateIndexReference]) dateSecondaryFirst = None for idate in range(ndate): if idate == dateIndexReference: continue if dateSecondary != []: if dates[idate] not in dateSecondary: continue dateSecondaryFirst = dates[idate] break if dateSecondaryFirst is None: raise Exception('no secondary date is to be processed\n') #set number of matching points numberOfOffsetsRangeUsed = [[None for j in range(nswath)] for i in range(nframe)] numberOfOffsetsAzimuthUsed = [[None for j in range(nswath)] for i in range(nframe)] for i, frameNumber in enumerate(frames): frameDir = 'f{}_{}'.format(i+1, frameNumber) for j, swathNumber in enumerate(range(swaths[0], swaths[-1] + 1)): swathDir = 's{}'.format(swathNumber) print('determine number of range/azimuth offsets frame {}, swath {}'.format(frameNumber, swathNumber)) referenceSwath = referenceTrack.frames[i].swaths[j] #1. set initinial numbers #in case there are long time span pairs that have bad coherence ratio = np.sqrt(1.5) if referenceTrack.operationMode in scansarModes: numberOfOffsetsRange = int(10*ratio+0.5) numberOfOffsetsAzimuth = int(40*ratio+0.5) else: numberOfOffsetsRange = int(20*ratio+0.5) numberOfOffsetsAzimuth = int(20*ratio+0.5) #2. change the initial numbers using water body if useWbdForNumberOffsets and (wbdFile is not None) and (demFile is not None): numberRangeLooks=100 numberAzimuthLooks=100 #compute land ratio using topo module # latFile = 'lat_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # lonFile = 'lon_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # hgtFile = 'hgt_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # losFile = 'los_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # wbdRadarFile = 'wbd_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) latFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'lat.rdr') lonFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'lon.rdr') hgtFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'hgt.rdr') losFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'los.rdr') wbdRadarFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'wbd.rdr') topo(referenceSwath, referenceTrack, demFile, latFile, lonFile, hgtFile, losFile=losFile, incFile=None, mskFile=None, numberRangeLooks=numberRangeLooks, numberAzimuthLooks=numberAzimuthLooks, multilookTimeOffset=False) waterBodyRadar(latFile, lonFile, wbdFile, wbdRadarFile) wbdImg = isceobj.createImage() wbdImg.load(wbdRadarFile+'.xml') width = wbdImg.width length = wbdImg.length wbd = np.fromfile(wbdRadarFile, dtype=np.byte).reshape(length, width) landRatio = np.sum(wbd==0) / (length*width) if (landRatio <= 0.00125): print('\n\nWARNING: land too small for estimating slc offsets at frame {}, swath {}'.format(frameNumber, swathNumber)) print('proceed to use geometric offsets for forming interferogram') print('but please consider not using this swath\n\n') warningMessage += 'land too small for estimating slc offsets at frame {}, swath {}, use geometric offsets\n'.format(frameNumber, swathNumber) numberOfOffsetsRange = 0 numberOfOffsetsAzimuth = 0 else: #put the results on a grid with a specified interval interval = 0.2 axisRatio = int(np.sqrt(landRatio)/interval)*interval + interval if axisRatio > 1: axisRatio = 1 numberOfOffsetsRange = int(numberOfOffsetsRange/axisRatio) numberOfOffsetsAzimuth = int(numberOfOffsetsAzimuth/axisRatio) else: warningMessage += 'no water mask used to determine number of matching points. frame {} swath {}\n'.format(frameNumber, swathNumber) #3. user's settings if numberOfOffsetsRangeInput != []: numberOfOffsetsRange = numberOfOffsetsRangeInput[i][j] if numberOfOffsetsAzimuthInput != []: numberOfOffsetsAzimuth = numberOfOffsetsAzimuthInput[i][j] #4. save final results numberOfOffsetsRangeUsed[i][j] = numberOfOffsetsRange numberOfOffsetsAzimuthUsed[i][j] = numberOfOffsetsAzimuth #estimate offsets for idate in range(ndate): if idate == dateIndexReference: continue if dateSecondary != []: if dates[idate] not in dateSecondary: continue secondaryTrack = loadTrack(dateDirs[idate], dates[idate]) for i, frameNumber in enumerate(frames): frameDir = 'f{}_{}'.format(i+1, frameNumber) for j, swathNumber in enumerate(range(swaths[0], swaths[-1] + 1)): swathDir = 's{}'.format(swathNumber) print('estimating offset frame {}, swath {}'.format(frameNumber, swathNumber)) referenceDir = os.path.join(dateDirs[dateIndexReference], frameDir, swathDir) secondaryDir = os.path.join(dateDirs[idate], frameDir, swathDir) referenceSwath = referenceTrack.frames[i].swaths[j] secondarySwath = secondaryTrack.frames[i].swaths[j] #compute geometrical offsets if (wbdFile is not None) and (demFile is not None) and (numberOfOffsetsRangeUsed[i][j] == 0) and (numberOfOffsetsAzimuthUsed[i][j] == 0): #compute geomtricla offsets # latFile = 'lat_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # lonFile = 'lon_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # hgtFile = 'hgt_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # losFile = 'los_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # rgOffsetFile = 'rg_offset_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # azOffsetFile = 'az_offset_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # wbdRadarFile = 'wbd_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) latFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'lat.rdr') lonFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'lon.rdr') hgtFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'hgt.rdr') losFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'los.rdr') #put them in current date directory rgOffsetFile = os.path.join(idir, dates[idate], frameDir, swathDir, 'rg_offset.rdr') azOffsetFile = os.path.join(idir, dates[idate], frameDir, swathDir, 'az_offset.rdr') wbdRadarFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'wbd.rdr') geo2rdr(secondarySwath, secondaryTrack, latFile, lonFile, hgtFile, rgOffsetFile, azOffsetFile, numberRangeLooks=numberRangeLooks, numberAzimuthLooks=numberAzimuthLooks, multilookTimeOffset=False) reformatGeometricalOffset(rgOffsetFile, azOffsetFile, os.path.join(secondaryDir, 'cull.off'), rangeStep=numberRangeLooks, azimuthStep=numberAzimuthLooks, maximumNumberOfOffsets=2000) os.remove(rgOffsetFile) os.remove(rgOffsetFile+'.vrt') os.remove(rgOffsetFile+'.xml') os.remove(azOffsetFile) os.remove(azOffsetFile+'.vrt') os.remove(azOffsetFile+'.xml') #estimate offsets using ampcor else: ampcor = Ampcor(name='insarapp_slcs_ampcor') ampcor.configure() mSLC = isceobj.createSlcImage() mSLC.load(os.path.join(referenceDir, dates[dateIndexReference]+'.slc.xml')) mSLC.filename = os.path.join(referenceDir, dates[dateIndexReference]+'.slc') mSLC.extraFilename = os.path.join(referenceDir, dates[dateIndexReference]+'.slc.vrt') mSLC.setAccessMode('read') mSLC.createImage() sSLC = isceobj.createSlcImage() sSLC.load(os.path.join(secondaryDir, dates[idate]+'.slc.xml')) sSLC.filename = os.path.join(secondaryDir, dates[idate]+'.slc') sSLC.extraFilename = os.path.join(secondaryDir, dates[idate]+'.slc.vrt') sSLC.setAccessMode('read') sSLC.createImage() ampcor.setImageDataType1('complex') ampcor.setImageDataType2('complex') ampcor.setReferenceSlcImage(mSLC) ampcor.setSecondarySlcImage(sSLC) #MATCH REGION #compute an offset at image center to use rgoff, azoff = computeOffsetFromOrbit(referenceSwath, referenceTrack, secondarySwath, secondaryTrack, referenceSwath.numberOfSamples * 0.5, referenceSwath.numberOfLines * 0.5) #it seems that we cannot use 0, haven't look into the problem if rgoff == 0: rgoff = 1 if azoff == 0: azoff = 1 firstSample = 1 if rgoff < 0: firstSample = int(35 - rgoff) firstLine = 1 if azoff < 0: firstLine = int(35 - azoff) ampcor.setAcrossGrossOffset(rgoff) ampcor.setDownGrossOffset(azoff) ampcor.setFirstSampleAcross(firstSample) ampcor.setLastSampleAcross(mSLC.width) ampcor.setNumberLocationAcross(numberOfOffsetsRangeUsed[i][j]) ampcor.setFirstSampleDown(firstLine) ampcor.setLastSampleDown(mSLC.length) ampcor.setNumberLocationDown(numberOfOffsetsAzimuthUsed[i][j]) #MATCH PARAMETERS #full-aperture mode if referenceTrack.operationMode in scansarModes: ampcor.setWindowSizeWidth(64) ampcor.setWindowSizeHeight(512) #note this is the half width/length of search area, number of resulting correlation samples: 32*2+1 ampcor.setSearchWindowSizeWidth(32) ampcor.setSearchWindowSizeHeight(32) #triggering full-aperture mode matching ampcor.setWinsizeFilt(8) ampcor.setOversamplingFactorFilt(64) #regular mode else: ampcor.setWindowSizeWidth(64) ampcor.setWindowSizeHeight(64) ampcor.setSearchWindowSizeWidth(32) ampcor.setSearchWindowSizeHeight(32) #REST OF THE STUFF ampcor.setAcrossLooks(1) ampcor.setDownLooks(1) ampcor.setOversamplingFactor(64) ampcor.setZoomWindowSize(16) #1. The following not set #Matching Scale for Sample/Line Directions (-) = 1. 1. #should add the following in Ampcor.py? #if not set, in this case, Ampcor.py'value is also 1. 1. #ampcor.setScaleFactorX(1.) #ampcor.setScaleFactorY(1.) #MATCH THRESHOLDS AND DEBUG DATA #2. The following not set #in roi_pac the value is set to 0 1 #in isce the value is set to 0.001 1000.0 #SNR and Covariance Thresholds (-) = {s1} {s2} #should add the following in Ampcor? #THIS SHOULD BE THE ONLY THING THAT IS DIFFERENT FROM THAT OF ROI_PAC #ampcor.setThresholdSNR(0) #ampcor.setThresholdCov(1) ampcor.setDebugFlag(False) ampcor.setDisplayFlag(False) #in summary, only two things not set which are indicated by 'The following not set' above. #run ampcor ampcor.ampcor() offsets = ampcor.getOffsetField() ampcorOffsetFile = os.path.join(secondaryDir, 'ampcor.off') writeOffset(offsets, ampcorOffsetFile) #finalize image, and re-create it #otherwise the file pointer is still at the end of the image mSLC.finalizeImage() sSLC.finalizeImage() ########################################## #3. cull offsets ########################################## refinedOffsets = cullOffsets(offsets) if refinedOffsets == None: print('******************************************************************') print('WARNING: There are not enough offsets left, so we are forced to') print(' use offset without culling. frame {}, swath {}'.format(frameNumber, swathNumber)) print('******************************************************************') warningMessage += 'not enough offsets left, use offset without culling. frame {} swath {}'.format(frameNumber, swathNumber) refinedOffsets = offsets cullOffsetFile = os.path.join(secondaryDir, 'cull.off') writeOffset(refinedOffsets, cullOffsetFile) #os.chdir('../') #os.chdir('../') #delete geometry files for i, frameNumber in enumerate(frames): frameDir = 'f{}_{}'.format(i+1, frameNumber) for j, swathNumber in enumerate(range(swaths[0], swaths[-1] + 1)): swathDir = 's{}'.format(swathNumber) if (wbdFile is not None) and (demFile is not None): # latFile = 'lat_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # lonFile = 'lon_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # hgtFile = 'hgt_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # losFile = 'los_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) # wbdRadarFile = 'wbd_f{}_{}_s{}.rdr'.format(i+1, frameNumber, swathNumber) latFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'lat.rdr') lonFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'lon.rdr') hgtFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'hgt.rdr') losFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'los.rdr') wbdRadarFile = os.path.join(idir, dateSecondaryFirst, frameDir, swathDir, 'wbd.rdr') os.remove(latFile) os.remove(latFile+'.vrt') os.remove(latFile+'.xml') os.remove(lonFile) os.remove(lonFile+'.vrt') os.remove(lonFile+'.xml') os.remove(hgtFile) os.remove(hgtFile+'.vrt') os.remove(hgtFile+'.xml') os.remove(losFile) os.remove(losFile+'.vrt') os.remove(losFile+'.xml') os.remove(wbdRadarFile) os.remove(wbdRadarFile+'.vrt') os.remove(wbdRadarFile+'.xml') numberOfOffsetsUsedTxt = '\nnumber of offsets in cross correlation:\n' numberOfOffsetsUsedTxt += ' frame swath range azimuth\n' numberOfOffsetsUsedTxt += '============================================\n' for i, frameNumber in enumerate(frames): frameDir = 'f{}_{}'.format(i+1, frameNumber) for j, swathNumber in enumerate(range(swaths[0], swaths[-1] + 1)): swathDir = 's{}'.format(swathNumber) numberOfOffsetsUsedTxt += ' {} {} {} {}\n'.format(frameNumber, swathNumber, numberOfOffsetsRangeUsed[i][j], numberOfOffsetsAzimuthUsed[i][j]) print(numberOfOffsetsUsedTxt) if warningMessage != '': print('\n'+warningMessage+'\n')
[ "os.remove", "numpy.sum", "argparse.ArgumentParser", "mroipac.ampcor.Ampcor.Ampcor", "os.path.join", "os.path.abspath", "isceobj.Alos2Proc.Alos2ProcPublic.geo2rdr", "StackPulic.loadTrack", "isceobj.Alos2Proc.Alos2ProcPublic.topo", "isceobj.Alos2Proc.Alos2ProcPublic.cullOffsets", "StackPulic.acquisitionModesAlos2", "isceobj.createImage", "sys.exit", "isceobj.Alos2Proc.Alos2ProcPublic.computeOffsetFromOrbit", "numpy.fromfile", "isceobj.Alos2Proc.Alos2ProcPublic.writeOffset", "StackPulic.stackDateStatistics", "isceobj.createSlcImage", "isceobj.Alos2Proc.Alos2ProcPublic.waterBodyRadar", "numpy.sqrt" ]
[((881, 985), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""estimate offset between a pair of SLCs for a number of dates"""'}), "(description=\n 'estimate offset between a pair of SLCs for a number of dates')\n", (904, 985), False, 'import argparse\n'), ((3369, 3392), 'StackPulic.acquisitionModesAlos2', 'acquisitionModesAlos2', ([], {}), '()\n', (3390, 3392), False, 'from StackPulic import acquisitionModesAlos2\n'), ((3512, 3552), 'StackPulic.stackDateStatistics', 'stackDateStatistics', (['idir', 'dateReference'], {}), '(idir, dateReference)\n', (3531, 3552), False, 'from StackPulic import stackDateStatistics\n'), ((3675, 3741), 'StackPulic.loadTrack', 'loadTrack', (['dateDirs[dateIndexReference]', 'dates[dateIndexReference]'], {}), '(dateDirs[dateIndexReference], dates[dateIndexReference])\n', (3684, 3741), False, 'from StackPulic import loadTrack\n'), ((2593, 2604), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2601, 2604), False, 'import sys\n'), ((3068, 3088), 'os.path.abspath', 'os.path.abspath', (['wbd'], {}), '(wbd)\n', (3083, 3088), False, 'import os\n'), ((3164, 3184), 'os.path.abspath', 'os.path.abspath', (['dem'], {}), '(dem)\n', (3179, 3184), False, 'import os\n'), ((8997, 9037), 'StackPulic.loadTrack', 'loadTrack', (['dateDirs[idate]', 'dates[idate]'], {}), '(dateDirs[idate], dates[idate])\n', (9006, 9037), False, 'from StackPulic import loadTrack\n'), ((4876, 4888), 'numpy.sqrt', 'np.sqrt', (['(1.5)'], {}), '(1.5)\n', (4883, 4888), True, 'import numpy as np\n'), ((5950, 6019), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""lat.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'lat.rdr')\n", (5962, 6019), False, 'import os\n'), ((6046, 6115), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""lon.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'lon.rdr')\n", (6058, 6115), False, 'import os\n'), ((6142, 6211), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""hgt.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'hgt.rdr')\n", (6154, 6211), False, 'import os\n'), ((6238, 6307), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""los.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'los.rdr')\n", (6250, 6307), False, 'import os\n'), ((6339, 6408), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""wbd.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'wbd.rdr')\n", (6351, 6408), False, 'import os\n'), ((6426, 6657), 'isceobj.Alos2Proc.Alos2ProcPublic.topo', 'topo', (['referenceSwath', 'referenceTrack', 'demFile', 'latFile', 'lonFile', 'hgtFile'], {'losFile': 'losFile', 'incFile': 'None', 'mskFile': 'None', 'numberRangeLooks': 'numberRangeLooks', 'numberAzimuthLooks': 'numberAzimuthLooks', 'multilookTimeOffset': '(False)'}), '(referenceSwath, referenceTrack, demFile, latFile, lonFile, hgtFile,\n losFile=losFile, incFile=None, mskFile=None, numberRangeLooks=\n numberRangeLooks, numberAzimuthLooks=numberAzimuthLooks,\n multilookTimeOffset=False)\n', (6430, 6657), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import topo\n'), ((6703, 6758), 'isceobj.Alos2Proc.Alos2ProcPublic.waterBodyRadar', 'waterBodyRadar', (['latFile', 'lonFile', 'wbdFile', 'wbdRadarFile'], {}), '(latFile, lonFile, wbdFile, wbdRadarFile)\n', (6717, 6758), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import waterBodyRadar\n'), ((6785, 6806), 'isceobj.createImage', 'isceobj.createImage', ([], {}), '()\n', (6804, 6806), False, 'import isce, isceobj\n'), ((9404, 9466), 'os.path.join', 'os.path.join', (['dateDirs[dateIndexReference]', 'frameDir', 'swathDir'], {}), '(dateDirs[dateIndexReference], frameDir, swathDir)\n', (9416, 9466), False, 'import os\n'), ((9498, 9547), 'os.path.join', 'os.path.join', (['dateDirs[idate]', 'frameDir', 'swathDir'], {}), '(dateDirs[idate], frameDir, swathDir)\n', (9510, 9547), False, 'import os\n'), ((19329, 19398), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""lat.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'lat.rdr')\n", (19341, 19398), False, 'import os\n'), ((19425, 19494), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""lon.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'lon.rdr')\n", (19437, 19494), False, 'import os\n'), ((19521, 19590), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""hgt.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'hgt.rdr')\n", (19533, 19590), False, 'import os\n'), ((19617, 19686), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""los.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'los.rdr')\n", (19629, 19686), False, 'import os\n'), ((19718, 19787), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""wbd.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'wbd.rdr')\n", (19730, 19787), False, 'import os\n'), ((19805, 19823), 'os.remove', 'os.remove', (['latFile'], {}), '(latFile)\n', (19814, 19823), False, 'import os\n'), ((19840, 19867), 'os.remove', 'os.remove', (["(latFile + '.vrt')"], {}), "(latFile + '.vrt')\n", (19849, 19867), False, 'import os\n'), ((19882, 19909), 'os.remove', 'os.remove', (["(latFile + '.xml')"], {}), "(latFile + '.xml')\n", (19891, 19909), False, 'import os\n'), ((19925, 19943), 'os.remove', 'os.remove', (['lonFile'], {}), '(lonFile)\n', (19934, 19943), False, 'import os\n'), ((19960, 19987), 'os.remove', 'os.remove', (["(lonFile + '.vrt')"], {}), "(lonFile + '.vrt')\n", (19969, 19987), False, 'import os\n'), ((20002, 20029), 'os.remove', 'os.remove', (["(lonFile + '.xml')"], {}), "(lonFile + '.xml')\n", (20011, 20029), False, 'import os\n'), ((20045, 20063), 'os.remove', 'os.remove', (['hgtFile'], {}), '(hgtFile)\n', (20054, 20063), False, 'import os\n'), ((20080, 20107), 'os.remove', 'os.remove', (["(hgtFile + '.vrt')"], {}), "(hgtFile + '.vrt')\n", (20089, 20107), False, 'import os\n'), ((20122, 20149), 'os.remove', 'os.remove', (["(hgtFile + '.xml')"], {}), "(hgtFile + '.xml')\n", (20131, 20149), False, 'import os\n'), ((20165, 20183), 'os.remove', 'os.remove', (['losFile'], {}), '(losFile)\n', (20174, 20183), False, 'import os\n'), ((20200, 20227), 'os.remove', 'os.remove', (["(losFile + '.vrt')"], {}), "(losFile + '.vrt')\n", (20209, 20227), False, 'import os\n'), ((20242, 20269), 'os.remove', 'os.remove', (["(losFile + '.xml')"], {}), "(losFile + '.xml')\n", (20251, 20269), False, 'import os\n'), ((20285, 20308), 'os.remove', 'os.remove', (['wbdRadarFile'], {}), '(wbdRadarFile)\n', (20294, 20308), False, 'import os\n'), ((20325, 20357), 'os.remove', 'os.remove', (["(wbdRadarFile + '.vrt')"], {}), "(wbdRadarFile + '.vrt')\n", (20334, 20357), False, 'import os\n'), ((20372, 20404), 'os.remove', 'os.remove', (["(wbdRadarFile + '.xml')"], {}), "(wbdRadarFile + '.xml')\n", (20381, 20404), False, 'import os\n'), ((7047, 7063), 'numpy.sum', 'np.sum', (['(wbd == 0)'], {}), '(wbd == 0)\n', (7053, 7063), True, 'import numpy as np\n'), ((10627, 10696), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""lat.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'lat.rdr')\n", (10639, 10696), False, 'import os\n'), ((10727, 10796), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""lon.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'lon.rdr')\n", (10739, 10796), False, 'import os\n'), ((10827, 10896), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""hgt.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'hgt.rdr')\n", (10839, 10896), False, 'import os\n'), ((10927, 10996), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""los.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'los.rdr')\n", (10939, 10996), False, 'import os\n'), ((11088, 11157), 'os.path.join', 'os.path.join', (['idir', 'dates[idate]', 'frameDir', 'swathDir', '"""rg_offset.rdr"""'], {}), "(idir, dates[idate], frameDir, swathDir, 'rg_offset.rdr')\n", (11100, 11157), False, 'import os\n'), ((11193, 11262), 'os.path.join', 'os.path.join', (['idir', 'dates[idate]', 'frameDir', 'swathDir', '"""az_offset.rdr"""'], {}), "(idir, dates[idate], frameDir, swathDir, 'az_offset.rdr')\n", (11205, 11262), False, 'import os\n'), ((11298, 11367), 'os.path.join', 'os.path.join', (['idir', 'dateSecondaryFirst', 'frameDir', 'swathDir', '"""wbd.rdr"""'], {}), "(idir, dateSecondaryFirst, frameDir, swathDir, 'wbd.rdr')\n", (11310, 11367), False, 'import os\n'), ((11389, 11592), 'isceobj.Alos2Proc.Alos2ProcPublic.geo2rdr', 'geo2rdr', (['secondarySwath', 'secondaryTrack', 'latFile', 'lonFile', 'hgtFile', 'rgOffsetFile', 'azOffsetFile'], {'numberRangeLooks': 'numberRangeLooks', 'numberAzimuthLooks': 'numberAzimuthLooks', 'multilookTimeOffset': '(False)'}), '(secondarySwath, secondaryTrack, latFile, lonFile, hgtFile,\n rgOffsetFile, azOffsetFile, numberRangeLooks=numberRangeLooks,\n numberAzimuthLooks=numberAzimuthLooks, multilookTimeOffset=False)\n', (11396, 11592), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import geo2rdr\n'), ((11809, 11832), 'os.remove', 'os.remove', (['rgOffsetFile'], {}), '(rgOffsetFile)\n', (11818, 11832), False, 'import os\n'), ((11853, 11885), 'os.remove', 'os.remove', (["(rgOffsetFile + '.vrt')"], {}), "(rgOffsetFile + '.vrt')\n", (11862, 11885), False, 'import os\n'), ((11904, 11936), 'os.remove', 'os.remove', (["(rgOffsetFile + '.xml')"], {}), "(rgOffsetFile + '.xml')\n", (11913, 11936), False, 'import os\n'), ((11955, 11978), 'os.remove', 'os.remove', (['azOffsetFile'], {}), '(azOffsetFile)\n', (11964, 11978), False, 'import os\n'), ((11999, 12031), 'os.remove', 'os.remove', (["(azOffsetFile + '.vrt')"], {}), "(azOffsetFile + '.vrt')\n", (12008, 12031), False, 'import os\n'), ((12050, 12082), 'os.remove', 'os.remove', (["(azOffsetFile + '.xml')"], {}), "(azOffsetFile + '.xml')\n", (12059, 12082), False, 'import os\n'), ((12179, 12214), 'mroipac.ampcor.Ampcor.Ampcor', 'Ampcor', ([], {'name': '"""insarapp_slcs_ampcor"""'}), "(name='insarapp_slcs_ampcor')\n", (12185, 12214), False, 'from mroipac.ampcor.Ampcor import Ampcor\n'), ((12282, 12306), 'isceobj.createSlcImage', 'isceobj.createSlcImage', ([], {}), '()\n', (12304, 12306), False, 'import isce, isceobj\n'), ((12439, 12501), 'os.path.join', 'os.path.join', (['referenceDir', "(dates[dateIndexReference] + '.slc')"], {}), "(referenceDir, dates[dateIndexReference] + '.slc')\n", (12451, 12501), False, 'import os\n'), ((12541, 12607), 'os.path.join', 'os.path.join', (['referenceDir', "(dates[dateIndexReference] + '.slc.vrt')"], {}), "(referenceDir, dates[dateIndexReference] + '.slc.vrt')\n", (12553, 12607), False, 'import os\n'), ((12720, 12744), 'isceobj.createSlcImage', 'isceobj.createSlcImage', ([], {}), '()\n', (12742, 12744), False, 'import isce, isceobj\n'), ((12864, 12913), 'os.path.join', 'os.path.join', (['secondaryDir', "(dates[idate] + '.slc')"], {}), "(secondaryDir, dates[idate] + '.slc')\n", (12876, 12913), False, 'import os\n'), ((12953, 13006), 'os.path.join', 'os.path.join', (['secondaryDir', "(dates[idate] + '.slc.vrt')"], {}), "(secondaryDir, dates[idate] + '.slc.vrt')\n", (12965, 13006), False, 'import os\n'), ((13445, 13614), 'isceobj.Alos2Proc.Alos2ProcPublic.computeOffsetFromOrbit', 'computeOffsetFromOrbit', (['referenceSwath', 'referenceTrack', 'secondarySwath', 'secondaryTrack', '(referenceSwath.numberOfSamples * 0.5)', '(referenceSwath.numberOfLines * 0.5)'], {}), '(referenceSwath, referenceTrack, secondarySwath,\n secondaryTrack, referenceSwath.numberOfSamples * 0.5, referenceSwath.\n numberOfLines * 0.5)\n', (13467, 13614), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import computeOffsetFromOrbit\n'), ((17139, 17179), 'os.path.join', 'os.path.join', (['secondaryDir', '"""ampcor.off"""'], {}), "(secondaryDir, 'ampcor.off')\n", (17151, 17179), False, 'import os\n'), ((17200, 17238), 'isceobj.Alos2Proc.Alos2ProcPublic.writeOffset', 'writeOffset', (['offsets', 'ampcorOffsetFile'], {}), '(offsets, ampcorOffsetFile)\n', (17211, 17238), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import writeOffset\n'), ((17658, 17678), 'isceobj.Alos2Proc.Alos2ProcPublic.cullOffsets', 'cullOffsets', (['offsets'], {}), '(offsets)\n', (17669, 17678), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import cullOffsets\n'), ((18380, 18418), 'os.path.join', 'os.path.join', (['secondaryDir', '"""cull.off"""'], {}), "(secondaryDir, 'cull.off')\n", (18392, 18418), False, 'import os\n'), ((18439, 18482), 'isceobj.Alos2Proc.Alos2ProcPublic.writeOffset', 'writeOffset', (['refinedOffsets', 'cullOffsetFile'], {}), '(refinedOffsets, cullOffsetFile)\n', (18450, 18482), False, 'from isceobj.Alos2Proc.Alos2ProcPublic import writeOffset\n'), ((6955, 6995), 'numpy.fromfile', 'np.fromfile', (['wbdRadarFile'], {'dtype': 'np.byte'}), '(wbdRadarFile, dtype=np.byte)\n', (6966, 6995), True, 'import numpy as np\n'), ((11659, 11697), 'os.path.join', 'os.path.join', (['secondaryDir', '"""cull.off"""'], {}), "(secondaryDir, 'cull.off')\n", (11671, 11697), False, 'import os\n'), ((12337, 12403), 'os.path.join', 'os.path.join', (['referenceDir', "(dates[dateIndexReference] + '.slc.xml')"], {}), "(referenceDir, dates[dateIndexReference] + '.slc.xml')\n", (12349, 12403), False, 'import os\n'), ((12775, 12828), 'os.path.join', 'os.path.join', (['secondaryDir', "(dates[idate] + '.slc.xml')"], {}), "(secondaryDir, dates[idate] + '.slc.xml')\n", (12787, 12828), False, 'import os\n'), ((7845, 7863), 'numpy.sqrt', 'np.sqrt', (['landRatio'], {}), '(landRatio)\n', (7852, 7863), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from config import config import logging def plot_from_csv(file_path, output_dir, metric, savefig=True): """ Plot the metric saved in the file_path file """ logging.info("Plotting metrics...") x = np.loadtxt(file_path, delimiter=',') epochs = np.arange(len(x)) plt.figure() if config['pretrained']: plt.title("Pretrained " + config['model'] + ' loss') else: plt.title(config['model'] + ' loss') plt.plot(epochs, x, 'b-', label='validation') plt.legend() plt.xlabel('epochs') if config['task'] == 'gaze-reg': plt.ylabel("MSE") elif config['task'] == 'angle-reg': plt.ylabel("Mean Absolute Angle Error") else: plt.ylabel('Binary Cross Entropy Loss') if savefig: plt.savefig(output_dir + '/plots/' + config['model'] + '_val_' + metric + '.png') def plot_array(x, output_dir, metric, savefig=True): """ Plot the metric saved in the file_path file """ logging.info("Plotting metrics...") epochs = np.arange(len(x)) plt.figure() if config['pretrained']: plt.title("Pretrained " + config['model'] + " " + metric) else: plt.title(config['model'] + " " + metric) plt.plot(epochs, np.array(x), 'b-', label='validation') plt.legend() plt.xlabel('epochs') if config['task'] == 'gaze-reg': plt.ylabel("MSE") elif metric == 'accuracy': plt.ylabel("Accuracy") elif config['task'] == 'angle-reg': plt.ylabel("Mean Absolute Angle Error") else: plt.ylabel('Binary Cross Entropy Loss') if savefig: plt.savefig(output_dir + '/plots/' + config['model'] + '_val_' + metric + '.png') def plot_metrics(train, val, output_dir, metric, model_number=0 ,savefig=True): """ Plot the training and validation metric together in one image """ logging.info("Plotting training and validation metrics ...") epochs = np.arange(len(train)) plt.figure() if config['pretrained']: plt.title("Pretrained " + config['model'] + " " + metric) else: plt.title(config['model'] + " " + str(model_number) + " " + metric) plt.plot(epochs, np.array(train), 'b-', label='train') plt.plot(epochs, np.array(val), 'g-', label='validation') plt.legend() plt.xlabel('epochs') plt.ylabel(metric) if savefig: plt.savefig(output_dir + '/plots/' + config['model'] + '_' +str(model_number) + "_" + metric + '.png')
[ "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "logging.info", "matplotlib.pyplot.figure", "numpy.array", "numpy.loadtxt", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((227, 262), 'logging.info', 'logging.info', (['"""Plotting metrics..."""'], {}), "('Plotting metrics...')\n", (239, 262), False, 'import logging\n'), ((271, 307), 'numpy.loadtxt', 'np.loadtxt', (['file_path'], {'delimiter': '""","""'}), "(file_path, delimiter=',')\n", (281, 307), True, 'import numpy as np\n'), ((343, 355), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (353, 355), True, 'import matplotlib.pyplot as plt\n'), ((505, 550), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'x', '"""b-"""'], {'label': '"""validation"""'}), "(epochs, x, 'b-', label='validation')\n", (513, 550), True, 'import matplotlib.pyplot as plt\n'), ((555, 567), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (565, 567), True, 'import matplotlib.pyplot as plt\n'), ((572, 592), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (582, 592), True, 'import matplotlib.pyplot as plt\n'), ((1032, 1067), 'logging.info', 'logging.info', (['"""Plotting metrics..."""'], {}), "('Plotting metrics...')\n", (1044, 1067), False, 'import logging\n'), ((1103, 1115), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1113, 1115), True, 'import matplotlib.pyplot as plt\n'), ((1335, 1347), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1345, 1347), True, 'import matplotlib.pyplot as plt\n'), ((1352, 1372), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (1362, 1372), True, 'import matplotlib.pyplot as plt\n'), ((1919, 1979), 'logging.info', 'logging.info', (['"""Plotting training and validation metrics ..."""'], {}), "('Plotting training and validation metrics ...')\n", (1931, 1979), False, 'import logging\n'), ((2019, 2031), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2029, 2031), True, 'import matplotlib.pyplot as plt\n'), ((2338, 2350), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2348, 2350), True, 'import matplotlib.pyplot as plt\n'), ((2355, 2375), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (2365, 2375), True, 'import matplotlib.pyplot as plt\n'), ((2380, 2398), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['metric'], {}), '(metric)\n', (2390, 2398), True, 'import matplotlib.pyplot as plt\n'), ((393, 445), 'matplotlib.pyplot.title', 'plt.title', (["('Pretrained ' + config['model'] + ' loss')"], {}), "('Pretrained ' + config['model'] + ' loss')\n", (402, 445), True, 'import matplotlib.pyplot as plt\n'), ((464, 500), 'matplotlib.pyplot.title', 'plt.title', (["(config['model'] + ' loss')"], {}), "(config['model'] + ' loss')\n", (473, 500), True, 'import matplotlib.pyplot as plt\n'), ((639, 656), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""MSE"""'], {}), "('MSE')\n", (649, 656), True, 'import matplotlib.pyplot as plt\n'), ((827, 912), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(output_dir + '/plots/' + config['model'] + '_val_' + metric + '.png')"], {}), "(output_dir + '/plots/' + config['model'] + '_val_' + metric +\n '.png')\n", (838, 912), True, 'import matplotlib.pyplot as plt\n'), ((1153, 1210), 'matplotlib.pyplot.title', 'plt.title', (["('Pretrained ' + config['model'] + ' ' + metric)"], {}), "('Pretrained ' + config['model'] + ' ' + metric)\n", (1162, 1210), True, 'import matplotlib.pyplot as plt\n'), ((1229, 1270), 'matplotlib.pyplot.title', 'plt.title', (["(config['model'] + ' ' + metric)"], {}), "(config['model'] + ' ' + metric)\n", (1238, 1270), True, 'import matplotlib.pyplot as plt\n'), ((1292, 1303), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1300, 1303), True, 'import numpy as np\n'), ((1419, 1436), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""MSE"""'], {}), "('MSE')\n", (1429, 1436), True, 'import matplotlib.pyplot as plt\n'), ((1669, 1754), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(output_dir + '/plots/' + config['model'] + '_val_' + metric + '.png')"], {}), "(output_dir + '/plots/' + config['model'] + '_val_' + metric +\n '.png')\n", (1680, 1754), True, 'import matplotlib.pyplot as plt\n'), ((2069, 2126), 'matplotlib.pyplot.title', 'plt.title', (["('Pretrained ' + config['model'] + ' ' + metric)"], {}), "('Pretrained ' + config['model'] + ' ' + metric)\n", (2078, 2126), True, 'import matplotlib.pyplot as plt\n'), ((2234, 2249), 'numpy.array', 'np.array', (['train'], {}), '(train)\n', (2242, 2249), True, 'import numpy as np\n'), ((2293, 2306), 'numpy.array', 'np.array', (['val'], {}), '(val)\n', (2301, 2306), True, 'import numpy as np\n'), ((705, 744), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Absolute Angle Error"""'], {}), "('Mean Absolute Angle Error')\n", (715, 744), True, 'import matplotlib.pyplot as plt\n'), ((763, 802), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Binary Cross Entropy Loss"""'], {}), "('Binary Cross Entropy Loss')\n", (773, 802), True, 'import matplotlib.pyplot as plt\n'), ((1476, 1498), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (1486, 1498), True, 'import matplotlib.pyplot as plt\n'), ((1547, 1586), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Absolute Angle Error"""'], {}), "('Mean Absolute Angle Error')\n", (1557, 1586), True, 'import matplotlib.pyplot as plt\n'), ((1605, 1644), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Binary Cross Entropy Loss"""'], {}), "('Binary Cross Entropy Loss')\n", (1615, 1644), True, 'import matplotlib.pyplot as plt\n')]
from .test_abelfunctions import AbelfunctionsTestCase import abelfunctions import numpy import unittest from abelfunctions.abelmap import AbelMap, Jacobian from numpy.linalg import norm from sage.all import I class TestDivisors(AbelfunctionsTestCase): def setUp(self): # cache some items for performance self.X11_Jacobian = Jacobian(self.X11) self.X11_P = self.X11(0)[0] self.X11_Q = self.X11(1)[0] self.X11_R = self.X11(I)[0] self.X11_P0 = self.X11.base_place def test_divisors_X11(self): J = self.X11_Jacobian P = self.X11_P D = 3*P val1 = AbelMap(D) val2 = sum(ni*AbelMap(Pi) for (Pi,ni) in D) error = norm(J(val1-val2)) self.assertLess(error,1e-7) D1 = sum(self.X11(2)) val1 = AbelMap(D1) val2 = sum(ni*AbelMap(Pi) for (Pi,ni) in D1) error = norm(J(val1-val2)) self.assertLess(error,1e-7) D2 = sum(self.X11(0.5)) val1 = AbelMap(D2) val2 = sum(ni*AbelMap(Pi) for (Pi,ni) in D2) error = norm(J(val1-val2)) self.assertLess(error,1e-7) def test_new_base_point_X11(self): J = self.X11_Jacobian P = self.X11_P Q = self.X11_Q R = self.X11_R P0 = self.X11_P0 AP = AbelMap(P) AQ = AbelMap(Q) AR = AbelMap(R) APQ = AbelMap(P,Q) AQR = AbelMap(Q,R) ARP = AbelMap(R,P) error = norm(J(APQ - AQ + AP)) self.assertLess(error,1e-7) error = norm(J(AQR - AR + AQ)) self.assertLess(error,1e-7) error = norm(J(ARP - AP + AR)) self.assertLess(error,1e-7) class TestJacobian(AbelfunctionsTestCase): def test_zero_X11(self): J = Jacobian(self.X11) zero = numpy.array([0,0,0,0]) value = J(zero) error = norm(value - zero) self.assertLess(error,1e-14)
[ "abelfunctions.abelmap.AbelMap", "numpy.array", "abelfunctions.abelmap.Jacobian", "numpy.linalg.norm" ]
[((347, 365), 'abelfunctions.abelmap.Jacobian', 'Jacobian', (['self.X11'], {}), '(self.X11)\n', (355, 365), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((634, 644), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['D'], {}), '(D)\n', (641, 644), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((814, 825), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['D1'], {}), '(D1)\n', (821, 825), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((998, 1009), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['D2'], {}), '(D2)\n', (1005, 1009), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1312, 1322), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['P'], {}), '(P)\n', (1319, 1322), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1336, 1346), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['Q'], {}), '(Q)\n', (1343, 1346), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1360, 1370), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['R'], {}), '(R)\n', (1367, 1370), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1386, 1399), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['P', 'Q'], {}), '(P, Q)\n', (1393, 1399), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1413, 1426), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['Q', 'R'], {}), '(Q, R)\n', (1420, 1426), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1440, 1453), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['R', 'P'], {}), '(R, P)\n', (1447, 1453), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1766, 1784), 'abelfunctions.abelmap.Jacobian', 'Jacobian', (['self.X11'], {}), '(self.X11)\n', (1774, 1784), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1800, 1825), 'numpy.array', 'numpy.array', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (1811, 1825), False, 'import numpy\n'), ((1863, 1881), 'numpy.linalg.norm', 'norm', (['(value - zero)'], {}), '(value - zero)\n', (1867, 1881), False, 'from numpy.linalg import norm\n'), ((667, 678), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['Pi'], {}), '(Pi)\n', (674, 678), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((848, 859), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['Pi'], {}), '(Pi)\n', (855, 859), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n'), ((1032, 1043), 'abelfunctions.abelmap.AbelMap', 'AbelMap', (['Pi'], {}), '(Pi)\n', (1039, 1043), False, 'from abelfunctions.abelmap import AbelMap, Jacobian\n')]
#!/usr/bin/env python3 # -*- coding = utf-8 -*- import os import sys import json import statistics import cv2 from keras.models import load_model import numpy as np from models.model_factory import load_keras_model from util.constant import fer2013_classes from util.classifyimgops import apply_offsets from util.classifyimgops import preprocess_input from util.info import load_info # Window Position Coordinates (MacBook Pro 13-inch) CENTER_X = 100 CENTER_Y = 80 CENTER_POS = (CENTER_X, CENTER_Y) # Get DNN Model face_detector, net = load_info() # Choose Model (only one) dnn = True cascade = False # Bounding frame_window = 10 if dnn: emotion_offsets = (55, 45) elif cascade: emotion_offsets = (20, 40) else: raise ValueError("You must select one of dnn or cascade.") # Load Emotion Model. emotion_model_path = os.path.join(os.path.dirname(__file__), 'data/savedmodels/Model-49-0.6572.hdf5') emotion_labels = fer2013_classes emotion_classifier = load_keras_model('Model-27-0.6631', compile = False) emotion_target_size = emotion_classifier.input_shape[1:3] # starting lists for calculating modes emotion_window = [] # Bring the video screen to the front (MACOS ONLY). if sys.platform == "darwin": os.system("""osascript -e 'tell app "Finder" to set frontmost of process "Python" to be true'""") def showPositionedWindow(window_name, img_name, coords): cv2.namedWindow(window_name) cv2.moveWindow(window_name, coords[0], coords[1]) cv2.imshow(window_name, img_name) vr = cv2.VideoCapture(0) global faces while True: _, frame = vr.read() gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if dnn: blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), swapRB = False, crop = False) net.setInput(blob) faces = net.forward() if cascade: faces = face_detector.detectMultiScale(gray_image, 1.3, 5) if cascade: for face_coordinates in faces: x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets) gray_face = gray_image[y1: y2, x1: x2] try: gray_face = cv2.resize(gray_face, (emotion_target_size)) except: continue # Preprocess & Classify Instantaneous Emotion gray_face = preprocess_input(gray_face, True) gray_face = np.expand_dims(gray_face, 0) gray_face = np.expand_dims(gray_face, -1) emotion_prediction = emotion_classifier.predict(gray_face) # Set up a range of emotions from which to display from. emotion_probability = np.max(emotion_prediction) emotion_label_arg = np.argmax(emotion_prediction) emotion_text = emotion_labels[emotion_label_arg] emotion_window.append(emotion_text) if len(emotion_window) > frame_window: emotion_window.pop(0) try: emotion_mode = statistics.mode(emotion_window) except: continue if emotion_text == 'happy': color = emotion_probability * np.asarray((255, 255, 0)) elif emotion_text == 'angry': color = emotion_probability * np.asarray((255, 0, 0)) elif emotion_text == 'sad': color = emotion_probability * np.asarray((0, 0, 255)) elif emotion_text == 'surprise': color = emotion_probability * np.asarray((0, 255, 255)) else: color = emotion_probability * np.asarray((0, 255, 0)) color = color.astype(int) color = color.tolist() x, y, w, h = face_coordinates cv2.rectangle(frame, (x1, y1), (x2, y2), color, 3) cv2.putText(frame, emotion_mode, (x + 0, y - 45), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 3, cv2.LINE_AA) if dnn: (h, w) = frame.shape[:2] for k in range(0, faces.shape[2]): c = faces[0, 0, k, 2] if c < 0.5: continue box = faces[0, 0, k, 3:7] * np.array([w, h, w, h]) (x, y, xe, ye) = box.astype("int") face_coordinates = (x, y, xe - x, ye - y) x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets) gray_face = gray_image[y1: y2, x1: x2] try: gray_face = cv2.resize(gray_face, (emotion_target_size)) except: continue # Preprocess & Classify Instantaneous Emotion gray_face = preprocess_input(gray_face, True) gray_face = np.expand_dims(gray_face, 0) gray_face = np.expand_dims(gray_face, -1) emotion_prediction = emotion_classifier.predict(gray_face) # Set up a range of emotions from which to display from. emotion_probability = np.max(emotion_prediction) emotion_label_arg = np.argmax(emotion_prediction) emotion_text = emotion_labels[emotion_label_arg] emotion_window.append(emotion_text) if len(emotion_window) > frame_window: emotion_window.pop(0) try: emotion_mode = statistics.mode(emotion_window) except: continue if emotion_text == 'happy': color = emotion_probability * np.asarray((255, 255, 0)) elif emotion_text == 'angry': color = emotion_probability * np.asarray((255, 0, 0)) elif emotion_text == 'sad': color = emotion_probability * np.asarray((0, 0, 255)) elif emotion_text == 'surprise': color = emotion_probability * np.asarray((0, 255, 255)) else: color = emotion_probability * np.asarray((0, 255, 0)) color = color.astype(int).tolist() # For Testing: # cv2.rectangle(frame, (x1, y1), (x2, y2), color, 3) cv2.rectangle(frame, (x, y), (xe, ye), color, 3) cv2.putText(frame, emotion_mode, (x + 0, y - 45), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 3, cv2.LINE_AA) showPositionedWindow('frame', frame, CENTER_POS) if cv2.waitKey(1) and 0xFF == ord('z'): break vr.release() cv2.destroyAllWindows()
[ "numpy.argmax", "cv2.rectangle", "util.classifyimgops.preprocess_input", "cv2.imshow", "util.classifyimgops.apply_offsets", "util.info.load_info", "cv2.cvtColor", "os.path.dirname", "models.model_factory.load_keras_model", "numpy.max", "statistics.mode", "cv2.destroyAllWindows", "cv2.resize", "cv2.waitKey", "numpy.asarray", "os.system", "cv2.putText", "numpy.expand_dims", "cv2.VideoCapture", "numpy.array", "cv2.moveWindow", "cv2.namedWindow" ]
[((540, 551), 'util.info.load_info', 'load_info', ([], {}), '()\n', (549, 551), False, 'from util.info import load_info\n'), ((965, 1015), 'models.model_factory.load_keras_model', 'load_keras_model', (['"""Model-27-0.6631"""'], {'compile': '(False)'}), "('Model-27-0.6631', compile=False)\n", (981, 1015), False, 'from models.model_factory import load_keras_model\n'), ((1501, 1520), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1517, 1520), False, 'import cv2\n'), ((5881, 5904), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5902, 5904), False, 'import cv2\n'), ((843, 868), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (858, 868), False, 'import os\n'), ((1218, 1323), 'os.system', 'os.system', (['"""osascript -e \'tell app "Finder" to set frontmost of process "Python" to be true\'"""'], {}), '(\n \'osascript -e \\\'tell app "Finder" to set frontmost of process "Python" to be true\\\'\'\n )\n', (1227, 1323), False, 'import os\n'), ((1376, 1404), 'cv2.namedWindow', 'cv2.namedWindow', (['window_name'], {}), '(window_name)\n', (1391, 1404), False, 'import cv2\n'), ((1408, 1457), 'cv2.moveWindow', 'cv2.moveWindow', (['window_name', 'coords[0]', 'coords[1]'], {}), '(window_name, coords[0], coords[1])\n', (1422, 1457), False, 'import cv2\n'), ((1461, 1494), 'cv2.imshow', 'cv2.imshow', (['window_name', 'img_name'], {}), '(window_name, img_name)\n', (1471, 1494), False, 'import cv2\n'), ((1586, 1625), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (1598, 1625), False, 'import cv2\n'), ((5818, 5832), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5829, 5832), False, 'import cv2\n'), ((1672, 1701), 'cv2.resize', 'cv2.resize', (['frame', '(300, 300)'], {}), '(frame, (300, 300))\n', (1682, 1701), False, 'import cv2\n'), ((1962, 2010), 'util.classifyimgops.apply_offsets', 'apply_offsets', (['face_coordinates', 'emotion_offsets'], {}), '(face_coordinates, emotion_offsets)\n', (1975, 2010), False, 'from util.classifyimgops import apply_offsets\n'), ((2233, 2266), 'util.classifyimgops.preprocess_input', 'preprocess_input', (['gray_face', '(True)'], {}), '(gray_face, True)\n', (2249, 2266), False, 'from util.classifyimgops import preprocess_input\n'), ((2288, 2316), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(0)'], {}), '(gray_face, 0)\n', (2302, 2316), True, 'import numpy as np\n'), ((2338, 2367), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(-1)'], {}), '(gray_face, -1)\n', (2352, 2367), True, 'import numpy as np\n'), ((2534, 2560), 'numpy.max', 'np.max', (['emotion_prediction'], {}), '(emotion_prediction)\n', (2540, 2560), True, 'import numpy as np\n'), ((2590, 2619), 'numpy.argmax', 'np.argmax', (['emotion_prediction'], {}), '(emotion_prediction)\n', (2599, 2619), True, 'import numpy as np\n'), ((3504, 3554), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x1, y1)', '(x2, y2)', 'color', '(3)'], {}), '(frame, (x1, y1), (x2, y2), color, 3)\n', (3517, 3554), False, 'import cv2\n'), ((3564, 3669), 'cv2.putText', 'cv2.putText', (['frame', 'emotion_mode', '(x + 0, y - 45)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', 'color', '(3)', 'cv2.LINE_AA'], {}), '(frame, emotion_mode, (x + 0, y - 45), cv2.FONT_HERSHEY_SIMPLEX,\n 1, color, 3, cv2.LINE_AA)\n', (3575, 3669), False, 'import cv2\n'), ((4013, 4061), 'util.classifyimgops.apply_offsets', 'apply_offsets', (['face_coordinates', 'emotion_offsets'], {}), '(face_coordinates, emotion_offsets)\n', (4026, 4061), False, 'from util.classifyimgops import apply_offsets\n'), ((4284, 4317), 'util.classifyimgops.preprocess_input', 'preprocess_input', (['gray_face', '(True)'], {}), '(gray_face, True)\n', (4300, 4317), False, 'from util.classifyimgops import preprocess_input\n'), ((4339, 4367), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(0)'], {}), '(gray_face, 0)\n', (4353, 4367), True, 'import numpy as np\n'), ((4389, 4418), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(-1)'], {}), '(gray_face, -1)\n', (4403, 4418), True, 'import numpy as np\n'), ((4585, 4611), 'numpy.max', 'np.max', (['emotion_prediction'], {}), '(emotion_prediction)\n', (4591, 4611), True, 'import numpy as np\n'), ((4641, 4670), 'numpy.argmax', 'np.argmax', (['emotion_prediction'], {}), '(emotion_prediction)\n', (4650, 4670), True, 'import numpy as np\n'), ((5578, 5626), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y)', '(xe, ye)', 'color', '(3)'], {}), '(frame, (x, y), (xe, ye), color, 3)\n', (5591, 5626), False, 'import cv2\n'), ((5636, 5741), 'cv2.putText', 'cv2.putText', (['frame', 'emotion_mode', '(x + 0, y - 45)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', 'color', '(3)', 'cv2.LINE_AA'], {}), '(frame, emotion_mode, (x + 0, y - 45), cv2.FONT_HERSHEY_SIMPLEX,\n 1, color, 3, cv2.LINE_AA)\n', (5647, 5741), False, 'import cv2\n'), ((2085, 2127), 'cv2.resize', 'cv2.resize', (['gray_face', 'emotion_target_size'], {}), '(gray_face, emotion_target_size)\n', (2095, 2127), False, 'import cv2\n'), ((2823, 2854), 'statistics.mode', 'statistics.mode', (['emotion_window'], {}), '(emotion_window)\n', (2838, 2854), False, 'import statistics\n'), ((3869, 3891), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (3877, 3891), True, 'import numpy as np\n'), ((4136, 4178), 'cv2.resize', 'cv2.resize', (['gray_face', 'emotion_target_size'], {}), '(gray_face, emotion_target_size)\n', (4146, 4178), False, 'import cv2\n'), ((4874, 4905), 'statistics.mode', 'statistics.mode', (['emotion_window'], {}), '(emotion_window)\n', (4889, 4905), False, 'import statistics\n'), ((2961, 2986), 'numpy.asarray', 'np.asarray', (['(255, 255, 0)'], {}), '((255, 255, 0))\n', (2971, 2986), True, 'import numpy as np\n'), ((5012, 5037), 'numpy.asarray', 'np.asarray', (['(255, 255, 0)'], {}), '((255, 255, 0))\n', (5022, 5037), True, 'import numpy as np\n'), ((3068, 3091), 'numpy.asarray', 'np.asarray', (['(255, 0, 0)'], {}), '((255, 0, 0))\n', (3078, 3091), True, 'import numpy as np\n'), ((5119, 5142), 'numpy.asarray', 'np.asarray', (['(255, 0, 0)'], {}), '((255, 0, 0))\n', (5129, 5142), True, 'import numpy as np\n'), ((3171, 3194), 'numpy.asarray', 'np.asarray', (['(0, 0, 255)'], {}), '((0, 0, 255))\n', (3181, 3194), True, 'import numpy as np\n'), ((5222, 5245), 'numpy.asarray', 'np.asarray', (['(0, 0, 255)'], {}), '((0, 0, 255))\n', (5232, 5245), True, 'import numpy as np\n'), ((3279, 3304), 'numpy.asarray', 'np.asarray', (['(0, 255, 255)'], {}), '((0, 255, 255))\n', (3289, 3304), True, 'import numpy as np\n'), ((3362, 3385), 'numpy.asarray', 'np.asarray', (['(0, 255, 0)'], {}), '((0, 255, 0))\n', (3372, 3385), True, 'import numpy as np\n'), ((5330, 5355), 'numpy.asarray', 'np.asarray', (['(0, 255, 255)'], {}), '((0, 255, 255))\n', (5340, 5355), True, 'import numpy as np\n'), ((5413, 5436), 'numpy.asarray', 'np.asarray', (['(0, 255, 0)'], {}), '((0, 255, 0))\n', (5423, 5436), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 15:02:36 2019 Bresenham画圆法实现 博客教程地址: https://blog.csdn.net/varyshare/article/details/96724103 @author: 知乎@Ai酱 """ import numpy as np import matplotlib.pyplot as plt img = np.zeros((105,105)) # 创建一个105x105的画布 count = 0 def draw(x,y): """ 绘制点(x,y) 注意:需要把(x,y)变换到数组坐标系(图形学坐标系) 因为数组(0,0)是左上,而原先坐标系(0,0)是中心点 而且数组行数向下是增加的。 """ img[-y+int(img.shape[0]/2),x+int(img.shape[1]/2)] = 1 pass r_pixel = 50 # 圆的半径,单位:像素 # 初始化,画第一个点,从水平最右边那个点开始画 (x,y) = (r_pixel,0) """ 从定义来讲就是 P_k=d1+d2 d1 = 第1个下一步待选点离圆弧的距离(负数) d2 = 第2个下一步待选点离圆弧的距离(正数) 但是为了提高效率通常使用递推来求P_{k+1}=P_k + 一个数 """ P_k = -2*r_pixel + 3 # 迭代的求完1/8圆弧 while x>=y: # 下一步有两个待选点,具体选哪个要看P_k>0 或 <0 if P_k>=0:# 外侧候选点偏离圆弧更远 P_k_next = P_k - 4*x + 4*y + 10 (x_next,y_next) = (x-1, y+1) else:# 内侧候选点偏离圆弧更远 P_k_next = P_k + 4*y + 6 (x_next,y_next) = (x, y+1) # 对称法画其他地方 draw(x,y) draw(-x,y) draw(x,-y) draw(-x,-y) draw(y,x) draw(y,-x) draw(-y,x) draw(-y,-x) # 更新坐标和P_k (x,y) = (int(x_next),int(y_next)) P_k = P_k_next pass # 绘制图片 plt.imshow(img)
[ "matplotlib.pyplot.imshow", "numpy.zeros" ]
[((222, 242), 'numpy.zeros', 'np.zeros', (['(105, 105)'], {}), '((105, 105))\n', (230, 242), True, 'import numpy as np\n'), ((1167, 1182), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (1177, 1182), True, 'import matplotlib.pyplot as plt\n')]
from copy import copy from typing import Optional, Union import numpy as np from torch import Tensor from tqdm import tqdm from graphwar.attack.injection.injection_attacker import InjectionAttacker class RandomInjection(InjectionAttacker): r"""Injection nodes into a graph randomly. Example ------- >>> from graphwar.dataset import GraphWarDataset >>> import torch_geometric.transforms as T >>> dataset = GraphWarDataset(root='~/data/pygdata', name='cora', transform=T.LargestConnectedComponents()) >>> data = dataset[0] >>> from graphwar.attack.injection import RandomInjection >>> attacker = RandomInjection(data) >>> attacker.reset() >>> attacker.attack(10, feat_limits=(0, 1)) # injecting 10 nodes for continuous features >>> attacker.reset() >>> attacker.attack(10, feat_budgets=10) # injecting 10 nodes for binary features >>> attacker.data() # get attacked graph >>> attacker.injected_nodes() # get injected nodes after attack >>> attacker.injected_edges() # get injected edges after attack >>> attacker.injected_feats() # get injected features after attack Note ---- * Please remember to call :meth:`reset` before each attack. """ def attack(self, num_budgets: Union[int, float], *, targets: Optional[Tensor] = None, interconnection: bool = False, num_edges_global: Optional[int] = None, num_edges_local: Optional[int] = None, feat_limits: Optional[Union[tuple, dict]] = None, feat_budgets: Optional[int] = None, disable: bool = False) -> "RandomInjection": """Base method that describes the adversarial injection attack Parameters ---------- num_budgets : Union[int, float] the number/percentage of nodes allowed to inject targets : Optional[Tensor], optional the targeted nodes where injected nodes perturb, if None, it will be all nodes in the graph, by default None interconnection : bool, optional whether the injected nodes can connect to each other, by default False num_edges_global : Optional[int], optional the number of total edges in the graph to be injected for all injected nodes, by default None num_edges_local : Optional[int], optional the number of edges allowed to inject for each injected nodes, by default None feat_limits : Optional[Union[tuple, dict]], optional the limitation or allowed budgets of injected node features, it can be a tuple, e.g., `(0, 1)` or a dict, e.g., `{'min':0, 'max': 1}`. if None, it is set as (self.feat.min(), self.feat.max()), by default None feat_budgets : Optional[int], optional the number of nonzero features can be injected for each node, e.g., `10`, denoting 10 nonzero features can be injected, by default None disable : bool, optional whether the tqdm progbar is to disabled, by default False Returns ------- the attacker itself Note ---- * Both `num_edges_local` and `num_edges_global` cannot be used simultaneously. * Both `feat_limits` and `feat_budgets` cannot be used simultaneously. """ super().attack(num_budgets, targets=targets, num_edges_global=num_edges_global, num_edges_local=num_edges_local, feat_limits=feat_limits, feat_budgets=feat_budgets) candidate_nodes = self.targets.tolist() for injected_node in tqdm(range(self.num_nodes, self.num_nodes+self.num_budgets), desc="Injecting nodes...", disable=disable): sampled = np.random.choice( candidate_nodes, self.num_edges_local, replace=False) self.inject_node(injected_node) self.inject_feat() for target in sampled: self.inject_edge(injected_node, target) if interconnection: candidate_nodes.append(injected_node) return self
[ "numpy.random.choice" ]
[((3978, 4048), 'numpy.random.choice', 'np.random.choice', (['candidate_nodes', 'self.num_edges_local'], {'replace': '(False)'}), '(candidate_nodes, self.num_edges_local, replace=False)\n', (3994, 4048), True, 'import numpy as np\n')]
from __future__ import division import warnings warnings.filterwarnings("ignore") import numpy as np # linear algebra import pandas as pd from sklearn.utils import shuffle from sklearn.model_selection import train_test_split import logging,sys import lasagne from lasagne import layers from lasagne.updates import nesterov_momentum from nolearn.lasagne import NeuralNet FORMAT = '%(asctime)-15s [%(levelname)-8s] %(message)s' logging.basicConfig(stream=sys.stdout,format=FORMAT, level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%I') console = logging.StreamHandler() console.setLevel(logging.INFO) #data frame logging.info("*** CLEANING DATAFRAME ***") data_frame = pd.read_csv("dataset.csv",header=1) data_frame.drop(data_frame.columns[[0]], axis=1, inplace=True) dataset = shuffle(np.array(data_frame)) extracted_dataset= [] target = [] #extract target column for row in dataset: extracted_dataset.append(row[1:]) if row[0] == 'B': target.append(0) else: target.append(1) X_train, X_test, Y_train, Y_test= train_test_split(extracted_dataset,target,test_size=0.3) logging.info("*** DATASET PARTITIONED IN TRAIN: "+str(len(X_train))+ " TEST: "+str(len(X_test))) Y_train = np.array(Y_train).astype(np.uint8) Y_test = np.array(Y_test).astype(np.uint8) X_train = np.array(X_train).reshape((-1, 1, 6, 5)).astype(np.uint8) X_test = np.array(X_test).reshape((-1, 1, 6, 5)).astype(np.uint8) """ epoch: one forward pass and one backward pass of all the training examples --> 15 """ net1 = NeuralNet( layers=[('input', layers.InputLayer), ('hidden', layers.DenseLayer), ('output', layers.DenseLayer), ], # layer parameters: input_shape=(None, 1, 6, 5), hidden_num_units=1000, # number of units in 'hidden' layer output_nonlinearity=lasagne.nonlinearities.softmax, output_num_units=2, # target values for the digits 0, 1 # optimization method: update=nesterov_momentum, update_learning_rate=0.0001, update_momentum=0.9, max_epochs=30, verbose=0, ) net1.fit(X_train, Y_train) def CNN(n_epochs): net1 = NeuralNet( layers=[ ('input', layers.InputLayer), ('conv1', layers.Conv2DLayer), # Convolutional layer. Params defined below ('pool1', layers.MaxPool2DLayer), # Like downsampling, for execution speed ('conv2', layers.Conv2DLayer), ('hidden3', layers.DenseLayer), ('output', layers.DenseLayer), ], input_shape=(None, 1, 6, 5), conv1_num_filters=8, conv1_filter_size=(3, 3), conv1_nonlinearity=lasagne.nonlinearities.rectify, pool1_pool_size=(2, 2), conv2_num_filters=12, conv2_filter_size=(1, 1), conv2_nonlinearity=lasagne.nonlinearities.rectify, hidden3_num_units=1000, output_num_units=2, output_nonlinearity=lasagne.nonlinearities.softmax, update_learning_rate=0.0001, update_momentum=0.9, max_epochs=n_epochs, verbose=0, ) return net1 cnn = CNN(40).fit(X_train, Y_train) # train the CNN model for 15 epochs logging.info("*** TRAINING END ***") predicted = cnn.predict(X_test) idx = 0 true = 0 false = 0 for i in X_test: #logging.info("*** Pred:"+str(predicted[idx])+" real: "+str(Y_test[idx])+" res "+str(predicted[idx]==Y_test[idx])+" ***") if predicted[idx]==Y_test[idx]: true +=1 else: false +=1 idx +=1 accuracy = (true/(true+false))*100 logging.info("Positive Class: "+str(true)) logging.info("Negative Class: "+str(false)) logging.info("Accuracy: "+str(accuracy))
[ "nolearn.lasagne.NeuralNet", "logging.basicConfig", "warnings.filterwarnings", "pandas.read_csv", "sklearn.model_selection.train_test_split", "logging.StreamHandler", "logging.info", "numpy.array" ]
[((48, 81), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (71, 81), False, 'import warnings\n'), ((429, 535), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'format': 'FORMAT', 'level': 'logging.INFO', 'datefmt': '"""%Y-%m-%d %H:%M:%I"""'}), "(stream=sys.stdout, format=FORMAT, level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%I')\n", (448, 535), False, 'import logging, sys\n'), ((541, 564), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (562, 564), False, 'import logging, sys\n'), ((610, 652), 'logging.info', 'logging.info', (['"""*** CLEANING DATAFRAME ***"""'], {}), "('*** CLEANING DATAFRAME ***')\n", (622, 652), False, 'import logging, sys\n'), ((666, 702), 'pandas.read_csv', 'pd.read_csv', (['"""dataset.csv"""'], {'header': '(1)'}), "('dataset.csv', header=1)\n", (677, 702), True, 'import pandas as pd\n'), ((1041, 1099), 'sklearn.model_selection.train_test_split', 'train_test_split', (['extracted_dataset', 'target'], {'test_size': '(0.3)'}), '(extracted_dataset, target, test_size=0.3)\n', (1057, 1099), False, 'from sklearn.model_selection import train_test_split\n'), ((1522, 1877), 'nolearn.lasagne.NeuralNet', 'NeuralNet', ([], {'layers': "[('input', layers.InputLayer), ('hidden', layers.DenseLayer), ('output',\n layers.DenseLayer)]", 'input_shape': '(None, 1, 6, 5)', 'hidden_num_units': '(1000)', 'output_nonlinearity': 'lasagne.nonlinearities.softmax', 'output_num_units': '(2)', 'update': 'nesterov_momentum', 'update_learning_rate': '(0.0001)', 'update_momentum': '(0.9)', 'max_epochs': '(30)', 'verbose': '(0)'}), "(layers=[('input', layers.InputLayer), ('hidden', layers.\n DenseLayer), ('output', layers.DenseLayer)], input_shape=(None, 1, 6, 5\n ), hidden_num_units=1000, output_nonlinearity=lasagne.nonlinearities.\n softmax, output_num_units=2, update=nesterov_momentum,\n update_learning_rate=0.0001, update_momentum=0.9, max_epochs=30, verbose=0)\n", (1531, 1877), False, 'from nolearn.lasagne import NeuralNet\n'), ((3166, 3202), 'logging.info', 'logging.info', (['"""*** TRAINING END ***"""'], {}), "('*** TRAINING END ***')\n", (3178, 3202), False, 'import logging, sys\n'), ((783, 803), 'numpy.array', 'np.array', (['data_frame'], {}), '(data_frame)\n', (791, 803), True, 'import numpy as np\n'), ((2128, 2808), 'nolearn.lasagne.NeuralNet', 'NeuralNet', ([], {'layers': "[('input', layers.InputLayer), ('conv1', layers.Conv2DLayer), ('pool1',\n layers.MaxPool2DLayer), ('conv2', layers.Conv2DLayer), ('hidden3',\n layers.DenseLayer), ('output', layers.DenseLayer)]", 'input_shape': '(None, 1, 6, 5)', 'conv1_num_filters': '(8)', 'conv1_filter_size': '(3, 3)', 'conv1_nonlinearity': 'lasagne.nonlinearities.rectify', 'pool1_pool_size': '(2, 2)', 'conv2_num_filters': '(12)', 'conv2_filter_size': '(1, 1)', 'conv2_nonlinearity': 'lasagne.nonlinearities.rectify', 'hidden3_num_units': '(1000)', 'output_num_units': '(2)', 'output_nonlinearity': 'lasagne.nonlinearities.softmax', 'update_learning_rate': '(0.0001)', 'update_momentum': '(0.9)', 'max_epochs': 'n_epochs', 'verbose': '(0)'}), "(layers=[('input', layers.InputLayer), ('conv1', layers.\n Conv2DLayer), ('pool1', layers.MaxPool2DLayer), ('conv2', layers.\n Conv2DLayer), ('hidden3', layers.DenseLayer), ('output', layers.\n DenseLayer)], input_shape=(None, 1, 6, 5), conv1_num_filters=8,\n conv1_filter_size=(3, 3), conv1_nonlinearity=lasagne.nonlinearities.\n rectify, pool1_pool_size=(2, 2), conv2_num_filters=12,\n conv2_filter_size=(1, 1), conv2_nonlinearity=lasagne.nonlinearities.\n rectify, hidden3_num_units=1000, output_num_units=2,\n output_nonlinearity=lasagne.nonlinearities.softmax,\n update_learning_rate=0.0001, update_momentum=0.9, max_epochs=n_epochs,\n verbose=0)\n", (2137, 2808), False, 'from nolearn.lasagne import NeuralNet\n'), ((1206, 1223), 'numpy.array', 'np.array', (['Y_train'], {}), '(Y_train)\n', (1214, 1223), True, 'import numpy as np\n'), ((1250, 1266), 'numpy.array', 'np.array', (['Y_test'], {}), '(Y_test)\n', (1258, 1266), True, 'import numpy as np\n'), ((1294, 1311), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (1302, 1311), True, 'import numpy as np\n'), ((1361, 1377), 'numpy.array', 'np.array', (['X_test'], {}), '(X_test)\n', (1369, 1377), True, 'import numpy as np\n')]
import logging import os from typing import ( Optional, ) import numpy as np import psycopg2 import tensorflow as tf from molecule_game.mol_preprocessor import ( MolPreprocessor, atom_featurizer, bond_featurizer, ) from rdkit.Chem.rdmolfiles import MolFromSmiles from tensorflow.python.keras.preprocessing.sequence import pad_sequences from examples.old.stable_radical_optimization.run_mcts import predict from molecule_game.stable_radical_optimization.stable_radical_optimization_state import StableRadicalOptimizationState from rlmolecule.alphazero.alphazero_problem import AlphaZeroProblem from rlmolecule.alphazero.alphazero_vertex import AlphaZeroVertex from rlmolecule.molecule.policy.model import build_policy_evaluator from rlmolecule.molecule.policy.preprocessor import load_preprocessor logger = logging.getLogger(__name__) default_preprocessor = MolPreprocessor(atom_features=atom_featurizer, bond_features=bond_featurizer, explicit_hs=False) default_preprocessor.from_json(os.path.join( os.path.dirname(os.path.abspath(__file__)), '../../molecule_game/preprocessor.json')) class StableRadicalOptimizationProblem(AlphaZeroProblem): """ An AlphaZeroProblem that implements a stable radical optimization search. """ def __init__( self, config: any, start_smiles: str, preprocessor: Optional[MolPreprocessor] = None, preprocessor_data=None, policy_checkpoint_dir=None, ) -> None: # super().__init__( # config.min_reward, # config.pb_c_base, # config.pb_c_init, # config.dirichlet_noise, # config.dirichlet_alpha, # config.dirichlet_x, # ) self._config: any = config self._start_smiles: str = start_smiles assert (preprocessor is None and preprocessor_data is not None) or \ (preprocessor is not None and preprocessor_data is None) self._preprocessor: MolPreprocessor = preprocessor if preprocessor else load_preprocessor(preprocessor_data) policy_evaluator, loaded_checkpoint = build_policy_evaluator(policy_checkpoint_dir) self._policy_evaluator: tf.function = policy_evaluator if loaded_checkpoint: logger.info(f'{self.id}: Loaded checkpoint {loaded_checkpoint}') else: logger.info(f'{self.id}: No checkpoint found {loaded_checkpoint}') # memoizer, start = \ # AlphaZeroNode.make_memoized_root_node( # StableRadicalOptimizationState(self, MolFromSmiles(start_smiles), False), self) # # self._graph_memoizer: NetworkXNodeMemoizer = memoizer # self._start: AlphaZeroNode = start # self._policy_trainer = build_policy_trainer() # self._policy_model = self._policy_trainer.layers[-1].policy_model # self._policy_predictions = tf.function(experimental_relax_shapes=True)(self._policy_model.predict_step) # self.load_from_checkpoint() # TODO: does this ever do anything? pass @property def config(self) -> any: return self._config def get_initial_state(self) -> StableRadicalOptimizationState: return StableRadicalOptimizationState(MolFromSmiles(self._start_smiles), self._config, False) def get_reward(self, state: StableRadicalOptimizationState, policy_inputs: any) -> float: config = self.config reward = None # TODO: consider factoring out this database memoization code with psycopg2.connect(**config.dbparams) as conn: with conn.cursor() as cur: cur.execute( "select real_reward from {table}_reward where smiles = %s".format( table=config.sql_basename), (state.smiles,)) result = cur.fetchone() if result: reward = result[0] if reward is None: if ((policy_inputs['atom'] == 1).any() | (policy_inputs['bond'] == 1).any()): # Node is outside the domain of validity # self._true_reward = 0. return config.min_reward else: spins, buried_vol = predict( {key: tf.constant(np.expand_dims(val, 0)) for key, val in policy_inputs.items()}) spins = spins.numpy().flatten() buried_vol = buried_vol.numpy().flatten() atom_index = int(spins.argmax()) max_spin = spins[atom_index] spin_buried_vol = buried_vol[atom_index] atom_type = state.molecule.GetAtomWithIdx(atom_index).GetSymbol() # This is a bit of a placeholder; but the range for spin is about 1/50th that # of buried volume. reward = (1 - max_spin) * 50 + spin_buried_vol with psycopg2.connect(**config.dbparams) as conn: with conn.cursor() as cur: cur.execute(""" INSERT INTO {table}_reward (smiles, real_reward, atom_type, buried_vol, max_spin, atom_index) values (%s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING;""".format(table=config.sql_basename), ( state.smiles, float(reward), atom_type, # This should be the real reward float(spin_buried_vol), float(max_spin), atom_index)) ranked_reward = self._get_ranked_rewards(reward) # TODO: do we want to store this here? # node._true_reward = reward return ranked_reward def get_value_and_policy(self, successors: [AlphaZeroVertex]) -> (float, {AlphaZeroVertex: float}): values, prior_logits = self._policy_evaluator(self._make_batched_policy_inputs(successors)) # inputs to policy network priors = tf.nn.softmax(prior_logits[1:]).numpy().flatten() # Update child nodes with predicted prior_logits successor_priors = {node: prior for node, prior in zip(successors, priors)} value = float(tf.nn.sigmoid(values[0])) return value, successor_priors def _make_batched_policy_inputs(self, vertices: [AlphaZeroVertex]) -> {}: """ :return the given verticies policy inputs concatenated together. Used as the inputs for the policy neural network. """ policy_inputs = [self._get_policy_inputs(vertex) for vertex in vertices] return {key: pad_sequences([elem[key] for elem in policy_inputs], padding='post') for key in policy_inputs[0].keys()} def _get_policy_inputs(self, vertex: AlphaZeroVertex) -> {}: """ :return GNN inputs for the node """ # TODO: memoize # if self._policy_inputs is None: # self._policy_inputs = self.game.preprocessor.construct_feature_matrices(self) # return self._policy_inputs # noinspection PyUnresolvedReferences return self._preprocessor.construct_feature_matrices(vertex.state.molecule) def _get_ranked_rewards(self, reward: float) -> float: config = self.config with psycopg2.connect(**config.dbparams) as conn: with conn.cursor() as cur: cur.execute("select count(*) from {table}_game where experiment_id = %s;".format( table=config.sql_basename), (config.experiment_id,)) n_games = cur.fetchone()[0] if n_games < config.reward_buffer_min_size: # Here, we don't have enough of a game buffer # to decide if the move is good or not logging.debug(f"ranked_reward: not enough games ({n_games})") return np.random.choice([0., 1.]) else: with conn.cursor() as cur: cur.execute(""" select percentile_disc(%s) within group (order by real_reward) from (select real_reward from {table}_game where experiment_id = %s order by id desc limit %s) as finals """.format(table=config.sql_basename), (config.ranked_reward_alpha, config.experiment_id, config.reward_buffer_max_size)) r_alpha = cur.fetchone()[0] logging.debug(f"ranked_reward: r_alpha={r_alpha}, reward={reward}") if np.isclose(reward, r_alpha): return np.random.choice([0., 1.]) elif reward > r_alpha: return 1. elif reward < r_alpha: return 0.
[ "rdkit.Chem.rdmolfiles.MolFromSmiles", "numpy.random.choice", "rlmolecule.molecule.policy.model.build_policy_evaluator", "os.path.abspath", "logging.debug", "tensorflow.nn.softmax", "numpy.expand_dims", "numpy.isclose", "molecule_game.mol_preprocessor.MolPreprocessor", "rlmolecule.molecule.policy.preprocessor.load_preprocessor", "tensorflow.python.keras.preprocessing.sequence.pad_sequences", "tensorflow.nn.sigmoid", "logging.getLogger", "psycopg2.connect" ]
[((825, 852), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (842, 852), False, 'import logging\n'), ((877, 978), 'molecule_game.mol_preprocessor.MolPreprocessor', 'MolPreprocessor', ([], {'atom_features': 'atom_featurizer', 'bond_features': 'bond_featurizer', 'explicit_hs': '(False)'}), '(atom_features=atom_featurizer, bond_features=\n bond_featurizer, explicit_hs=False)\n', (892, 978), False, 'from molecule_game.mol_preprocessor import MolPreprocessor, atom_featurizer, bond_featurizer\n'), ((2228, 2273), 'rlmolecule.molecule.policy.model.build_policy_evaluator', 'build_policy_evaluator', (['policy_checkpoint_dir'], {}), '(policy_checkpoint_dir)\n', (2250, 2273), False, 'from rlmolecule.molecule.policy.model import build_policy_evaluator\n'), ((1118, 1143), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1133, 1143), False, 'import os\n'), ((2144, 2180), 'rlmolecule.molecule.policy.preprocessor.load_preprocessor', 'load_preprocessor', (['preprocessor_data'], {}), '(preprocessor_data)\n', (2161, 2180), False, 'from rlmolecule.molecule.policy.preprocessor import load_preprocessor\n'), ((3359, 3392), 'rdkit.Chem.rdmolfiles.MolFromSmiles', 'MolFromSmiles', (['self._start_smiles'], {}), '(self._start_smiles)\n', (3372, 3392), False, 'from rdkit.Chem.rdmolfiles import MolFromSmiles\n'), ((3645, 3680), 'psycopg2.connect', 'psycopg2.connect', ([], {}), '(**config.dbparams)\n', (3661, 3680), False, 'import psycopg2\n'), ((6311, 6335), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['values[0]'], {}), '(values[0])\n', (6324, 6335), True, 'import tensorflow as tf\n'), ((6713, 6781), 'tensorflow.python.keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['[elem[key] for elem in policy_inputs]'], {'padding': '"""post"""'}), "([elem[key] for elem in policy_inputs], padding='post')\n", (6726, 6781), False, 'from tensorflow.python.keras.preprocessing.sequence import pad_sequences\n'), ((7392, 7427), 'psycopg2.connect', 'psycopg2.connect', ([], {}), '(**config.dbparams)\n', (7408, 7427), False, 'import psycopg2\n'), ((7881, 7942), 'logging.debug', 'logging.debug', (['f"""ranked_reward: not enough games ({n_games})"""'], {}), "(f'ranked_reward: not enough games ({n_games})')\n", (7894, 7942), False, 'import logging\n'), ((7966, 7994), 'numpy.random.choice', 'np.random.choice', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (7982, 7994), True, 'import numpy as np\n'), ((8597, 8664), 'logging.debug', 'logging.debug', (['f"""ranked_reward: r_alpha={r_alpha}, reward={reward}"""'], {}), "(f'ranked_reward: r_alpha={r_alpha}, reward={reward}')\n", (8610, 8664), False, 'import logging\n'), ((8685, 8712), 'numpy.isclose', 'np.isclose', (['reward', 'r_alpha'], {}), '(reward, r_alpha)\n', (8695, 8712), True, 'import numpy as np\n'), ((5033, 5068), 'psycopg2.connect', 'psycopg2.connect', ([], {}), '(**config.dbparams)\n', (5049, 5068), False, 'import psycopg2\n'), ((8741, 8769), 'numpy.random.choice', 'np.random.choice', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (8757, 8769), True, 'import numpy as np\n'), ((6097, 6128), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['prior_logits[1:]'], {}), '(prior_logits[1:])\n', (6110, 6128), True, 'import tensorflow as tf\n'), ((4390, 4412), 'numpy.expand_dims', 'np.expand_dims', (['val', '(0)'], {}), '(val, 0)\n', (4404, 4412), True, 'import numpy as np\n')]
from typing import Iterable, Union import numpy as np class DistributionTransformer: def __init__(self, num_bins: int = 300, use_density: bool = True): """ Instantiate a new distribution transformer that extracts distribution information from input values. Parameters ---------- num_bins : int Defines the dimension of the resulting distribution representation and the number of equal-width bins. use_density : bool If True the distribution representation defines a probability density function rather than just a count histogram. """ self._num_bins = num_bins self._use_density = use_density @property def num_bins(self) -> int: return self._num_bins @property def use_density(self) -> bool: return self._use_density def transform(self, input_values: Iterable[Union[int, float]]) -> np.ndarray: """ Generate a probability distribution representation for the given inputs. Parameters ---------- input_values : Iterable[Union[int, float]] A collection of numbers seen as a representative sample of the probability distribution. Returns ------- np.ndarray A vectorised representation of the distribution. """ input_array = np.array(input_values) if len(input_array) < 1: return np.empty(self._num_bins) input_array = input_array[~np.isnan(input_array)] hist, bin_edges = np.histogram( input_array, bins=self._num_bins, density=self._use_density ) return hist
[ "numpy.empty", "numpy.histogram", "numpy.array", "numpy.isnan" ]
[((1371, 1393), 'numpy.array', 'np.array', (['input_values'], {}), '(input_values)\n', (1379, 1393), True, 'import numpy as np\n'), ((1556, 1629), 'numpy.histogram', 'np.histogram', (['input_array'], {'bins': 'self._num_bins', 'density': 'self._use_density'}), '(input_array, bins=self._num_bins, density=self._use_density)\n', (1568, 1629), True, 'import numpy as np\n'), ((1446, 1470), 'numpy.empty', 'np.empty', (['self._num_bins'], {}), '(self._num_bins)\n', (1454, 1470), True, 'import numpy as np\n'), ((1507, 1528), 'numpy.isnan', 'np.isnan', (['input_array'], {}), '(input_array)\n', (1515, 1528), True, 'import numpy as np\n')]
# ----------------------------------------------------------------------------- # MIT License # # Copyright (c) 2018 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ----------------------------------------------------------------------------- # -- Utils # ----------------------------------------------------------------------------- import os import cv2 import dlib import json import math import numpy as np import argparse from xml import Xml from math import radians, sin, cos from cv2.dnn import blobFromImage # constants: TYPE_STR = type("") CV_FONT = cv2.FONT_HERSHEY_SIMPLEX caffe_model = "caffe/res10_300x300_ssd_iter_140000.caffemodel" caffe_proto = "caffe/deploy.prototxt" cf_values = (104.0, 177.0, 123.0) # cf_size = (300, 300) # cf_size = (200, 200) # better cf_size = (150, 150) # best, detect even small faces cf_scale = 1.0 confidence_threshold = 0.55 state_file = ".state" # global variables: caffeNet = None face_det = None shape_predictor = None # ----------------------------------------------------------------------------- # -- CLASS UTILS # ----------------------------------------------------------------------------- class Keys: '''opencv key constants''' S = 115 R = 114 Q = 113 ESC = 27 class Colors: '''a set of predefined BGR colors for drawing functions''' white = (255, 255, 255) black = (0, 0, 0) cyan = (255, 255, 128) blue = (255, 0, 0) green = (0, 255, 0) red = (0, 0, 255) yellow = (0, 255, 255) purple = (255, 64, 255) class Options: '''incapsulate a set of predefine dlib shape predictor training options''' def create(tree_depth, cascades, pool_size, splits, threads=4, oversampling=20): '''returns the option obj with the given values''' options = dlib.shape_predictor_training_options() options.tree_depth = tree_depth options.nu = 0.1 options.num_threads = threads options.cascade_depth = cascades options.be_verbose = True options.feature_pool_size = pool_size options.num_test_splits = splits options.oversampling_amount = oversampling return options def accurate(threads=4, oversampling=20): '''use to train an accurate shape-predictor, decrease [oversampling] for a faster training''' options = dlib.shape_predictor_training_options() options.tree_depth = 4 options.nu = 0.1 options.num_threads = threads options.cascade_depth = 15 options.be_verbose = True options.feature_pool_size = 800 options.num_test_splits = 150 + 50 options.oversampling_amount = oversampling return options def dlib(threads=4): '''same options used by dlib shape predictors''' options = dlib.shape_predictor_training_options() options.oversampling_amount = 40 options.num_threads = threads options.cascade_depth = 15 options.feature_pool_size = 800 options.num_test_splits = 150 options.be_verbose = True return options def mini(threads=4, oversampling=20): '''use to train a minified shape-predictor, but still accurate''' options = dlib.shape_predictor_training_options() options.tree_depth = 3 options.nu = 0.1 options.num_threads = threads options.cascade_depth = 15 options.be_verbose = True options.feature_pool_size = 800 options.num_test_splits = 150 options.oversampling_amount = oversampling return options def fast(threads=4, oversampling=20): '''use to train a minified shape-predictor, but still accurate''' options = dlib.shape_predictor_training_options() options.tree_depth = 3 options.nu = 0.1 options.num_threads = threads options.cascade_depth = 13 options.be_verbose = True options.feature_pool_size = 200 options.num_test_splits = 200 options.oversampling_amount = oversampling return options def light(threads=4, oversampling=20): '''use to train a minified shape-predictor, but still accurate''' options = dlib.shape_predictor_training_options() options.tree_depth = 2 options.nu = 0.1 options.num_threads = threads options.cascade_depth = 15 options.be_verbose = True options.feature_pool_size = 300 options.num_test_splits = 300 options.oversampling_amount = oversampling return options def lf(threads=4, oversampling=20): '''use to train a minified shape-predictor, but still accurate''' options = dlib.shape_predictor_training_options() options.tree_depth = 2 options.nu = 0.1 options.num_threads = threads options.cascade_depth = 10 options.be_verbose = True options.feature_pool_size = 200 options.num_test_splits = 300 options.oversampling_amount = oversampling return options def optimal(threads=4, oversampling=20, tree_depth=10): '''train a balanced shape predictor in terms of speed, accuracy and size''' options = dlib.shape_predictor_training_options() options.tree_depth = 3 options.nu = 0.1 options.num_threads = threads options.cascade_depth = tree_depth options.be_verbose = True options.feature_pool_size = 150 options.num_test_splits = 350 options.oversampling_amount = oversampling return options def fastest(threads=4, oversampling=20): '''use to train a minified shape-predictor, but still accurate''' options = dlib.shape_predictor_training_options() options.tree_depth = 3 options.nu = 0.1 options.num_threads = threads options.cascade_depth = 13 options.be_verbose = True options.feature_pool_size = 100 options.num_test_splits = 250 options.oversampling_amount = oversampling return options class Annotation: '''face annotations (.ann extension)''' def __init__(self, path, box=None, points=[]): assert(type(box) is Region) self.path = path self.box = [box.left, box.top, box.width, box.height] self.points = points def save(self): '''save the annotation obj to a file''' with open(self.path, "w") as f: f.write(json.dumps({'box': self.box, 'points': self.points})) def load(path): '''load an annotation obj froma file''' with open(path, 'r') as file: data = json.loads(file.read()) x, y, w, h = data["box"] points = data["points"] return Annotation(path, Region(x, y, w, h), points) def inside(folder="."): '''iterate through all annotation inside the given folder''' for img, path in images_inside(folder): folder, file = os.path.split(path) # load the annotation relative to the current image ann_path = os.path.join(folder, file.split(".")[0] + ".ann") yield Annotation.load(ann_path), path def read_ibug_annotation(path=None): '''returns an array of the points defined inside the given annotation file''' assert(path) pts = [] ann = open(path, "r") for line in ann.readlines()[3:-1]: x, y = line.split()[:2] x = int(x.split(".")[0]) y = int(y.split(".")[0]) pts.append((x, y)) return pts class Region: '''class to express rectangular region easly''' def __init__(self, x, y, w, h): '''creates a new rect: requires top-left corner (x, y) and size''' assert(w > 0 and h > 0) # dimension: self.width = int(w) self.height = int(h) self.half_w = int(self.width / 2) self.half_h = int(self.height / 2) # position: self.left = int(x) self.top = int(y) self.right = int(x + w) self.bottom = int(y + h) def square(x, y, size): '''creates a square region''' return Region(x, y, size, size) def copy(self): '''returns a copy of the current region''' return Region(self.left, self.top, self.width, self.height) def dlib(rect): '''creates a Region from a dlib rect''' return Region(rect.left(), rect.top(), rect.width(), rect.height()) def tuple(opencv_rect): '''creates a region from an opencv (left, top, right, bottom) tuple''' left, top, right, bottom = opencv_rect return Region(left, top, right - left, bottom - top) def ensure(self, width, height): '''edit the current region to respect the given dimension''' if self.left < 0: self.left = 0 if self.top < 0: self.top = 0 if self.width > width: self.width = int(width) self.half_w = int(width / 2) if self.height > height: self.height = int(height) self.half_h = int(height / 2) self.right = self.left + self.width self.bottom = self.top + self.height return self def center(self): '''return the center of the region as a tuple''' return (self.left + self.half_w, self.top + self.half_h) def move_center(self, pt): '''move the region in order to be centered at the given point''' xc, yc = pt self.left = xc - self.half_w self.right = xc + self.half_w self.top = yc - self.half_h self.bottom = yc + self.half_h return self def flip(self, width=None, height=None): '''flip the current region along x-axis if [width] is specified, and along y-axis if [height] is provided''' copy = self.copy() if width is not None: copy.right = width - self.left copy.left = copy.right - self.width if height is not None: copy.top = height - self.bottom copy.bottom = copy.top + self.height return copy def move_at(self, pt, axis=None): '''move the center of region in order to be at the given point, optionally axis can be locked''' if axis is None: return self.move_center(pt) elif axis == "x": x0 = pt[0] self.left = x0 - self.half_w self.right = x0 + self.half_w return self elif axis == "y": y0 = pt[1] self.top = y0 - self.half_h self.bottom = y0 + self.half_h return self def tl(self): '''return the top-left corner as a point-tuple (left, top)''' return (self.left, self.top) def br(self): '''return the bottom-right corner as a point-tuple (bottom, right)''' return (self.right, self.bottom) def scale(self, fx=1, fy=1): '''scale the the region by the specified factors, the scaled region will have the same center of the original one''' w = self.width * fx h = self.height * fy dw = (w - self.width) / 2 dh = (h - self.height) / 2 return Region(self.left - dw, self.top - dh, w, h) def origin(self, x=0, y=0): '''change the top-left corner of the region''' self.left = x self.top = y def area(self): '''returns the area of the region''' return self.width * self.height def unpack(self): '''returns left, top, right, bottom, width and height''' w = self.width h = self.height return self.left, self.top, self.right, self.bottom, w, h def as_dlib(self): '''returns a dlib.rectangle''' return dlib.rectangle(self.left, self.top, self.right, self.bottom) def as_tuple(self): '''returns a tuple (left, top, right, bottom) suitable for opencv''' return (self.left, self.top, self.right, self.bottom) def as_list(self): '''returns [left, top, right, bottom, width, height]''' w = self.width h = self.height return [self.left, self.top, self.right, self.bottom, w, h] # ----------------------------------------------------------------------------- def cli_arguments(): '''build and parse command line arguments''' ap = argparse.ArgumentParser() s = """ generate an output file of annotations, it the file ends with .xml it generates an xml file ready to be used with dlib """ # output file ap.add_argument("-o", "--out", required=True, help=s) # input directory ap.add_argument("-d", "--dir", required=True, help="input directory with images") # (flag) append mode ap.add_argument("-a", "--append", action="store_const", const='a', help="open the output file in append mode") # (flag) mirror points and images along x axis ap.add_argument("-m", "--mirror", action="store_true", help="mirror points and images along x axis") # (flag) detect faces automatically ap.add_argument("--auto", action="store_true", help="detect faces automatically") # (optional) detect landmarks ap.add_argument("-l", "--land", required=False, help="automatically detect landmark") # (optional) train a model ap.add_argument("-t", "--train", required=False, help="train a dlib shape-predictor model") return vars(ap.parse_args()) def void(): '''a function that does nothing''' # ----------------------------------------------------------------------------- # -- FILE UTILS # ----------------------------------------------------------------------------- def open_file(args): '''return an opened output file''' name = args["out"] mode = args["append"] or "w" if args["train"]: mode = "a" if name.endswith(".xml"): return Xml(name, mode=mode) else: return open(name, mode) def count_files_inside(directory="."): '''return the number of files (does not consider folders) in directory''' try: path, dirs, files = next(os.walk(directory)) except StopIteration: return 0 return len(files) def get_file_with(extension, at_path): '''return the the file at the given path with the given extension (if provided and without the dot)''' folder, file = os.path.split(at_path) # find the right file if extension is not None: ext = file.split(".")[-1] file = file.replace(ext, extension) path = os.path.join(folder, file) return open(path, "r") def get_associated_image(path): '''returns the path of the image file with the same name of the file at the given path''' folder, file = os.path.split(path) ext = file.split(".")[-1] exts = ["jpg", "png", "jpeg"] for e in exts: _file = file.replace(ext, e) _path = os.path.join(folder, _file) if os.path.isfile(_path): return _path def file_iter(dir=".", ext=None): '''generate all files inside the given dir with the specified extension, if [ext] is None. It generates all files''' for path, dirs, files in os.walk(dir): # scan every file in subfolders for file in files: if (ext is None) or file.endswith(ext): yield os.path.join(path, file), file for d in dirs: for p, f in file_iter(dir=os.path.join(path, d), ext=ext): yield p, f # ----------------------------------------------------------------------------- # -- IMAGE UTILS # ----------------------------------------------------------------------------- def crop_image(image, roi, ensure=False): '''returns the cropped image according to a region-of-interest, optionally force the region to be inside the image''' assert(type(roi) is Region) if ensure is True: h, w = image.shape[:2] roi = roi.ensure(w, h) l, t, r, b = roi.as_list()[:4] return image[t:b, l:r].copy() def rotate_image(image, angle=0, center=None): '''rotate the given image, by default it rotates around the center''' h, w = image.shape[:2] if center is None: center = (w / 2, h / 2) M = cv2.getRotationMatrix2D(center, angle, 1) return cv2.warpAffine(image, M, (w, h)) def delete_image(path): '''delete the given image and the mirrored one if it exists''' folder, file = os.path.split(path) # delete mirror mirror = os.path.join(folder, file.replace(".", "_mirror.")) if os.path.isfile(mirror): os.remove(mirror) os.remove(path) def is_image(file): '''check if the given file is an image''' return (file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".png")) def is_mirrored(img_file): '''check if the given image is the mirror of another one''' return img_file.find("_mirror") > 0 def flip_image(image, axis=1): '''mirror the given image along x axis by default''' return cv2.flip(image, axis) def images_inside(directory=""): '''generate all the images within the given directory, generate (image, path)''' for path, dirs, files in os.walk(directory): # scan every file in subfolders for file in files: # skip non-image file if not is_image(file): continue # load image img_path = os.path.join(path, file) yield cv2.imread(img_path), img_path for folder in dirs: for i, p in images_inside(folder): yield i, p def show_image(image, window="window", onSkip=void, onQuit=void): '''show image easly, support skip(ESC) and quit(Q) events with custom callbacks''' while True: cv2.imshow(window, image) key = cv2.waitKey(20) & 0Xff if key == Keys.ESC: return onSkip() if key == Keys.S: return True # say to skip stuff.. elif key == Keys.Q: onQuit() cv2.destroyAllWindows() return exit() def show_properly(image, size=600): '''resize too large images''' h, w = image.shape[:2] ratio = h / w fx = 1 / (w * ratio / size) fy = 1 / (h / size) return cv2.resize(image, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC) # ----------------------------------------------------------------------------- # -- FACE UTILS # ----------------------------------------------------------------------------- def init_face_detector(flag=False, size=150, scale_factor=1.0): '''load the caffe-model if --auto flag is specified, typical values are: 224, 227, 299, 321''' global caffeNet, cf_size, cf_scale if flag is True: cf_size = (size, size) cf_scale = scale_factor caffeNet = cv2.dnn.readNetFromCaffe(caffe_proto, caffe_model) def detect_faces(image, detector="cnn"): '''detect every face inside image. By default it uses the cnn detector, pass "dlib" to use the dlib frontal face detector. Returns a list of tuple\\rectangles: (top, left, right, bottom)''' # detect faces with dlib.frontal_face_detector if detector == "dlib": # load detector if needed global face_det if face_det is None: face_det = dlib.get_frontal_face_detector() dets = face_det(image, 1) boxes = [] for d in dets: boxes.append(Region.dlib(d)) return boxes # detect faces with opencv caffe cnn detector assert(caffeNet) # get image dimension (h, w) = image.shape[:2] np_arr = np.array([w, h, w, h]) if h <= 0 or w <= 0: return [] # convert image to blob (that do some preprocessing..) blob = blobFromImage(cv2.resize(image, cf_size), cf_scale, size=cf_size, mean=cf_values, swapRB=True) # obtain detections and predictions caffeNet.setInput(blob) detections = caffeNet.forward() # detected face-boxes boxes = [] for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence >= confidence_threshold: # compute the bounding box of the face box = detections[0, 0, i, 3:7] * np_arr boxes.append(Region.tuple(box.astype("int"))) return boxes def faces_inside(directory="", scale_factor=1, remove_image=False): '''generate all faces within a given directory and optionally remove the images''' for path, dirs, files in os.walk(directory): # scan every file in subfolders for file in files: # skip non-image file if not is_image(file): continue # load image img_path = os.path.join(path, file) image = cv2.imread(img_path) # detect faces within image regions = detect_faces(image) for region in regions: # crop the region if scale_factor != 1: region = region.scale(scale_factor, scale_factor) face = crop_image(image, region) yield face, region if remove_image is True: os.remove(os.path.join(path, file)) # explore subfolders for folder in dirs: d = os.path.join(path, folder) for _face, _region in faces_inside(d, scale_factor, remove_image): yield _face, _region def is_face_aligned_with_landmarks(rect, points): '''decide if the face is aligned with the landmarks by comparing either boundin-boxes.''' print("warning [is_face_aligned_with_landmarks]: code changed!") assert(type(rect) is Region) region = points_region(points) # a, b, c, d = region # t, l, r, b = rect # get intersection rect # r1 = dlib.rectangle(l, t, r, b) # r2 = dlib.rectangle(b, a, c, d) r1 = rect.as_dlib() r2 = region.as_dlib() r3 = r1.intersect(r2) # area a1 = r1.area() a2 = r3.area() print(r1) print(r2) print(a1, r3, a2) if a1 == 0 or a2 == 0: return False print(a1 / a2) return (a1 / a2) >= 0.55 def ibug_dataset(folder="."): '''iterate through the ibug dataset-like generating: image, landmarks''' for fpath, fname in file_iter(folder, ext=".pts"): # retrive image ipath = get_associated_image(fpath) image = cv2.imread(ipath) # read landmarks marks = Annotation.read_ibug_annotation(fpath) yield image, marks, fpath def prominent_face(faces): '''returns the bigger (prominent) face (Region obj)''' max_area = -2 ^ 31 max_face = None for face in faces: assert(type(face) is Region) area = face.area() if area > max_area: max_area = area max_face = face return max_face def frontal_face(image, face, eye_sx, eye_dx): '''returns rotated image and rotatation in degrees''' assert(type(face) is Region) dy = eye_dx[1] - eye_sx[1] dx = eye_dx[0] - eye_sx[0] angle = math.degrees(math.atan2(dy, dx)) return rotate_image(image, angle, face.center()), angle # ----------------------------------------------------------------------------- # -- LANDMARK UTILS # ----------------------------------------------------------------------------- def load_shape_predictor(model_path): '''load the dlib shape predictor model''' global shape_predictor shape_predictor = dlib.shape_predictor(model_path) def detect_landmarks(face, region): '''detect landmarks for the given face and face Region, returns an array of tuples (x, y)''' assert(type(region) is Region) rect = region.as_dlib() shape = shape_predictor(face, rect) points = [] for i in range(0, shape.num_parts): point = shape.part(i) points.append((point.x, point.y)) return points def rotate_landmarks(points, center, angle=0): '''rotate the given points according to the specified angle''' rad = radians(-angle) siny = sin(rad) cosx = cos(rad) new_pts = [] for p in points: x = p[0] - center[0] y = p[1] - center[1] px = int(x * cosx - y * siny + center[0]) py = int(x * siny + y * cosx + center[1]) new_pts.append((px, py)) return new_pts def points_region(pts): '''return a Region obj that contains all the given points''' assert(len(pts) > 1) left = min(pts, key=lambda p: p[0])[0] right = max(pts, key=lambda p: p[0])[0] top = min(pts, key=lambda p: p[1])[1] bottom = max(pts, key=lambda p: p[1])[1] return Region.tuple((left, top, right, bottom)) def naive_flip_landmarks(points, width): '''flipping naively 68-landmark point''' pts = points.copy() # adjust position for i in range(0, 68): x, y = pts[i] x = width - x pts[i] = (x, y) # swapping items for i in range(0, 8): pts[i], pts[16 - i] = pts[16 - i], pts[i] for i in range(0, 5): pts[17 + i], pts[26 - i] = pts[26 - i], pts[17 + i] pts[31], pts[35] = pts[35], pts[31] pts[32], pts[34] = pts[34], pts[32] for i in range(0, 4): pts[36 + i], pts[45 - i] = pts[45 - i], pts[36 + i] pts[40], pts[47] = pts[47], pts[40] pts[41], pts[46] = pts[46], pts[41] pts[48], pts[54] = pts[54], pts[48] pts[49], pts[53] = pts[53], pts[49] pts[50], pts[52] = pts[52], pts[50] pts[59], pts[55] = pts[55], pts[59] pts[58], pts[56] = pts[56], pts[58] pts[60], pts[64] = pts[64], pts[60] pts[61], pts[63] = pts[63], pts[61] pts[67], pts[65] = pts[65], pts[67] return pts # ----------------------------------------------------------------------------- # -- DRAWING UTILS # ----------------------------------------------------------------------------- def draw_rect(image, rect, color=(128, 0, 128), thickness=2, label=None): '''draw the given rectangle (Region obj) on image, with an optional label''' assert(type(rect) is Region) cv2.rectangle(image, rect.tl(), rect.br(), color, thickness) # puts a label on-top of the rect if type(label) == TYPE_STR: fscale = int(1 + (rect.height / 600) + (rect.width / 600)) / 2 size, pt = cv2.getTextSize(label, CV_FONT, fscale, 1) w, h = size[0] * 1.1, size[1] * 1.4 top = int(rect.top - pt / 2 - 3) label_rect = Region(rect.left, rect.top - h, w, h) draw_rect(image, label_rect, color=color, thickness=-1) cv2.putText(image, label, (rect.left + 4, top), CV_FONT, fscale, Colors.white) def draw_rects(image, regions, color=(128, 0, 128), thickness=2): '''draws an array of Region obj''' for r in regions: cv2.rectangle(image, r.tl(), r.br(), color, thickness) def draw_point(image, x, y, radius=-1, color=(0, 255, 255), thickness=-1): '''draw a circle on image at the given coordinate''' if radius <= -1: h, w = image.shape[:2] radius = int(2 + (h / 600) + (w / 600)) cv2.circle(image, (x, y), radius, color, thickness) def draw_points(image, points, radius=-1, font=CV_FONT, color=(0, 255, 255), thickness=-1, text=True): '''draw a list of (x, y) point tuple''' if radius <= -1: h, w = image.shape[:2] radius = int(2 + (h / 600) + (w / 600)) for i, p in enumerate(points): cv2.circle(image, (p[0], p[1]), radius, color, thickness) if text: cv2.putText(image, str(i), (p[0], p[1]), font, radius / 10, Colors.white) def draw_face_landmarks(image, landmarks, color=Colors.green, tickness=1): '''mimic the render_face_detections dlib function''' assert(len(landmarks) == 68) # Around Chin. Ear to Ear for i in range(0, 16): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) # left eyebrow for i in range(17, 21): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) # right eyebrow for i in range(22, 26): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) # line on top of nose for i in range(27, 30): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) # bottom part of the nose for i in range(31, 35): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) # Line from the nose to the bottom part above cv2.line(image, landmarks[31], landmarks[30], color, tickness, cv2.LINE_AA) cv2.line(image, landmarks[35], landmarks[30], color, tickness, cv2.LINE_AA) # left eye for i in range(36, 41): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) cv2.line(image, landmarks[36], landmarks[41], color, tickness, cv2.LINE_AA) # right eye for i in range(42, 47): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) cv2.line(image, landmarks[42], landmarks[47], color, tickness, cv2.LINE_AA) # lips: outer part for i in range(48, 59): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) cv2.line(image, landmarks[48], landmarks[59], color, tickness, cv2.LINE_AA) # lips: inside part for i in range(60, 67): p1 = landmarks[i] p2 = landmarks[i + 1] cv2.line(image, p1, p2, color, tickness, cv2.LINE_AA) cv2.line(image, landmarks[60], landmarks[67], color, tickness, cv2.LINE_AA) # -----------------------------------------------------------------------------
[ "os.remove", "argparse.ArgumentParser", "math.atan2", "os.walk", "xml.Xml", "json.dumps", "cv2.warpAffine", "os.path.isfile", "dlib.rectangle", "dlib.shape_predictor", "os.path.join", "cv2.getRotationMatrix2D", "cv2.imshow", "cv2.line", "math.radians", "math.cos", "cv2.destroyAllWindows", "cv2.resize", "cv2.circle", "cv2.waitKey", "math.sin", "dlib.get_frontal_face_detector", "cv2.flip", "cv2.putText", "cv2.getTextSize", "cv2.imread", "numpy.array", "dlib.shape_predictor_training_options", "cv2.dnn.readNetFromCaffe", "os.path.split" ]
[((13508, 13533), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (13531, 13533), False, 'import argparse\n'), ((15612, 15634), 'os.path.split', 'os.path.split', (['at_path'], {}), '(at_path)\n', (15625, 15634), False, 'import os\n'), ((15782, 15808), 'os.path.join', 'os.path.join', (['folder', 'file'], {}), '(folder, file)\n', (15794, 15808), False, 'import os\n'), ((15988, 16007), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (16001, 16007), False, 'import os\n'), ((16423, 16435), 'os.walk', 'os.walk', (['dir'], {}), '(dir)\n', (16430, 16435), False, 'import os\n'), ((17482, 17523), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', 'angle', '(1)'], {}), '(center, angle, 1)\n', (17505, 17523), False, 'import cv2\n'), ((17536, 17568), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'M', '(w, h)'], {}), '(image, M, (w, h))\n', (17550, 17568), False, 'import cv2\n'), ((17681, 17700), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (17694, 17700), False, 'import os\n'), ((17795, 17817), 'os.path.isfile', 'os.path.isfile', (['mirror'], {}), '(mirror)\n', (17809, 17817), False, 'import os\n'), ((17850, 17865), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (17859, 17865), False, 'import os\n'), ((18266, 18287), 'cv2.flip', 'cv2.flip', (['image', 'axis'], {}), '(image, axis)\n', (18274, 18287), False, 'import cv2\n'), ((18442, 18460), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (18449, 18460), False, 'import os\n'), ((19525, 19593), 'cv2.resize', 'cv2.resize', (['image', 'None'], {'fx': 'fx', 'fy': 'fy', 'interpolation': 'cv2.INTER_CUBIC'}), '(image, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC)\n', (19535, 19593), False, 'import cv2\n'), ((20889, 20911), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (20897, 20911), True, 'import numpy as np\n'), ((21800, 21818), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (21807, 21818), False, 'import os\n'), ((24798, 24830), 'dlib.shape_predictor', 'dlib.shape_predictor', (['model_path'], {}), '(model_path)\n', (24818, 24830), False, 'import dlib\n'), ((25348, 25363), 'math.radians', 'radians', (['(-angle)'], {}), '(-angle)\n', (25355, 25363), False, 'from math import radians, sin, cos\n'), ((25375, 25383), 'math.sin', 'sin', (['rad'], {}), '(rad)\n', (25378, 25383), False, 'from math import radians, sin, cos\n'), ((25395, 25403), 'math.cos', 'cos', (['rad'], {}), '(rad)\n', (25398, 25403), False, 'from math import radians, sin, cos\n'), ((28392, 28443), 'cv2.circle', 'cv2.circle', (['image', '(x, y)', 'radius', 'color', 'thickness'], {}), '(image, (x, y), radius, color, thickness)\n', (28402, 28443), False, 'import cv2\n'), ((30020, 30095), 'cv2.line', 'cv2.line', (['image', 'landmarks[31]', 'landmarks[30]', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, landmarks[31], landmarks[30], color, tickness, cv2.LINE_AA)\n', (30028, 30095), False, 'import cv2\n'), ((30100, 30175), 'cv2.line', 'cv2.line', (['image', 'landmarks[35]', 'landmarks[30]', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, landmarks[35], landmarks[30], color, tickness, cv2.LINE_AA)\n', (30108, 30175), False, 'import cv2\n'), ((30342, 30417), 'cv2.line', 'cv2.line', (['image', 'landmarks[36]', 'landmarks[41]', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, landmarks[36], landmarks[41], color, tickness, cv2.LINE_AA)\n', (30350, 30417), False, 'import cv2\n'), ((30585, 30660), 'cv2.line', 'cv2.line', (['image', 'landmarks[42]', 'landmarks[47]', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, landmarks[42], landmarks[47], color, tickness, cv2.LINE_AA)\n', (30593, 30660), False, 'import cv2\n'), ((30835, 30910), 'cv2.line', 'cv2.line', (['image', 'landmarks[48]', 'landmarks[59]', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, landmarks[48], landmarks[59], color, tickness, cv2.LINE_AA)\n', (30843, 30910), False, 'import cv2\n'), ((31086, 31161), 'cv2.line', 'cv2.line', (['image', 'landmarks[60]', 'landmarks[67]', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, landmarks[60], landmarks[67], color, tickness, cv2.LINE_AA)\n', (31094, 31161), False, 'import cv2\n'), ((2820, 2859), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (2857, 2859), False, 'import dlib\n'), ((3374, 3413), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (3411, 3413), False, 'import dlib\n'), ((3835, 3874), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (3872, 3874), False, 'import dlib\n'), ((4267, 4306), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (4304, 4306), False, 'import dlib\n'), ((4765, 4804), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (4802, 4804), False, 'import dlib\n'), ((5264, 5303), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (5301, 5303), False, 'import dlib\n'), ((5760, 5799), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (5797, 5799), False, 'import dlib\n'), ((6286, 6325), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (6323, 6325), False, 'import dlib\n'), ((6795, 6834), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (6832, 6834), False, 'import dlib\n'), ((12919, 12979), 'dlib.rectangle', 'dlib.rectangle', (['self.left', 'self.top', 'self.right', 'self.bottom'], {}), '(self.left, self.top, self.right, self.bottom)\n', (12933, 12979), False, 'import dlib\n'), ((15131, 15151), 'xml.Xml', 'Xml', (['name'], {'mode': 'mode'}), '(name, mode=mode)\n', (15134, 15151), False, 'from xml import Xml\n'), ((16145, 16172), 'os.path.join', 'os.path.join', (['folder', '_file'], {}), '(folder, _file)\n', (16157, 16172), False, 'import os\n'), ((16185, 16206), 'os.path.isfile', 'os.path.isfile', (['_path'], {}), '(_path)\n', (16199, 16206), False, 'import os\n'), ((17827, 17844), 'os.remove', 'os.remove', (['mirror'], {}), '(mirror)\n', (17836, 17844), False, 'import os\n'), ((19033, 19058), 'cv2.imshow', 'cv2.imshow', (['window', 'image'], {}), '(window, image)\n', (19043, 19058), False, 'import cv2\n'), ((20082, 20132), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (['caffe_proto', 'caffe_model'], {}), '(caffe_proto, caffe_model)\n', (20106, 20132), False, 'import cv2\n'), ((21041, 21067), 'cv2.resize', 'cv2.resize', (['image', 'cf_size'], {}), '(image, cf_size)\n', (21051, 21067), False, 'import cv2\n'), ((23715, 23732), 'cv2.imread', 'cv2.imread', (['ipath'], {}), '(ipath)\n', (23725, 23732), False, 'import cv2\n'), ((24402, 24420), 'math.atan2', 'math.atan2', (['dy', 'dx'], {}), '(dy, dx)\n', (24412, 24420), False, 'import math\n'), ((27601, 27643), 'cv2.getTextSize', 'cv2.getTextSize', (['label', 'CV_FONT', 'fscale', '(1)'], {}), '(label, CV_FONT, fscale, 1)\n', (27616, 27643), False, 'import cv2\n'), ((27862, 27940), 'cv2.putText', 'cv2.putText', (['image', 'label', '(rect.left + 4, top)', 'CV_FONT', 'fscale', 'Colors.white'], {}), '(image, label, (rect.left + 4, top), CV_FONT, fscale, Colors.white)\n', (27873, 27940), False, 'import cv2\n'), ((28753, 28810), 'cv2.circle', 'cv2.circle', (['image', '(p[0], p[1])', 'radius', 'color', 'thickness'], {}), '(image, (p[0], p[1]), radius, color, thickness)\n', (28763, 28810), False, 'import cv2\n'), ((29228, 29281), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (29236, 29281), False, 'import cv2\n'), ((29394, 29447), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (29402, 29447), False, 'import cv2\n'), ((29561, 29614), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (29569, 29614), False, 'import cv2\n'), ((29734, 29787), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (29742, 29787), False, 'import cv2\n'), ((29911, 29964), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (29919, 29964), False, 'import cv2\n'), ((30284, 30337), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (30292, 30337), False, 'import cv2\n'), ((30527, 30580), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (30535, 30580), False, 'import cv2\n'), ((30777, 30830), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (30785, 30830), False, 'import cv2\n'), ((31028, 31081), 'cv2.line', 'cv2.line', (['image', 'p1', 'p2', 'color', 'tickness', 'cv2.LINE_AA'], {}), '(image, p1, p2, color, tickness, cv2.LINE_AA)\n', (31036, 31081), False, 'import cv2\n'), ((8059, 8078), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (8072, 8078), False, 'import os\n'), ((15355, 15373), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (15362, 15373), False, 'import os\n'), ((18672, 18696), 'os.path.join', 'os.path.join', (['path', 'file'], {}), '(path, file)\n', (18684, 18696), False, 'import os\n'), ((19073, 19088), 'cv2.waitKey', 'cv2.waitKey', (['(20)'], {}), '(20)\n', (19084, 19088), False, 'import cv2\n'), ((20574, 20606), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (20604, 20606), False, 'import dlib\n'), ((22030, 22054), 'os.path.join', 'os.path.join', (['path', 'file'], {}), '(path, file)\n', (22042, 22054), False, 'import os\n'), ((22075, 22095), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (22085, 22095), False, 'import cv2\n'), ((22607, 22633), 'os.path.join', 'os.path.join', (['path', 'folder'], {}), '(path, folder)\n', (22619, 22633), False, 'import os\n'), ((7548, 7600), 'json.dumps', 'json.dumps', (["{'box': self.box, 'points': self.points}"], {}), "({'box': self.box, 'points': self.points})\n", (7558, 7600), False, 'import json\n'), ((19289, 19312), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (19310, 19312), False, 'import cv2\n'), ((16671, 16692), 'os.path.join', 'os.path.join', (['path', 'd'], {}), '(path, d)\n', (16683, 16692), False, 'import os\n'), ((18716, 18736), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (18726, 18736), False, 'import cv2\n'), ((22507, 22531), 'os.path.join', 'os.path.join', (['path', 'file'], {}), '(path, file)\n', (22519, 22531), False, 'import os\n'), ((16578, 16602), 'os.path.join', 'os.path.join', (['path', 'file'], {}), '(path, file)\n', (16590, 16602), False, 'import os\n')]
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys import torch import time import torch.optim as optim import torch.nn.functional as F import numpy as np from haversine import haversine from models import get_model from dataProcess import preprocess_data, process_data from utils import sgc_precompute, parse_args def train_regression(model, train_features, train_labels, val_features, U_dev, classLatMedian, classLonMedian, userLocation, epochs=100, weight_decay=5e-6, lr=0.01, patience=10, model_file='myModel.pkl'): optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) train_patience = 0 val_acc_best = -1 epoch_best = 0 for epoch in range(1, epochs + 1): model.train() optimizer.zero_grad() output = model(train_features) loss_train = F.cross_entropy(output, train_labels) loss_train.backward() optimizer.step() '''verification, no gradient descent''' _, _, val_acc, _, _, _ = geo_eval(model, val_features, U_dev, classLatMedian, classLonMedian, userLocation) '''show val_acc,val_acc_best every 50 epoch''' if epoch % 50 == 0: print("epoch:{}\t \tval_acc:{}\t \tval_acc_best:{}".format(epoch, val_acc, val_acc_best)) '''apply early stop using val_acc_best, and save model''' if val_acc > val_acc_best: val_acc_best = val_acc epoch_best = epoch train_patience = 0 torch.save(model.state_dict(), model_file) else: train_patience += 1 if train_patience == patience: print("Early stop! \t epoch_best:{}\t \t \tval_acc_best:{}".format(epoch_best, val_acc_best)) break return val_acc_best, epoch_best def train_regression2(model, train_features, train_labels, val_features, U_dev, classLatMedian, classLonMedian, userLocation, epochs=100, weight_decay=5e-6, lr=0.01, patience=10, model_file='myModel.pkl', cluster_nodes=None, cluster_adj=None, node2cluster_arr=None): optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) train_patience = 0 val_acc_best = -1 epoch_best = 0 train_len = train_features.shape[0] for epoch in range(1, epochs + 1): model.train() optimizer.zero_grad() output = model(train_features, node2cluster_arr[0:train_len], cluster_nodes, cluster_adj) loss_train = F.cross_entropy(output, train_labels) loss_train.backward() optimizer.step() '''verification, no gradient descent''' _, _, val_acc, _, _, _ = geo_eval2(model, val_features, U_dev, classLatMedian, classLonMedian, userLocation, node2cluster_arr[train_len:train_len + val_features.shape[0]]) '''show val_acc,val_acc_best every 50 epoch''' if epoch % 50 == 0: print("epoch:{}\t \tval_acc:{}\t \tval_acc_best:{}".format(epoch, val_acc, val_acc_best)) '''apply early stop using val_acc_best, and save model''' if val_acc > val_acc_best: val_acc_best = val_acc epoch_best = epoch train_patience = 0 # torch.save(model.state_dict(), model_file) torch.save(model, model_file) else: train_patience += 1 if train_patience == patience: print("Early stop! \t epoch_best:{}\t \t \tval_acc_best:{}".format(epoch_best, val_acc_best)) break return val_acc_best, epoch_best def geo_eval(model, features, U_test, classLatMedian, classLonMedian, userLocation): with torch.no_grad(): model.eval() y_pred = model(features) y_pred = y_pred.data.cpu().numpy() y_pred = np.argmax(y_pred, axis=1) # 1代表行 assert len(y_pred) == len(U_test), "#preds: %d, #users: %d" % (len(y_pred), len(U_test)) distances = [] latlon_pred = [] latlon_true = [] for i in range(0, len(y_pred)): user = U_test[i] location = userLocation[user].split(',') lat, lon = float(location[0]), float(location[1]) latlon_true.append([lat, lon]) prediction = str(y_pred[i]) lat_pred, lon_pred = classLatMedian[prediction], classLonMedian[prediction] latlon_pred.append([lat_pred, lon_pred, y_pred[i]]) distance = haversine((lat, lon), (lat_pred, lon_pred)) distances.append(distance) acc_at_161 = 100 * len([d for d in distances if d < 161]) / float(len(distances)) return np.mean(distances), np.median(distances), acc_at_161, distances, latlon_true, latlon_pred def geo_eval2(model, features, U_test, classLatMedian, classLonMedian, userLocation, node2cluster_arr): with torch.no_grad(): model.eval() y_pred = model(features, node2cluster_arr) y_pred = y_pred.data.cpu().numpy() y_pred = np.argmax(y_pred, axis=1) # 1代表行 assert len(y_pred) == len(U_test), "#preds: %d, #users: %d" % (len(y_pred), len(U_test)) distances = [] latlon_pred = [] latlon_true = [] for i in range(0, len(y_pred)): user = U_test[i] location = userLocation[user].split(',') lat, lon = float(location[0]), float(location[1]) latlon_true.append([lat, lon]) prediction = str(y_pred[i]) lat_pred, lon_pred = classLatMedian[prediction], classLonMedian[prediction] latlon_pred.append([lat_pred, lon_pred, y_pred[i]]) distance = haversine((lat, lon), (lat_pred, lon_pred)) distances.append(distance) acc_at_161 = 100 * len([d for d in distances if d < 161]) / float(len(distances)) return np.mean(distances), np.median(distances), acc_at_161, distances, latlon_true, latlon_pred def main(): """ preprocess_data() : load data from dataset and precess data into numpy format process_data() : port the data to pyTorch and convert to cuda U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation : only use when Valid and Test """ data = preprocess_data(args) data = process_data(data, args) (adj, features, labels, idx_train, idx_val, idx_test, U_train, U_dev, U_test, classLatMedian, classLonMedian, userLocation, cluster_nodes, cluster_adj, node2cluster_arr) = data """ get model and train input_dim: features.size(1) # equal 9467 for ./data/cmu output_dim: labels.max().item() + 1 # equal 129 for ./data/cmu """ model = get_model(args.model, features.shape[1], labels.max().item() + 1, usecuda=args.usecuda) model_file = "./result/model/{}_lr_{}.pkl".format(args.model, str(args.lr)) if args.model == "SGC": if args.vis == "vis": from plotFunc import draw_representations for i in range(1, 5): draw_representations(features, labels, k=4, seed=77, do_pca=True, filename='./result/pic/dim_128_origin_{}.png'.format(i)) # influence = torch.FloatTensor(influence).cuda() # features = torch.mm(influence, features) features = sgc_precompute(features, adj, args.degree) if args.vis == "vis": from plotFunc import draw_representations for i in range(1, 5): draw_representations(features, labels, k=4, seed=77, do_pca=True, filename='./result/pic/dim_128_sgc_{}.png'.format(i)) exit(1) val_acc_best, epoch_best = train_regression(model, features[idx_train], labels[idx_train], features[idx_val], U_dev, classLatMedian, classLonMedian, userLocation, args.epochs, args.weight_decay, args.lr, args.patience, model_file) if args.model == "HGNN": val_acc_best, epoch_best = train_regression2(model, features[idx_train], labels[idx_train], features[idx_val], U_dev, classLatMedian, classLonMedian, userLocation, args.epochs, args.weight_decay, args.lr, args.patience, model_file, cluster_nodes, cluster_adj, node2cluster_arr) # load model from file and test the model # my_model = get_model(args.model, features.shape[1], labels.max().item() + 1, usecuda=args.usecuda) # my_model.load_state_dict(torch.load(model_file)) my_model = torch.load(model_file) csv_file_test = "./result/dim_{}_{}_{}_{}_test.csv".format( features.shape[1], args.feature_norm, args.weight_decay, args.lr) csv_file_train = "./result/dim_{}_{}_{}_{}_train.csv".format( features.shape[1], args.feature_norm, args.weight_decay, args.lr) if args.model == "HGNN": meanDis, MedianDis, accAT161, distances, latlon_true, latlon_pred = geo_eval2(my_model, features[idx_test], U_test, classLatMedian, classLonMedian, userLocation, node2cluster_arr[idx_test]) # save_coordinate_true_predict(distances, latlon_true, latlon_pred, labels[idx_test], classLatMedian, classLonMedian, # csv_file_test) _, _, train_acc_at_161, distances, latlon_true, latlon_pred = geo_eval2(my_model, features[idx_train], U_train, classLatMedian, classLonMedian, userLocation, node2cluster_arr[idx_train]) else: meanDis, MedianDis, accAT161, distances, latlon_true, latlon_pred = geo_eval(my_model, features[idx_test], U_test, classLatMedian, classLonMedian, userLocation) # save_coordinate_true_predict(distances, latlon_true, latlon_pred, labels[idx_test], classLatMedian, classLonMedian, # csv_file_test) _, _, train_acc_at_161, distances, latlon_true, latlon_pred = geo_eval(my_model, features[idx_train], U_train, classLatMedian, classLonMedian, userLocation) print("train_acc_at_161:{}\t\tTest:\tMean:{}\t\tMedian:{}\t\tAcc@161:{}\n" .format(train_acc_at_161, meanDis, MedianDis, accAT161)) # save_coordinate_true_predict(distances, latlon_true, latlon_pred, labels[idx_train], classLatMedian, classLonMedian, # csv_file_train) # write time, args and results down to file, format is important. timeStr = time.strftime("%Y-%m-%d %H:%M:%S\t", time.localtime(time.time())) argsStr = "-dump_file:{}\t-degree:{}\t-lr:{}\t-decay:{}".format( args.dump_file, args.degree, args.lr, args.weight_decay) resultStr = "Dev:\tepoch_best:{}\t\tval_acc_best:{}\n".format(epoch_best, val_acc_best) + \ "train_acc_at_161:{}\t\tTest:\tMean:{}\t\tMedian:{}\t\tAcc@161:{}".format( train_acc_at_161, meanDis, MedianDis, accAT161) content = "\n" + timeStr + "\n" + argsStr + "\n" + resultStr + "\n" with open('result/influ_doc128_sgc.txt', 'a') as f: f.write(content) f.close() def save_coordinate_true_predict(distances, latlon_true, latlon_pred, labels, classLatMedian, classLonMedian, coordinate_file): """ :return: record the true and false users. """ true_array, pred_array, dis_array = np.array(latlon_true), np.array(latlon_pred), np.array(distances) dis_array = dis_array.reshape(len(dis_array), 1) labels = labels.data.cpu().numpy().tolist() lab_list = list() for l in labels: lat_lab, lon_lab = classLatMedian[str(l)], classLonMedian[str(l)] lab_list.append([lat_lab, lon_lab, l]) lab_array = np.array(lab_list) combine = np.hstack((true_array, pred_array, lab_array, dis_array)) out_str = "id,true_lat,true_lon,pred_lat,pred_lon,pred_class,lab_lat,lab_lon,lab_class,distance,class_acc,acc@161\n" with open(coordinate_file, 'w') as f: for i, coor in enumerate(combine): if coor[4] == coor[7]: sign = "Yes" else: sign = "No" if coor[8] <= 161: sign2 = "In." else: sign2 = "Out" out_str += str(i) + ',' + str(coor[0]) + ',' + str(coor[1]) + ',' + str(coor[2]) + ',' + str(coor[3]) \ + ',' + str(coor[4]) + ',' + str(coor[5]) + ',' + str(coor[6]) + ',' + str(coor[7]) \ + ',' + str(coor[8]) + ',' + sign + ',' + sign2 + "\n" if (i % 1000 == 0) or (i == len(combine) - 1): f.write(out_str) out_str = "" f.close() if __name__ == '__main__': # update learning rate and restart args = parse_args(sys.argv[1:]) degree_rate = [2] weight_decay_rate = [5e-7] lr_rate = [0.0001, 0.0001, 0.001] for degree in degree_rate: args.degree = degree for weight_decay in weight_decay_rate: args.weight_decay = weight_decay for lr in lr_rate: args.lr = lr print("degree:{}\t\tweight_decay:{}\t\tlr:{}".format(args.degree, args.weight_decay, args.lr)) main()
[ "numpy.argmax", "numpy.median", "torch.load", "torch.nn.functional.cross_entropy", "haversine.haversine", "dataProcess.process_data", "numpy.hstack", "torch.save", "time.time", "dataProcess.preprocess_data", "numpy.array", "numpy.mean", "utils.sgc_precompute", "utils.parse_args", "torch.no_grad" ]
[((3813, 3838), 'numpy.argmax', 'np.argmax', (['y_pred'], {'axis': '(1)'}), '(y_pred, axis=1)\n', (3822, 3838), True, 'import numpy as np\n'), ((4932, 4957), 'numpy.argmax', 'np.argmax', (['y_pred'], {'axis': '(1)'}), '(y_pred, axis=1)\n', (4941, 4957), True, 'import numpy as np\n'), ((6099, 6120), 'dataProcess.preprocess_data', 'preprocess_data', (['args'], {}), '(args)\n', (6114, 6120), False, 'from dataProcess import preprocess_data, process_data\n'), ((6132, 6156), 'dataProcess.process_data', 'process_data', (['data', 'args'], {}), '(data, args)\n', (6144, 6156), False, 'from dataProcess import preprocess_data, process_data\n'), ((8556, 8578), 'torch.load', 'torch.load', (['model_file'], {}), '(model_file)\n', (8566, 8578), False, 'import torch\n'), ((12457, 12475), 'numpy.array', 'np.array', (['lab_list'], {}), '(lab_list)\n', (12465, 12475), True, 'import numpy as np\n'), ((12490, 12547), 'numpy.hstack', 'np.hstack', (['(true_array, pred_array, lab_array, dis_array)'], {}), '((true_array, pred_array, lab_array, dis_array))\n', (12499, 12547), True, 'import numpy as np\n'), ((13490, 13514), 'utils.parse_args', 'parse_args', (['sys.argv[1:]'], {}), '(sys.argv[1:])\n', (13500, 13514), False, 'from utils import sgc_precompute, parse_args\n'), ((848, 885), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['output', 'train_labels'], {}), '(output, train_labels)\n', (863, 885), True, 'import torch.nn.functional as F\n'), ((2500, 2537), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['output', 'train_labels'], {}), '(output, train_labels)\n', (2515, 2537), True, 'import torch.nn.functional as F\n'), ((3690, 3705), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3703, 3705), False, 'import torch\n'), ((4409, 4452), 'haversine.haversine', 'haversine', (['(lat, lon)', '(lat_pred, lon_pred)'], {}), '((lat, lon), (lat_pred, lon_pred))\n', (4418, 4452), False, 'from haversine import haversine\n'), ((4586, 4604), 'numpy.mean', 'np.mean', (['distances'], {}), '(distances)\n', (4593, 4604), True, 'import numpy as np\n'), ((4606, 4626), 'numpy.median', 'np.median', (['distances'], {}), '(distances)\n', (4615, 4626), True, 'import numpy as np\n'), ((4791, 4806), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4804, 4806), False, 'import torch\n'), ((5528, 5571), 'haversine.haversine', 'haversine', (['(lat, lon)', '(lat_pred, lon_pred)'], {}), '((lat, lon), (lat_pred, lon_pred))\n', (5537, 5571), False, 'from haversine import haversine\n'), ((5705, 5723), 'numpy.mean', 'np.mean', (['distances'], {}), '(distances)\n', (5712, 5723), True, 'import numpy as np\n'), ((5725, 5745), 'numpy.median', 'np.median', (['distances'], {}), '(distances)\n', (5734, 5745), True, 'import numpy as np\n'), ((7160, 7202), 'utils.sgc_precompute', 'sgc_precompute', (['features', 'adj', 'args.degree'], {}), '(features, adj, args.degree)\n', (7174, 7202), False, 'from utils import sgc_precompute, parse_args\n'), ((12110, 12131), 'numpy.array', 'np.array', (['latlon_true'], {}), '(latlon_true)\n', (12118, 12131), True, 'import numpy as np\n'), ((12133, 12154), 'numpy.array', 'np.array', (['latlon_pred'], {}), '(latlon_pred)\n', (12141, 12154), True, 'import numpy as np\n'), ((12156, 12175), 'numpy.array', 'np.array', (['distances'], {}), '(distances)\n', (12164, 12175), True, 'import numpy as np\n'), ((3319, 3348), 'torch.save', 'torch.save', (['model', 'model_file'], {}), '(model, model_file)\n', (3329, 3348), False, 'import torch\n'), ((11275, 11286), 'time.time', 'time.time', ([], {}), '()\n', (11284, 11286), False, 'import time\n')]
import numpy as np import sys sys.path.append("../") # sys.path.append("../loaders/") from derive_dataset import get_max_r2, get_max_r2_alt from loaders import pvc1 if __name__ == "__main__": """Only for pvc1. See generate_hyperflow for the method for HyperFlow.""" maxr2s = [] for single_cell in range(23): loader = pvc1.PVC1( "/mnt/e/data_derived/crcns-ringach-data/", nt=1, ntau=10, nframedelay=0, repeats=True, single_cell=single_cell, split="report", ) Ys = [] for _, _, Y, _ in loader: Ys.append(Y) Y = np.concatenate(Ys, axis=0) Y = Y.reshape((1, Y.shape[0], Y.shape[1])).transpose((0, 2, 1)) maxr2 = get_max_r2(Y) maxr2_alt = get_max_r2_alt(Y) print(single_cell, maxr2, maxr2_alt) maxr2s.append(maxr2_alt) print(maxr2s)
[ "sys.path.append", "derive_dataset.get_max_r2", "derive_dataset.get_max_r2_alt", "loaders.pvc1.PVC1", "numpy.concatenate" ]
[((31, 53), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (46, 53), False, 'import sys\n'), ((340, 481), 'loaders.pvc1.PVC1', 'pvc1.PVC1', (['"""/mnt/e/data_derived/crcns-ringach-data/"""'], {'nt': '(1)', 'ntau': '(10)', 'nframedelay': '(0)', 'repeats': '(True)', 'single_cell': 'single_cell', 'split': '"""report"""'}), "('/mnt/e/data_derived/crcns-ringach-data/', nt=1, ntau=10,\n nframedelay=0, repeats=True, single_cell=single_cell, split='report')\n", (349, 481), False, 'from loaders import pvc1\n'), ((661, 687), 'numpy.concatenate', 'np.concatenate', (['Ys'], {'axis': '(0)'}), '(Ys, axis=0)\n', (675, 687), True, 'import numpy as np\n'), ((777, 790), 'derive_dataset.get_max_r2', 'get_max_r2', (['Y'], {}), '(Y)\n', (787, 790), False, 'from derive_dataset import get_max_r2, get_max_r2_alt\n'), ((811, 828), 'derive_dataset.get_max_r2_alt', 'get_max_r2_alt', (['Y'], {}), '(Y)\n', (825, 828), False, 'from derive_dataset import get_max_r2, get_max_r2_alt\n')]
from keras.preprocessing.image import img_to_array import imutils import cv2 from keras.models import load_model import numpy as np import pyttsx3 import pyaudio import matplotlib.pyplot as plt from keras.preprocessing import image from statistics import mode def get_labels(dataset_name): if dataset_name == 'imdb': return {0: 'woman', 1: 'man'} else: raise Exception('Invalid dataset name') def preprocess_input(x, v2=True): x = x.astype('float32') x = x / 255.0 if v2: x = x - 0.5 x = x * 2.0 return x def load_detection_model(model_path): detection_model = cv2.CascadeClassifier(model_path) return detection_model def detect_faces(detection_model, gray_image_array): return detection_model.detectMultiScale(gray_image_array, 1.3, 5) def draw_bounding_box(face_coordinates, image_array, color): x, y, w, h = face_coordinates cv2.rectangle(image_array, (x, y), (x + w, y + h), color, 2) def apply_offsets(face_coordinates, offsets): x, y, width, height = face_coordinates x_off, y_off = offsets return (x - x_off, x + width + x_off, y - y_off, y + height + y_off) def draw_text(coordinates, image_array, text, color, x_offset=0, y_offset=0, font_scale=2, thickness=2): x, y = coordinates[:2] cv2.putText(image_array, text, (x + x_offset, y + y_offset), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness, cv2.LINE_AA) # parameters for loading data and images detection_model_path = 'haarcascade/haarcascade_frontalface_default.xml' gender_model_path = 'pretrained_models/final_cnn.hdf5' gender_labels = get_labels('imdb') font = cv2.FONT_HERSHEY_SIMPLEX # hyper-parameters for bounding boxes shape frame_window = 20 gender_offsets = (40, 80) # loading models face_detection = load_detection_model(detection_model_path) gender_classifier = load_model(gender_model_path, compile=False) gender_classifier.summary() # getting input model shapes for inference gender_target_size = gender_classifier.input_shape[1:3] # starting lists for calculating modes gender_window = [] # starting video streaming cv2.namedWindow('window_frame') video_capture = cv2.VideoCapture(0) while True: bgr_image = video_capture.read()[1] gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY) rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB) faces = detect_faces(face_detection, gray_image) for face_coordinates in faces: x1, x2, y1, y2 = apply_offsets(face_coordinates, gender_offsets) rgb_face = rgb_image[y1:y2, x1:x2] gray_face = gray_image[y1:y2, x1:x2] try: rgb_face = cv2.resize(rgb_face, (gender_target_size)) except: continue gray_face = preprocess_input(gray_face, False) gray_face = np.expand_dims(gray_face, 0) gray_face = np.expand_dims(gray_face, -1) rgb_face = np.expand_dims(rgb_face, 0) rgb_face = preprocess_input(rgb_face, False) gender_prediction = gender_classifier.predict(rgb_face) gender_label_arg = np.argmax(gender_prediction) gender_text = gender_labels[gender_label_arg] gender_window.append(gender_text) if len(gender_window) > frame_window: gender_window.pop(0) try: gender_mode = mode(gender_window) except: continue if gender_text == gender_labels[0]: color = (255, 0, 0) else: color = (0, 0, 255) draw_bounding_box(face_coordinates, rgb_image, color) draw_text(face_coordinates, rgb_image, gender_mode, color, 0, -20, 1, 1) bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR) cv2.imshow('window_frame', bgr_image) if cv2.waitKey(1) & 0xFF == ord('q'): break
[ "keras.models.load_model", "cv2.resize", "cv2.putText", "numpy.argmax", "cv2.cvtColor", "cv2.waitKey", "numpy.expand_dims", "cv2.VideoCapture", "cv2.rectangle", "statistics.mode", "cv2.CascadeClassifier", "cv2.imshow", "cv2.namedWindow" ]
[((1935, 1979), 'keras.models.load_model', 'load_model', (['gender_model_path'], {'compile': '(False)'}), '(gender_model_path, compile=False)\n', (1945, 1979), False, 'from keras.models import load_model\n'), ((2195, 2226), 'cv2.namedWindow', 'cv2.namedWindow', (['"""window_frame"""'], {}), "('window_frame')\n", (2210, 2226), False, 'import cv2\n'), ((2243, 2262), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2259, 2262), False, 'import cv2\n'), ((626, 659), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['model_path'], {}), '(model_path)\n', (647, 659), False, 'import cv2\n'), ((911, 971), 'cv2.rectangle', 'cv2.rectangle', (['image_array', '(x, y)', '(x + w, y + h)', 'color', '(2)'], {}), '(image_array, (x, y), (x + w, y + h), color, 2)\n', (924, 971), False, 'import cv2\n'), ((1347, 1481), 'cv2.putText', 'cv2.putText', (['image_array', 'text', '(x + x_offset, y + y_offset)', 'cv2.FONT_HERSHEY_SIMPLEX', 'font_scale', 'color', 'thickness', 'cv2.LINE_AA'], {}), '(image_array, text, (x + x_offset, y + y_offset), cv2.\n FONT_HERSHEY_SIMPLEX, font_scale, color, thickness, cv2.LINE_AA)\n', (1358, 1481), False, 'import cv2\n'), ((2333, 2376), 'cv2.cvtColor', 'cv2.cvtColor', (['bgr_image', 'cv2.COLOR_BGR2GRAY'], {}), '(bgr_image, cv2.COLOR_BGR2GRAY)\n', (2345, 2376), False, 'import cv2\n'), ((2393, 2435), 'cv2.cvtColor', 'cv2.cvtColor', (['bgr_image', 'cv2.COLOR_BGR2RGB'], {}), '(bgr_image, cv2.COLOR_BGR2RGB)\n', (2405, 2435), False, 'import cv2\n'), ((3756, 3798), 'cv2.cvtColor', 'cv2.cvtColor', (['rgb_image', 'cv2.COLOR_RGB2BGR'], {}), '(rgb_image, cv2.COLOR_RGB2BGR)\n', (3768, 3798), False, 'import cv2\n'), ((3803, 3840), 'cv2.imshow', 'cv2.imshow', (['"""window_frame"""', 'bgr_image'], {}), "('window_frame', bgr_image)\n", (3813, 3840), False, 'import cv2\n'), ((2879, 2907), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(0)'], {}), '(gray_face, 0)\n', (2893, 2907), True, 'import numpy as np\n'), ((2928, 2957), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(-1)'], {}), '(gray_face, -1)\n', (2942, 2957), True, 'import numpy as np\n'), ((2979, 3006), 'numpy.expand_dims', 'np.expand_dims', (['rgb_face', '(0)'], {}), '(rgb_face, 0)\n', (2993, 3006), True, 'import numpy as np\n'), ((3151, 3179), 'numpy.argmax', 'np.argmax', (['gender_prediction'], {}), '(gender_prediction)\n', (3160, 3179), True, 'import numpy as np\n'), ((2724, 2764), 'cv2.resize', 'cv2.resize', (['rgb_face', 'gender_target_size'], {}), '(rgb_face, gender_target_size)\n', (2734, 2764), False, 'import cv2\n'), ((3395, 3414), 'statistics.mode', 'mode', (['gender_window'], {}), '(gender_window)\n', (3399, 3414), False, 'from statistics import mode\n'), ((3848, 3862), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3859, 3862), False, 'import cv2\n')]
# This is a visualization script for the CSSP results on real datasets. # The visualization is available for the following subsampling functions: ## * Projection DPPs ## * Volume sampling ## * Pivoted QR ## * Double Phase ## * Largest leverage scores import sys sys.path.insert(0, '..') from CSSPy.dataset_tools import * from CSSPy.visualization_tools import * import numpy as np import pandas as pd from matplotlib import pyplot as plt # Importing the dataset dataset_name = "leukemia" exp_number = 50 k = 10 # Load the results from a txt file savefile_name = "results/test_2/boxplots/"+dataset_name+"_boosting_allalgos_"+str(exp_number)+"samples_k_"+str(k)+".txt" boosting_error_fro_aggregated_list_load = np.loadtxt(savefile_name) boosting_error_fro_aggregated_list_load_to_list = [] for i in list(range(5)): boosting_error_fro_aggregated_list_load_to_list.append(boosting_error_fro_aggregated_list_load[i]) # Plot the comparison of boosting of the algorithms plt.figure(figsize=(10, 8)) plt.xticks(fontsize=22) plt.yticks(fontsize=16) ax = plt.subplot(111) box_2 = plt.boxplot(boosting_error_fro_aggregated_list_load_to_list, showfliers=False) plt.setp(box_2['medians'], color='red', linewidth=3) plt.ylabel(r'$\mathrm{\|\| X- \pi_{S}^{Fr} X \|\| _{Fr}}$', fontsize=18) plt.xticks(rotation=45) plt.gca().xaxis.set_ticklabels(["Volume S.","Projection DPP","Largest lvs","Pivoted QR","Double Phase"]) # Save the figure on a pdf file figfile_name= "results/test_2/"+dataset_name+"_boosting_allalgos_"+str(exp_number)+"samples_k_"+str(k)+".pdf" plt.savefig(figfile_name) plt.show() ### The boosting of the algorithms # Load the results from a txt file savefile_name = "results/test_2/boxplots/"+dataset_name+"_allalgos_"+str(exp_number)+"samples_k_"+str(k)+".txt" error_fro_aggregated_list_load = np.loadtxt(savefile_name) error_fro_aggregated_list_load_to_list = [] for i in list(range(5)): error_fro_aggregated_list_load_to_list.append(error_fro_aggregated_list_load[i]) # Plot the comparison of boosting of the algorithms plt.figure(figsize=(10, 8)) plt.xticks(fontsize=22) plt.yticks(fontsize=16) ax = plt.subplot(111) box_2 = plt.boxplot(error_fro_aggregated_list_load_to_list, showfliers=False) plt.setp(box_2['medians'], color='red', linewidth=3) plt.ylabel(r'$\mathrm{\|\| X- \pi_{S}^{Fr} X \|\| _{Fr}}$', fontsize=18) plt.xticks(rotation=45) plt.gca().xaxis.set_ticklabels(["Volume S.","Projection DPP","Largest lvs","Pivoted QR","Double Phase"]) # Save the figure on a pdf file figfile_name= "results/test_2/"+dataset_name+"_allalgos_"+str(exp_number)+"samples_k_"+str(k)+".pdf" plt.savefig(figfile_name) plt.show()
[ "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.boxplot", "matplotlib.pyplot.yticks", "matplotlib.pyplot.setp", "sys.path.insert", "matplotlib.pyplot.figure", "numpy.loadtxt", "matplotlib.pyplot.gca", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.savefig" ]
[((263, 287), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (278, 287), False, 'import sys\n'), ((713, 738), 'numpy.loadtxt', 'np.loadtxt', (['savefile_name'], {}), '(savefile_name)\n', (723, 738), True, 'import numpy as np\n'), ((976, 1003), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (986, 1003), True, 'from matplotlib import pyplot as plt\n'), ((1005, 1028), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(22)'}), '(fontsize=22)\n', (1015, 1028), True, 'from matplotlib import pyplot as plt\n'), ((1029, 1052), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(16)'}), '(fontsize=16)\n', (1039, 1052), True, 'from matplotlib import pyplot as plt\n'), ((1058, 1074), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (1069, 1074), True, 'from matplotlib import pyplot as plt\n'), ((1084, 1162), 'matplotlib.pyplot.boxplot', 'plt.boxplot', (['boosting_error_fro_aggregated_list_load_to_list'], {'showfliers': '(False)'}), '(boosting_error_fro_aggregated_list_load_to_list, showfliers=False)\n', (1095, 1162), True, 'from matplotlib import pyplot as plt\n'), ((1163, 1215), 'matplotlib.pyplot.setp', 'plt.setp', (["box_2['medians']"], {'color': '"""red"""', 'linewidth': '(3)'}), "(box_2['medians'], color='red', linewidth=3)\n", (1171, 1215), True, 'from matplotlib import pyplot as plt\n'), ((1216, 1293), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\mathrm{\\\\|\\\\| X- \\\\pi_{S}^{Fr} X \\\\|\\\\| _{Fr}}$"""'], {'fontsize': '(18)'}), "('$\\\\mathrm{\\\\|\\\\| X- \\\\pi_{S}^{Fr} X \\\\|\\\\| _{Fr}}$', fontsize=18)\n", (1226, 1293), True, 'from matplotlib import pyplot as plt\n'), ((1289, 1312), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(45)'}), '(rotation=45)\n', (1299, 1312), True, 'from matplotlib import pyplot as plt\n'), ((1562, 1587), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figfile_name'], {}), '(figfile_name)\n', (1573, 1587), True, 'from matplotlib import pyplot as plt\n'), ((1588, 1598), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1596, 1598), True, 'from matplotlib import pyplot as plt\n'), ((1816, 1841), 'numpy.loadtxt', 'np.loadtxt', (['savefile_name'], {}), '(savefile_name)\n', (1826, 1841), True, 'import numpy as np\n'), ((2051, 2078), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (2061, 2078), True, 'from matplotlib import pyplot as plt\n'), ((2080, 2103), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(22)'}), '(fontsize=22)\n', (2090, 2103), True, 'from matplotlib import pyplot as plt\n'), ((2104, 2127), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(16)'}), '(fontsize=16)\n', (2114, 2127), True, 'from matplotlib import pyplot as plt\n'), ((2133, 2149), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (2144, 2149), True, 'from matplotlib import pyplot as plt\n'), ((2159, 2228), 'matplotlib.pyplot.boxplot', 'plt.boxplot', (['error_fro_aggregated_list_load_to_list'], {'showfliers': '(False)'}), '(error_fro_aggregated_list_load_to_list, showfliers=False)\n', (2170, 2228), True, 'from matplotlib import pyplot as plt\n'), ((2229, 2281), 'matplotlib.pyplot.setp', 'plt.setp', (["box_2['medians']"], {'color': '"""red"""', 'linewidth': '(3)'}), "(box_2['medians'], color='red', linewidth=3)\n", (2237, 2281), True, 'from matplotlib import pyplot as plt\n'), ((2282, 2359), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\mathrm{\\\\|\\\\| X- \\\\pi_{S}^{Fr} X \\\\|\\\\| _{Fr}}$"""'], {'fontsize': '(18)'}), "('$\\\\mathrm{\\\\|\\\\| X- \\\\pi_{S}^{Fr} X \\\\|\\\\| _{Fr}}$', fontsize=18)\n", (2292, 2359), True, 'from matplotlib import pyplot as plt\n'), ((2355, 2378), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(45)'}), '(rotation=45)\n', (2365, 2378), True, 'from matplotlib import pyplot as plt\n'), ((2619, 2644), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figfile_name'], {}), '(figfile_name)\n', (2630, 2644), True, 'from matplotlib import pyplot as plt\n'), ((2646, 2656), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2654, 2656), True, 'from matplotlib import pyplot as plt\n'), ((1313, 1322), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1320, 1322), True, 'from matplotlib import pyplot as plt\n'), ((2379, 2388), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2386, 2388), True, 'from matplotlib import pyplot as plt\n')]
from glob import glob from itertools import chain, product from matplotlib import mlab from matplotlib.animation import ArtistAnimation from scipy.ndimage.morphology import (binary_fill_holes, distance_transform_edt) from scipy.stats import norm from skimage import util from skimage.color import gray2rgb from skimage.draw import ellipse_perimeter, ellipse from skimage.exposure import equalize_hist from skimage.filters import threshold_multiotsu from skimage import io, morphology from skimage.measure import label from skimage.morphology import remove_small_objects from skimage.restoration import denoise_tv_chambolle from skimage.segmentation import clear_border, mark_boundaries from string import ascii_lowercase import csv import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import os import pandas as pd import warnings # Setting up the figures appearance. plt.rcParams['font.family'] = 'monospace' plt.rcParams['font.size'] = 30 plt.rcParams['axes.labelsize'] = plt.rcParams['font.size'] plt.rcParams['axes.titlesize'] = 1.2*plt.rcParams['font.size'] plt.rcParams['legend.fontsize'] = plt.rcParams['font.size'] plt.rcParams['xtick.labelsize'] = plt.rcParams['font.size'] plt.rcParams['ytick.labelsize'] = plt.rcParams['font.size'] # Defining some helping variables. OFFSET = -15 # defining some very used variables FONT_SIZE = 22 LINE_WIDTH = 4 SAVING_EXT = 'png' SCATTER_SIZE = 25 # The files we are going to use. FNAME_TIRAMISU = '../coefficients/larson2019_tiramisu-67/output.train_tiramisu-67.py' FNAME_UNET = '../coefficients/larson2019_unet/output.train_unet.py' FNAME_UNET_3D = '../coefficients/larson2019_unet_3d/output.train_unet_3d.py' # Determining colors for each network. COLOR_TIRAMISU = '#3e4989' COLOR_UNET = '#6ece58' COLOR_TIRAMISU_3D = '' COLOR_UNET_3D = '' def figure_2(): """ Figure 2. Exemplifying the methodology using Figure 1 as the input image. (a) Histogram equalization and TV Chambolle's filtering (parameter: weight=0.3). (b) Multi Otsu's resulting regions (parameter: classes=4). Fibers are located within the fourth region (in yellow). (c) Binary image obtained considering region four in (b) as the region of interest, and the remaining regions as the background. (d) the processed region from (c), as shown in Figure 1. Colormaps: (a, c, d) gray, (b) viridis. """ filename = 'support_figures/rec_SFRR_2600_B0p2_01000.tiff' image = io.imread(filename, plugin=None) image = util.img_as_float(image) # Figure 2(a). image_eq = equalize_hist(image) image_filt = denoise_tv_chambolle(image_eq, weight=0.6) plt.figure(figsize=(15, 10)) plt.imshow(image_filt, cmap='gray') plt.savefig('figures/Fig02a.' + SAVING_EXT, bbox_inches='tight') # Figure 2(b). thresholds = threshold_multiotsu(image_filt, classes=4) regions = np.digitize(image_filt, bins=thresholds) plt.figure(figsize=(15, 10)) plt.imshow(regions, cmap='viridis') plt.savefig('figures/Fig02b.' + SAVING_EXT, bbox_inches='tight') # Figure 2(c). img_fibers = remove_small_objects(regions == 3) plt.figure(figsize=(15, 10)) plt.imshow(img_fibers, cmap='gray') plt.savefig('figures/Fig02c.' + SAVING_EXT, bbox_inches='tight') # Figure 2(d). cut_fibers = _aux_cut_roi(img_fibers) plt.figure(figsize=(15, 10)) plt.imshow(cut_fibers, cmap='gray') plt.savefig('figures/Fig02d.' + SAVING_EXT, bbox_inches='tight') # Figure 2(e). label_fibers, _, _ = segmentation_wusem(cut_fibers, initial_radius=0, delta_radius=2, watershed_line=True) permutate = np.concatenate((np.zeros(1, dtype='int'), np.random.permutation(10 ** 4)), axis=None) label_random = permutate[label_fibers] label_mark = mark_boundaries( plt.cm.nipy_spectral(label_random/label_random.max())[..., :3], label_img=label_random, color=(0, 0, 0)) plt.figure(figsize=(15, 10)) plt.imshow(label_mark, cmap='gist_stern') plt.savefig('figures/Fig02e.' + SAVING_EXT, bbox_inches='tight') return None def figure_X(): """ Figure 1. (...). """ # getting accuracy, loss for tiramisu. epochs_tiramisu = _aux_split_epochs(filename=FNAME_TIRAMISU) time_tiramisu, accuracy_tiramisu, loss_tiramisu = _aux_plot_measures(epochs_tiramisu) # getting accuracy, loss for unet. epochs_unet = _aux_split_epochs(filename=FNAME_UNET) time_unet, accuracy_unet, loss_unet = _aux_plot_measures(epochs_unet) # Fig 1 (a). fig, ax = plt.subplots(nrows=2) ax[0].plot(time_tiramisu, accuracy_tiramisu, c=COLOR_TIRAMISU, linewidth=3) ax[0].plot(time_unet, accuracy_unet, c=COLOR_UNET, linewidth=3) ax[0].set_xlabel('Time (s)') ax[0].set_ylabel('Accuracy') ax[0].legend(['Tiramisu', 'U-net'], shadow=True) # Fig 1 (b). ax[1].plot(time_tiramisu, loss_tiramisu, c=COLOR_TIRAMISU, linewidth=3) ax[1].plot(time_unet, loss_unet, c=COLOR_UNET, linewidth=3) ax[1].set_xlabel('Time (s)') ax[1].set_ylabel('Loss') ax[1].legend(['Tiramisu', 'U-net'], shadow=True) return None def _aux_plot_measures(epochs): all_time, all_accuracy, all_loss = [], [], [] last_time = 0 for epoch in epochs: accuracy, loss = _aux_epoch_indicators(epoch) all_accuracy.append(accuracy) all_loss.append(loss) total_time = float(epoch[-1][1].split('s')[0]) time = np.linspace(start=last_time, stop=total_time, num=len(accuracy)) all_time.append(time) last_time = total_time return np.ravel(all_time), np.ravel(all_accuracy), np.ravel(all_loss) """ # now, let's get how much each epoch took. all_time_tiramisu, all_time_unet = [], [] epochs = _aux_split_epochs(filename=FNAME_TIRAMISU) for epoch in epochs: all_time_tiramisu.append(float(epoch[-1][1].split('s')[0])) epochs = _aux_split_epochs(filename=FNAME_UNET) for epoch in epochs: all_time_unet.append(float(epoch[-1][1].split('s')[0])) all_time_tiramisu = np.asarray(all_time_tiramisu) all_time_unet = np.asarray(all_time_unet) print(all_time_tiramisu.mean(), all_time_tiramisu.std()) print(all_time_unet.mean(), all_time_unet.std()) return None """ def _aux_cut_roi(image, crop_roi=False): """ """ rows, cols = image.shape rows_c = rows // 2 - 50 cols_c = cols // 2 - 10 radius_a = 900 radius_b = 935 rr, cc = ellipse(rows_c, cols_c, radius_a, radius_b, rotation=np.pi/4) mask = image < 0 mask[rr, cc] = True image *= mask if crop_roi: image = image[rows_c-radius_a:rows_c+radius_a, cols_c-radius_b:cols_c+radius_b] return image def _aux_epoch_indicators(epoch): """ """ all_accuracy, all_loss = [], [] for row in epoch: aux = ' '.join(row) if 'accuracy:' in aux: # / remove '\x08' / separate num / remove space acc = row[-1].replace('\x08', '').split(':')[-1].strip() all_accuracy.append(float(acc)) # / separate num / remove space loss = row[-2].split(':')[-1].strip() all_loss.append(float(loss)) return np.asarray(all_accuracy), np.asarray(all_loss) def _aux_split_epochs(filename): """ """ content, idx_epochs, epochs = [], [], [] with open(filename) as file: for row in csv.reader(file, delimiter='-'): content.append(row) for idx, row in enumerate(content): aux = ' '.join(row) if 'Epoch' in aux and len(aux) < 20: idx_epochs.append(idx) for idx, _ in enumerate(idx_epochs[:-1]): epochs.append(content[idx_epochs[idx]:idx_epochs[idx+1]]) return epochs def segmentation_wusem(image, str_el='disk', initial_radius=10, delta_radius=5, watershed_line=False): """Separates regions on a binary input image using successive erosions as markers for the watershed algorithm. The algorithm stops when the erosion image does not have objects anymore. Parameters ---------- image : (N, M) ndarray Binary input image. str_el : string, optional Structuring element used to erode the input image. Accepts the strings 'diamond', 'disk' and 'square'. Default is 'disk'. initial_radius : int, optional Initial radius of the structuring element to be used in the erosion. Default is 10. delta_radius : int, optional Delta radius used in the iterations: * Iteration #1: radius = initial_radius + delta_radius * Iteration #2: radius = initial_radius + 2 * delta_radius, and so on. Default is 5. Returns ------- img_labels : (N, M) ndarray Labeled image presenting the regions segmented from the input image. num_objects : int Number of objects in the input image. last_radius : int Radius size of the last structuring element used on the erosion. References ---------- .. [1] <NAME> et al. "Tomographic analysis of jammed ellipsoid packings", in: AIP Conference Proceedings, 2013, 1542: 377-380. DOI: 10.1063/1.4811946. Examples -------- >>> from skimage.data import binary_blobs >>> image = binary_blobs(length=512, seed=0) >>> img_labels, num_objects, _ = segmentation_wusem(image, str_el='disk', initial_radius=10, delta_radius=3) """ rows, cols = image.shape img_labels = np.zeros((rows, cols)) curr_radius = initial_radius distance = distance_transform_edt(image) while True: aux_se = { 'diamond': morphology.diamond(curr_radius), 'disk': morphology.disk(curr_radius), 'square': morphology.square(curr_radius) } str_el = aux_se.get('disk', morphology.disk(curr_radius)) erod_aux = morphology.binary_erosion(image, selem=str_el) if erod_aux.min() == erod_aux.max(): last_step = curr_radius break markers = label(erod_aux) if watershed_line: curr_labels = morphology.watershed(-distance, markers, mask=image, watershed_line=True) img_labels += curr_labels else: curr_labels = morphology.watershed(-distance, markers, mask=image) img_labels += curr_labels # preparing for another loop. curr_radius += delta_radius # reordering labels. img_labels = label(img_labels) # removing small labels. img_labels, num_objects = label(remove_small_objects(img_labels), return_num=True) return img_labels, num_objects, last_step
[ "csv.reader", "numpy.ravel", "matplotlib.pyplot.figure", "skimage.measure.label", "skimage.morphology.diamond", "matplotlib.pyplot.imshow", "skimage.morphology.binary_erosion", "matplotlib.pyplot.subplots", "skimage.draw.ellipse", "skimage.io.imread", "skimage.exposure.equalize_hist", "numpy.asarray", "skimage.restoration.denoise_tv_chambolle", "skimage.morphology.watershed", "skimage.morphology.square", "numpy.random.permutation", "numpy.digitize", "scipy.ndimage.morphology.distance_transform_edt", "skimage.filters.threshold_multiotsu", "numpy.zeros", "skimage.morphology.disk", "skimage.morphology.remove_small_objects", "skimage.util.img_as_float", "matplotlib.pyplot.savefig" ]
[((2509, 2541), 'skimage.io.imread', 'io.imread', (['filename'], {'plugin': 'None'}), '(filename, plugin=None)\n', (2518, 2541), False, 'from skimage import io, morphology\n'), ((2554, 2578), 'skimage.util.img_as_float', 'util.img_as_float', (['image'], {}), '(image)\n', (2571, 2578), False, 'from skimage import util\n'), ((2614, 2634), 'skimage.exposure.equalize_hist', 'equalize_hist', (['image'], {}), '(image)\n', (2627, 2634), False, 'from skimage.exposure import equalize_hist\n'), ((2652, 2694), 'skimage.restoration.denoise_tv_chambolle', 'denoise_tv_chambolle', (['image_eq'], {'weight': '(0.6)'}), '(image_eq, weight=0.6)\n', (2672, 2694), False, 'from skimage.restoration import denoise_tv_chambolle\n'), ((2700, 2728), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (2710, 2728), True, 'import matplotlib.pyplot as plt\n'), ((2733, 2768), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_filt'], {'cmap': '"""gray"""'}), "(image_filt, cmap='gray')\n", (2743, 2768), True, 'import matplotlib.pyplot as plt\n'), ((2773, 2837), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/Fig02a.' + SAVING_EXT)"], {'bbox_inches': '"""tight"""'}), "('figures/Fig02a.' + SAVING_EXT, bbox_inches='tight')\n", (2784, 2837), True, 'import matplotlib.pyplot as plt\n'), ((2875, 2917), 'skimage.filters.threshold_multiotsu', 'threshold_multiotsu', (['image_filt'], {'classes': '(4)'}), '(image_filt, classes=4)\n', (2894, 2917), False, 'from skimage.filters import threshold_multiotsu\n'), ((2932, 2972), 'numpy.digitize', 'np.digitize', (['image_filt'], {'bins': 'thresholds'}), '(image_filt, bins=thresholds)\n', (2943, 2972), True, 'import numpy as np\n'), ((2978, 3006), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (2988, 3006), True, 'import matplotlib.pyplot as plt\n'), ((3011, 3046), 'matplotlib.pyplot.imshow', 'plt.imshow', (['regions'], {'cmap': '"""viridis"""'}), "(regions, cmap='viridis')\n", (3021, 3046), True, 'import matplotlib.pyplot as plt\n'), ((3051, 3115), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/Fig02b.' + SAVING_EXT)"], {'bbox_inches': '"""tight"""'}), "('figures/Fig02b.' + SAVING_EXT, bbox_inches='tight')\n", (3062, 3115), True, 'import matplotlib.pyplot as plt\n'), ((3153, 3187), 'skimage.morphology.remove_small_objects', 'remove_small_objects', (['(regions == 3)'], {}), '(regions == 3)\n', (3173, 3187), False, 'from skimage.morphology import remove_small_objects\n'), ((3193, 3221), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (3203, 3221), True, 'import matplotlib.pyplot as plt\n'), ((3226, 3261), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_fibers'], {'cmap': '"""gray"""'}), "(img_fibers, cmap='gray')\n", (3236, 3261), True, 'import matplotlib.pyplot as plt\n'), ((3266, 3330), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/Fig02c.' + SAVING_EXT)"], {'bbox_inches': '"""tight"""'}), "('figures/Fig02c.' + SAVING_EXT, bbox_inches='tight')\n", (3277, 3330), True, 'import matplotlib.pyplot as plt\n'), ((3398, 3426), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (3408, 3426), True, 'import matplotlib.pyplot as plt\n'), ((3431, 3466), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cut_fibers'], {'cmap': '"""gray"""'}), "(cut_fibers, cmap='gray')\n", (3441, 3466), True, 'import matplotlib.pyplot as plt\n'), ((3471, 3535), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/Fig02d.' + SAVING_EXT)"], {'bbox_inches': '"""tight"""'}), "('figures/Fig02d.' + SAVING_EXT, bbox_inches='tight')\n", (3482, 3535), True, 'import matplotlib.pyplot as plt\n'), ((4176, 4204), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (4186, 4204), True, 'import matplotlib.pyplot as plt\n'), ((4209, 4250), 'matplotlib.pyplot.imshow', 'plt.imshow', (['label_mark'], {'cmap': '"""gist_stern"""'}), "(label_mark, cmap='gist_stern')\n", (4219, 4250), True, 'import matplotlib.pyplot as plt\n'), ((4255, 4319), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/Fig02e.' + SAVING_EXT)"], {'bbox_inches': '"""tight"""'}), "('figures/Fig02e.' + SAVING_EXT, bbox_inches='tight')\n", (4266, 4319), True, 'import matplotlib.pyplot as plt\n'), ((4795, 4816), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)'}), '(nrows=2)\n', (4807, 4816), True, 'import matplotlib.pyplot as plt\n'), ((6784, 6847), 'skimage.draw.ellipse', 'ellipse', (['rows_c', 'cols_c', 'radius_a', 'radius_b'], {'rotation': '(np.pi / 4)'}), '(rows_c, cols_c, radius_a, radius_b, rotation=np.pi / 4)\n', (6791, 6847), False, 'from skimage.draw import ellipse_perimeter, ellipse\n'), ((10028, 10050), 'numpy.zeros', 'np.zeros', (['(rows, cols)'], {}), '((rows, cols))\n', (10036, 10050), True, 'import numpy as np\n'), ((10099, 10128), 'scipy.ndimage.morphology.distance_transform_edt', 'distance_transform_edt', (['image'], {}), '(image)\n', (10121, 10128), False, 'from scipy.ndimage.morphology import binary_fill_holes, distance_transform_edt\n'), ((11251, 11268), 'skimage.measure.label', 'label', (['img_labels'], {}), '(img_labels)\n', (11256, 11268), False, 'from skimage.measure import label\n'), ((5890, 5908), 'numpy.ravel', 'np.ravel', (['all_time'], {}), '(all_time)\n', (5898, 5908), True, 'import numpy as np\n'), ((5910, 5932), 'numpy.ravel', 'np.ravel', (['all_accuracy'], {}), '(all_accuracy)\n', (5918, 5932), True, 'import numpy as np\n'), ((5934, 5952), 'numpy.ravel', 'np.ravel', (['all_loss'], {}), '(all_loss)\n', (5942, 5952), True, 'import numpy as np\n'), ((7572, 7596), 'numpy.asarray', 'np.asarray', (['all_accuracy'], {}), '(all_accuracy)\n', (7582, 7596), True, 'import numpy as np\n'), ((7598, 7618), 'numpy.asarray', 'np.asarray', (['all_loss'], {}), '(all_loss)\n', (7608, 7618), True, 'import numpy as np\n'), ((7768, 7799), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '"""-"""'}), "(file, delimiter='-')\n", (7778, 7799), False, 'import csv\n'), ((10420, 10466), 'skimage.morphology.binary_erosion', 'morphology.binary_erosion', (['image'], {'selem': 'str_el'}), '(image, selem=str_el)\n', (10445, 10466), False, 'from skimage import io, morphology\n'), ((10585, 10600), 'skimage.measure.label', 'label', (['erod_aux'], {}), '(erod_aux)\n', (10590, 10600), False, 'from skimage.measure import label\n'), ((11335, 11367), 'skimage.morphology.remove_small_objects', 'remove_small_objects', (['img_labels'], {}), '(img_labels)\n', (11355, 11367), False, 'from skimage.morphology import remove_small_objects\n'), ((3832, 3856), 'numpy.zeros', 'np.zeros', (['(1)'], {'dtype': '"""int"""'}), "(1, dtype='int')\n", (3840, 3856), True, 'import numpy as np\n'), ((3890, 3920), 'numpy.random.permutation', 'np.random.permutation', (['(10 ** 4)'], {}), '(10 ** 4)\n', (3911, 3920), True, 'import numpy as np\n'), ((10188, 10219), 'skimage.morphology.diamond', 'morphology.diamond', (['curr_radius'], {}), '(curr_radius)\n', (10206, 10219), False, 'from skimage import io, morphology\n'), ((10241, 10269), 'skimage.morphology.disk', 'morphology.disk', (['curr_radius'], {}), '(curr_radius)\n', (10256, 10269), False, 'from skimage import io, morphology\n'), ((10293, 10323), 'skimage.morphology.square', 'morphology.square', (['curr_radius'], {}), '(curr_radius)\n', (10310, 10323), False, 'from skimage import io, morphology\n'), ((10370, 10398), 'skimage.morphology.disk', 'morphology.disk', (['curr_radius'], {}), '(curr_radius)\n', (10385, 10398), False, 'from skimage import io, morphology\n'), ((10655, 10728), 'skimage.morphology.watershed', 'morphology.watershed', (['(-distance)', 'markers'], {'mask': 'image', 'watershed_line': '(True)'}), '(-distance, markers, mask=image, watershed_line=True)\n', (10675, 10728), False, 'from skimage import io, morphology\n'), ((10948, 11000), 'skimage.morphology.watershed', 'morphology.watershed', (['(-distance)', 'markers'], {'mask': 'image'}), '(-distance, markers, mask=image)\n', (10968, 11000), False, 'from skimage import io, morphology\n')]
import numpy as np class Vector: def __init__(self, x = 0, y = 0): self.x = x self.y = y def magnitude(self): return np.sqrt(self.x * self.x + self.y * self.y) def __repr__(self): return "Vektor({0}.x, {0}.y)".format(self)
[ "numpy.sqrt" ]
[((152, 194), 'numpy.sqrt', 'np.sqrt', (['(self.x * self.x + self.y * self.y)'], {}), '(self.x * self.x + self.y * self.y)\n', (159, 194), True, 'import numpy as np\n')]
import numpy as np import bandits_lab.algorithms as algs import bandits_lab.bandit_definitions as bands import sim_utilities as sim np.random.seed(10) T = 20000 n_tests = 75 """ Definition of the problems considered - the probability set considered is a triangle, - we build a family of bandit problems, defined by their mean vectors. For the last two mean vectors, the optimal (mixed) action in on the border of the simplex, whereas for the fist two, the optimal action is in the interior of the simplex. We know that the regret has to grow at least logarithmically in the latter case. We conjecture that diversity-preserving UCB yields bounded regret when the optimal action is on the border. """ K = 3 low = 0.1 lows = [0] + [low for _ in range(K - 1)] constraints_list = [ (lows[i], 1, np.array([1 * (j == i) for j in range(K)])) for i in range(K) ] setP = bands.PolytopeConstraints(K, constraints_list) delta = np.array([0.05, 0, -0.05]) mus = np.array([1 / 2, 1 / 3, 1 / 2]) mus_list = [ mus - 2 * delta, mus - delta, mus, mus + delta, mus + 2 * delta, ] min_reward, max_reward = setP.argmax_dot(-mus), setP.argmax_dot(mus) print(max_reward) delta_max = max_reward.fun - (-min_reward.fun) # print("Un point qui vérifie les contraintes : ", C.feasible) print("Maximum gap for this problem : ", delta_max) band_list = [bands.DivPBand(K, mus, setP) for mus in mus_list] """ Definition of the algorithms. We are only interested in (diversity-preserving) UCB here. We also run follow-the-leader for control. """ eps = 1 alg_list = [ # DivPUCB(K, C, label='DivP kl-UCB'), algs.DivPUCB(K, setP, sig=1, label="DivP UCB"), # L1OFUL(K, C, label="L1OFUL", delta=1/T), # DivPEpsGreedy( # K, setP, label=r"$\epsilon$-greedy, $\epsilon =$" + str(eps), epsilon=eps # ), # algs.DivPEpsGreedy(K, setP, label="Follow-the-leader", epsilon=0), ] N_tests = [n_tests for _ in band_list] data_dict = { "name": "Transition from logarithmic to bounded regret gaussian noise", "short_name": "log_or_bounded_regret", "T": T, "N_tests": N_tests, "band_list": band_list, "alg_list": alg_list, "results": None, "folder": "data_saves/diversity/", } # "data_saves/diversity/log_or_bounded_regret" sim.launch(data_dict, checkpoints=True, n_jobs=4) skips = [] sim.plot_and_save( data_dict, save_figure=False, skip_algs=skips, log_scale=True, show_vars=True, ) print("done")
[ "bandits_lab.bandit_definitions.PolytopeConstraints", "numpy.random.seed", "sim_utilities.launch", "sim_utilities.plot_and_save", "bandits_lab.algorithms.DivPUCB", "numpy.array", "bandits_lab.bandit_definitions.DivPBand" ]
[((134, 152), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (148, 152), True, 'import numpy as np\n'), ((940, 986), 'bandits_lab.bandit_definitions.PolytopeConstraints', 'bands.PolytopeConstraints', (['K', 'constraints_list'], {}), '(K, constraints_list)\n', (965, 986), True, 'import bandits_lab.bandit_definitions as bands\n'), ((996, 1022), 'numpy.array', 'np.array', (['[0.05, 0, -0.05]'], {}), '([0.05, 0, -0.05])\n', (1004, 1022), True, 'import numpy as np\n'), ((1029, 1060), 'numpy.array', 'np.array', (['[1 / 2, 1 / 3, 1 / 2]'], {}), '([1 / 2, 1 / 3, 1 / 2])\n', (1037, 1060), True, 'import numpy as np\n'), ((2353, 2402), 'sim_utilities.launch', 'sim.launch', (['data_dict'], {'checkpoints': '(True)', 'n_jobs': '(4)'}), '(data_dict, checkpoints=True, n_jobs=4)\n', (2363, 2402), True, 'import sim_utilities as sim\n'), ((2415, 2516), 'sim_utilities.plot_and_save', 'sim.plot_and_save', (['data_dict'], {'save_figure': '(False)', 'skip_algs': 'skips', 'log_scale': '(True)', 'show_vars': '(True)'}), '(data_dict, save_figure=False, skip_algs=skips, log_scale=\n True, show_vars=True)\n', (2432, 2516), True, 'import sim_utilities as sim\n'), ((1425, 1453), 'bandits_lab.bandit_definitions.DivPBand', 'bands.DivPBand', (['K', 'mus', 'setP'], {}), '(K, mus, setP)\n', (1439, 1453), True, 'import bandits_lab.bandit_definitions as bands\n'), ((1695, 1741), 'bandits_lab.algorithms.DivPUCB', 'algs.DivPUCB', (['K', 'setP'], {'sig': '(1)', 'label': '"""DivP UCB"""'}), "(K, setP, sig=1, label='DivP UCB')\n", (1707, 1741), True, 'import bandits_lab.algorithms as algs\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt from scipy import ndimage from PIL import Image import scipy import numpy as np import cv2 import os nomeImagem="muitas_crateras.jpg" def medianBlur(img): img_blur=cv2.medianBlur(img,7); return img_blur def averageBlur(img): kernel = np.ones((5,5),np.float32)/25 img_blur=cv2.filter2D(img,-1,kernel); return img_blur def highBoostBlur(img, img_blur, c): print(type(img)) mag = cv2.Laplacian(img, cv2.CV_16S, ksize=int(c*2)) mag = cv2.convertScaleAbs(mag) print(type(mag)) return mag#np.subtract(img, img_blur) def noFiltro(img): pixels=np.array(img.getdata()) ii,jj=img.size pixels=pixels.reshape(jj,ii) dx=ndimage.sobel(img,0) #Ox dy=ndimage.sobel(img,1) #Oy mag=np.hypot(dx,dy)#magnetude #mag*=255.0/np.max(mag) #normalização np.place(dx,dx==0,1) divided=np.divide(dy,dx) direc=np.arctan(divided)*180/np.pi for i in range(len(direc)): for j in range(len(direc[i])): if(direc[i][j]<=30): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i][j-1]+mag[i][j+1]): pixels[i][j]=mag[i][j] else: pixels[i][j]=0 elif(direc[i][j]>30 and direc[i][j]<=60): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j+1]+mag[i-1][j-1]): pixels[i][j]=mag[i][j] else: pixels[i][j]=0 elif(direc[i][j]>60 and direc[i][j]<=90): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j]+mag[i-1][j]): pixels[i][j]=mag[i][j] else: pixels[i][j]=0 elif(direc[i][j]>90 and direc[i][j]<=120): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j-1]+mag[i-1][j+1]): pixels[i][j]=mag[i][j] else: pixels[i][j]=0 pixels=pixels.astype(np.uint8) result=Image.fromarray(pixels) result.save('results/semFiltro.png') def media(img): pixels=np.array(img.getdata()) ii,jj=img.size pixels=pixels.astype(np.uint8) pixels=averageBlur(pixels) pixels=pixels.reshape(jj,ii) result=Image.fromarray(pixels) dx=ndimage.sobel(img,0) #Ox dy=ndimage.sobel(img,1) #Oy mag=np.hypot(dx,dy)#magnetude #mag*=255.0/np.max(mag) #normalização np.place(dx,dx==0,1) divided=np.divide(dy,dx) direc=np.arctan(divided)*180/np.pi pixels2=np.zeros((jj,ii)) for i in range(len(direc)): for j in range(len(direc[i])): if(direc[i][j]<=30): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i][j-1]+mag[i][j+1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>30 and direc[i][j]<=60): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j+1]+mag[i-1][j-1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>60 and direc[i][j]<=90): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j]+mag[i-1][j]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>90 and direc[i][j]<=120): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j-1]+mag[i-1][j+1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 pixels2=pixels2.astype(np.uint8) result=Image.fromarray(pixels2) result.save('results/media.png') def mediana(img): pixels=np.array(img.getdata()) ii,jj=img.size pixels=pixels.astype(np.uint8) pixels=medianBlur(pixels) pixels=pixels.reshape(jj,ii) result=Image.fromarray(pixels) dx=ndimage.sobel(img,0) #Ox dy=ndimage.sobel(img,1) #Oy mag=np.hypot(dx,dy)#magnetude #mag*=255.0/np.max(mag) #normalização np.place(dx,dx==0,1) divided=np.divide(dy,dx) direc=np.arctan(divided)*180/np.pi pixels2=np.zeros((jj,ii)) for i in range(len(direc)): for j in range(len(direc[i])): if(direc[i][j]<=30): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i][j-1]+mag[i][j+1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>30 and direc[i][j]<=60): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j+1]+mag[i-1][j-1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>60 and direc[i][j]<=90): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j]+mag[i-1][j]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>90 and direc[i][j]<=120): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j-1]+mag[i-1][j+1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 pixels2=pixels2.astype(np.uint8) result=Image.fromarray(pixels2) result.save('results/mediana.png') def passaAlta(img): pixels=np.array(img.getdata()) ii,jj=img.size pixels=pixels.astype(np.uint8) mpixels=medianBlur(pixels) mpixels=mpixels.astype(np.uint8) pixels=highBoostBlur(pixels,mpixels,1.5) pixels=pixels.reshape(jj,ii) result=Image.fromarray(pixels) result.save('results/passaaltaBlur1.5.png') dx=ndimage.sobel(img,0) #Ox dy=ndimage.sobel(img,1) #Oy mag=np.hypot(dx,dy)#magnetude mag*=255.0/np.max(mag) #normalização np.place(dx,dx==0,1) divided=np.divide(dy,dx) direc=np.arctan(divided)*180/np.pi pixels2=np.zeros((jj,ii)) for i in range(len(direc)): for j in range(len(direc[i])): if(direc[i][j]<=30): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i][j-1]+mag[i][j+1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>30 and direc[i][j]<=60): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j+1]+mag[i-1][j-1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>60 and direc[i][j]<=90): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j]+mag[i-1][j]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 elif(direc[i][j]>90 and direc[i][j]<=120): if(j-1>=0 and i-1>=0 and i+1<jj and j+1 <ii and mag[i][j]>mag[i+1][j-1]+mag[i-1][j+1]): pixels2[i][j]=pixels[i][j] else: pixels2[i][j]=0 pixels2=pixels2.astype(np.uint8) result=Image.fromarray(pixels2) result.save('results/passaAlta1.5.png') if __name__=="__main__": img=Image.open(nomeImagem).convert(mode="L") '''print "Imagem sem filtro" noFiltro(img) print "Media" media(img) print "Mediana" mediana(img) print "High pass"''' passaAlta(img)
[ "numpy.divide", "cv2.filter2D", "cv2.medianBlur", "numpy.zeros", "numpy.ones", "scipy.ndimage.sobel", "numpy.place", "numpy.hypot", "PIL.Image.open", "numpy.max", "cv2.convertScaleAbs", "PIL.Image.fromarray", "numpy.arctan" ]
[((248, 270), 'cv2.medianBlur', 'cv2.medianBlur', (['img', '(7)'], {}), '(img, 7)\n', (262, 270), False, 'import cv2\n'), ((369, 398), 'cv2.filter2D', 'cv2.filter2D', (['img', '(-1)', 'kernel'], {}), '(img, -1, kernel)\n', (381, 398), False, 'import cv2\n'), ((544, 568), 'cv2.convertScaleAbs', 'cv2.convertScaleAbs', (['mag'], {}), '(mag)\n', (563, 568), False, 'import cv2\n'), ((746, 767), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(0)'], {}), '(img, 0)\n', (759, 767), False, 'from scipy import ndimage\n'), ((778, 799), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(1)'], {}), '(img, 1)\n', (791, 799), False, 'from scipy import ndimage\n'), ((811, 827), 'numpy.hypot', 'np.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (819, 827), True, 'import numpy as np\n'), ((883, 907), 'numpy.place', 'np.place', (['dx', '(dx == 0)', '(1)'], {}), '(dx, dx == 0, 1)\n', (891, 907), True, 'import numpy as np\n'), ((916, 933), 'numpy.divide', 'np.divide', (['dy', 'dx'], {}), '(dy, dx)\n', (925, 933), True, 'import numpy as np\n'), ((2094, 2117), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels'], {}), '(pixels)\n', (2109, 2117), False, 'from PIL import Image\n'), ((2340, 2363), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels'], {}), '(pixels)\n', (2355, 2363), False, 'from PIL import Image\n'), ((2371, 2392), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(0)'], {}), '(img, 0)\n', (2384, 2392), False, 'from scipy import ndimage\n'), ((2403, 2424), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(1)'], {}), '(img, 1)\n', (2416, 2424), False, 'from scipy import ndimage\n'), ((2436, 2452), 'numpy.hypot', 'np.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (2444, 2452), True, 'import numpy as np\n'), ((2508, 2532), 'numpy.place', 'np.place', (['dx', '(dx == 0)', '(1)'], {}), '(dx, dx == 0, 1)\n', (2516, 2532), True, 'import numpy as np\n'), ((2541, 2558), 'numpy.divide', 'np.divide', (['dy', 'dx'], {}), '(dy, dx)\n', (2550, 2558), True, 'import numpy as np\n'), ((2609, 2627), 'numpy.zeros', 'np.zeros', (['(jj, ii)'], {}), '((jj, ii))\n', (2617, 2627), True, 'import numpy as np\n'), ((3771, 3795), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels2'], {}), '(pixels2)\n', (3786, 3795), False, 'from PIL import Image\n'), ((4015, 4038), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels'], {}), '(pixels)\n', (4030, 4038), False, 'from PIL import Image\n'), ((4046, 4067), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(0)'], {}), '(img, 0)\n', (4059, 4067), False, 'from scipy import ndimage\n'), ((4078, 4099), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(1)'], {}), '(img, 1)\n', (4091, 4099), False, 'from scipy import ndimage\n'), ((4111, 4127), 'numpy.hypot', 'np.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (4119, 4127), True, 'import numpy as np\n'), ((4183, 4207), 'numpy.place', 'np.place', (['dx', '(dx == 0)', '(1)'], {}), '(dx, dx == 0, 1)\n', (4191, 4207), True, 'import numpy as np\n'), ((4216, 4233), 'numpy.divide', 'np.divide', (['dy', 'dx'], {}), '(dy, dx)\n', (4225, 4233), True, 'import numpy as np\n'), ((4284, 4302), 'numpy.zeros', 'np.zeros', (['(jj, ii)'], {}), '((jj, ii))\n', (4292, 4302), True, 'import numpy as np\n'), ((5446, 5470), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels2'], {}), '(pixels2)\n', (5461, 5470), False, 'from PIL import Image\n'), ((5777, 5800), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels'], {}), '(pixels)\n', (5792, 5800), False, 'from PIL import Image\n'), ((5856, 5877), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(0)'], {}), '(img, 0)\n', (5869, 5877), False, 'from scipy import ndimage\n'), ((5888, 5909), 'scipy.ndimage.sobel', 'ndimage.sobel', (['img', '(1)'], {}), '(img, 1)\n', (5901, 5909), False, 'from scipy import ndimage\n'), ((5921, 5937), 'numpy.hypot', 'np.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (5929, 5937), True, 'import numpy as np\n'), ((5992, 6016), 'numpy.place', 'np.place', (['dx', '(dx == 0)', '(1)'], {}), '(dx, dx == 0, 1)\n', (6000, 6016), True, 'import numpy as np\n'), ((6025, 6042), 'numpy.divide', 'np.divide', (['dy', 'dx'], {}), '(dy, dx)\n', (6034, 6042), True, 'import numpy as np\n'), ((6093, 6111), 'numpy.zeros', 'np.zeros', (['(jj, ii)'], {}), '((jj, ii))\n', (6101, 6111), True, 'import numpy as np\n'), ((7265, 7289), 'PIL.Image.fromarray', 'Image.fromarray', (['pixels2'], {}), '(pixels2)\n', (7280, 7289), False, 'from PIL import Image\n'), ((327, 354), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.float32'], {}), '((5, 5), np.float32)\n', (334, 354), True, 'import numpy as np\n'), ((5962, 5973), 'numpy.max', 'np.max', (['mag'], {}), '(mag)\n', (5968, 5973), True, 'import numpy as np\n'), ((943, 961), 'numpy.arctan', 'np.arctan', (['divided'], {}), '(divided)\n', (952, 961), True, 'import numpy as np\n'), ((2568, 2586), 'numpy.arctan', 'np.arctan', (['divided'], {}), '(divided)\n', (2577, 2586), True, 'import numpy as np\n'), ((4243, 4261), 'numpy.arctan', 'np.arctan', (['divided'], {}), '(divided)\n', (4252, 4261), True, 'import numpy as np\n'), ((6052, 6070), 'numpy.arctan', 'np.arctan', (['divided'], {}), '(divided)\n', (6061, 6070), True, 'import numpy as np\n'), ((7368, 7390), 'PIL.Image.open', 'Image.open', (['nomeImagem'], {}), '(nomeImagem)\n', (7378, 7390), False, 'from PIL import Image\n')]
import os, sys import numpy as np try: import StringIO except ModuleNotFoundError: from io import BytesIO as StringIO import base as wb class NBest(object): def __init__(self, nbest, trans, acscore=None, lmscore=None, gfscore=None): """ construct a nbest class Args: nbest: nbet list trans: the test transcript ( correct text ) acscore: acoustic score lmscore: language model score gfscore: graph score """ self.nbest = nbest self.trans = trans self.acscore = None self.lmscore = None self.gfscore = gfscore if acscore is not None: self.acscore = wb.LoadScore(acscore) if lmscore is not None: self.lmscore = wb.LoadScore(lmscore) if gfscore is not None: self.gfscore = wb.LoadScore(gfscore) # save the best result self.lmscale = 1.0 self.acscale = 1.0 self.total_err = 0 self.total_word = 0 self.best_1best = None self.best_log = None self.wer_per_scale = [] self.nbest_list_id = None def process_best_file(self, best_file): new_best_file = wb.io.StringIO() for line in best_file: new_line = ' '.join(filter(lambda w: w.lower() != '<unk>', line.split())) new_best_file.write(new_line + '\n') best_file.close() new_best_file.seek(0) return new_best_file def wer(self, lmscale=np.linspace(0.1, 1.0, 10), rm_unk=False, sentence_process_fun=None, special_word='<?>'): """ compute the WER Returns: word error rate (WER) """ if self.lmscore is None: self.lmscore = np.zeros_like(self.acscore) if self.acscore is None: self.acscore = np.zeros(len(self.lmscore)) if self.gfscore is None: self.gfscore = np.zeros(len(self.lmscore)) self.wer_per_scale = [] # tune the lmscale opt_wer = 1000 for ac in [1]: for lm in lmscale: s = ac * np.array(self.acscore) + lm * (np.array(self.lmscore) + np.array(self.gfscore)) best_file = StringIO.StringIO() log_file = StringIO.StringIO() wb.GetBest(self.nbest, s, best_file) best_file.seek(0) if rm_unk: best_file = self.process_best_file(best_file) [totale, totalw, wer] = wb.CmpWER(best_file, self.trans, log_str_or_io=log_file, sentence_process_fun=sentence_process_fun, special_word=special_word) self.wer_per_scale.append([ac, lm, wer]) # print('acscale={}\tlmscale={}\twer={}\n'.format(acscale, lmscale, wer)) if wer < opt_wer: opt_wer = wer self.lmscale = lm self.acscale = ac self.total_word = totalw self.total_err = totale if self.best_1best is not None: self.best_1best.close() self.best_1best = best_file self.best_1best.seek(0) if self.best_log is not None: self.best_log.close() self.best_log = log_file self.best_log.seek(0) else: best_file.close() log_file.close() return opt_wer def oracle_wer(self, rm_unk=False, sentence_process_fun=None): import StringIO self.oracle_log_io = StringIO.StringIO() if rm_unk: nbest = self.process_best_file(self.nbest) else: nbest = self.nbest res = wb.CmpOracleWER(nbest, self.trans, self.oracle_log_io, sentence_process_fun) self.oracle_log_io.seek(0) return res def get_trans_txt(self, fwrite): # get the transcript text used to calculate PPL wb.file_rmlabel(self.trans, fwrite) def get_nbest_list(self, data): # return the nbest list id files used to rescoring if self.nbest_list_id is None: self.nbest_list_id = data.load_data(self.nbest, is_nbest=True) # # process the empty sequences # empty_len = int(data.beg_token_str is not None) + int(data.end_token_str is not None) # for s in self.nbest_list_id: # if len(s) == empty_len: # s.insert(-1, data.get_end_token()) return self.nbest_list_id def write_nbest_list(self, fwrite, data): with open(fwrite, 'wt') as f: for s in self.get_nbest_list(data): f.write(' '.join([str(i) for i in s]) + '\n') def write_lmscore(self, fwrite): with open(fwrite, 'wt') as fout, open(self.nbest, 'rt') as fin: for s, line in zip(self.lmscore, fin): fout.write(line.split()[0] + '\t' + str(s) + '\n') def write_log(self, fname): if self.best_log is None: print('[{0}.{1}] best_log=None, run {1}.wer() first.'.format(__name__, self.__class__.__name__)) with open(fname, 'wt') as f: self.best_log.seek(0) f.write(self.best_log.read()) def write_1best(self, fname): if self.best_1best is None: print('[{0}.{1}] best_1best=None, run {1}.wer() first.'.format(__name__, self.__class__.__name__)) with open(fname, 'wt') as f: self.best_1best.seek(0) f.write(self.best_1best.read()) def get_nbest_lens(self): return [len(s.split()) - 1 for s in open(self.nbest).readlines()]
[ "base.io.StringIO", "numpy.zeros_like", "base.LoadScore", "base.GetBest", "base.CmpWER", "numpy.array", "numpy.linspace", "base.file_rmlabel", "base.CmpOracleWER", "StringIO.StringIO" ]
[((1236, 1252), 'base.io.StringIO', 'wb.io.StringIO', ([], {}), '()\n', (1250, 1252), True, 'import base as wb\n'), ((1531, 1556), 'numpy.linspace', 'np.linspace', (['(0.1)', '(1.0)', '(10)'], {}), '(0.1, 1.0, 10)\n', (1542, 1556), True, 'import numpy as np\n'), ((3822, 3841), 'StringIO.StringIO', 'StringIO.StringIO', ([], {}), '()\n', (3839, 3841), False, 'import StringIO\n'), ((3977, 4053), 'base.CmpOracleWER', 'wb.CmpOracleWER', (['nbest', 'self.trans', 'self.oracle_log_io', 'sentence_process_fun'], {}), '(nbest, self.trans, self.oracle_log_io, sentence_process_fun)\n', (3992, 4053), True, 'import base as wb\n'), ((4210, 4245), 'base.file_rmlabel', 'wb.file_rmlabel', (['self.trans', 'fwrite'], {}), '(self.trans, fwrite)\n', (4225, 4245), True, 'import base as wb\n'), ((715, 736), 'base.LoadScore', 'wb.LoadScore', (['acscore'], {}), '(acscore)\n', (727, 736), True, 'import base as wb\n'), ((796, 817), 'base.LoadScore', 'wb.LoadScore', (['lmscore'], {}), '(lmscore)\n', (808, 817), True, 'import base as wb\n'), ((877, 898), 'base.LoadScore', 'wb.LoadScore', (['gfscore'], {}), '(gfscore)\n', (889, 898), True, 'import base as wb\n'), ((1779, 1806), 'numpy.zeros_like', 'np.zeros_like', (['self.acscore'], {}), '(self.acscore)\n', (1792, 1806), True, 'import numpy as np\n'), ((2255, 2274), 'StringIO.StringIO', 'StringIO.StringIO', ([], {}), '()\n', (2272, 2274), False, 'import StringIO\n'), ((2302, 2321), 'StringIO.StringIO', 'StringIO.StringIO', ([], {}), '()\n', (2319, 2321), False, 'import StringIO\n'), ((2338, 2374), 'base.GetBest', 'wb.GetBest', (['self.nbest', 's', 'best_file'], {}), '(self.nbest, s, best_file)\n', (2348, 2374), True, 'import base as wb\n'), ((2544, 2674), 'base.CmpWER', 'wb.CmpWER', (['best_file', 'self.trans'], {'log_str_or_io': 'log_file', 'sentence_process_fun': 'sentence_process_fun', 'special_word': 'special_word'}), '(best_file, self.trans, log_str_or_io=log_file,\n sentence_process_fun=sentence_process_fun, special_word=special_word)\n', (2553, 2674), True, 'import base as wb\n'), ((2147, 2169), 'numpy.array', 'np.array', (['self.acscore'], {}), '(self.acscore)\n', (2155, 2169), True, 'import numpy as np\n'), ((2178, 2200), 'numpy.array', 'np.array', (['self.lmscore'], {}), '(self.lmscore)\n', (2186, 2200), True, 'import numpy as np\n'), ((2203, 2225), 'numpy.array', 'np.array', (['self.gfscore'], {}), '(self.gfscore)\n', (2211, 2225), True, 'import numpy as np\n')]
"""Tests for the policies in the hbaselines/multi_fcnet subdirectory.""" import unittest import numpy as np import tensorflow as tf from gym.spaces import Box from hbaselines.utils.tf_util import get_trainable_vars from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as \ TD3MultiFeedForwardPolicy from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as \ SACMultiFeedForwardPolicy from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS class TestMultiActorCriticPolicy(unittest.TestCase): """Test MultiActorCriticPolicy in hbaselines/multi_fcnet/base.py.""" def setUp(self): self.sess = tf.compat.v1.Session() # Shared policy parameters self.policy_params_shared = { 'sess': self.sess, 'ac_space': Box(low=-1, high=1, shape=(1,)), 'co_space': Box(low=-2, high=2, shape=(2,)), 'ob_space': Box(low=-3, high=3, shape=(3,)), 'all_ob_space': Box(low=-3, high=3, shape=(10,)), 'layers': [256, 256], 'verbose': 0, } self.policy_params_shared.update(TD3_PARAMS.copy()) self.policy_params_shared.update(MULTI_FEEDFORWARD_PARAMS.copy()) self.policy_params_shared['shared'] = True # Independent policy parameters self.policy_params_independent = { 'sess': self.sess, 'ac_space': { 'a': Box(low=-1, high=1, shape=(1,)), 'b': Box(low=-2, high=2, shape=(2,)), }, 'co_space': { 'a': Box(low=-3, high=3, shape=(3,)), 'b': Box(low=-4, high=4, shape=(4,)), }, 'ob_space': { 'a': Box(low=-5, high=5, shape=(5,)), 'b': Box(low=-6, high=6, shape=(6,)), }, 'all_ob_space': Box(low=-6, high=6, shape=(18,)), 'layers': [256, 256], 'verbose': 0, } self.policy_params_independent.update(TD3_PARAMS.copy()) self.policy_params_independent.update(MULTI_FEEDFORWARD_PARAMS.copy()) self.policy_params_independent['shared'] = False def tearDown(self): self.sess.close() del self.policy_params_shared del self.policy_params_independent # Clear the graph. tf.compat.v1.reset_default_graph() def test_store_transition_1(self): """Check the functionality of the store_transition() method. This test checks for the following cases: 1. maddpg = False, shared = False 2. maddpg = False, shared = True """ policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = False policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() for i in range(4): action_0 = np.array([i for _ in range(1)]) action_1 = np.array([i for _ in range(2)]) context0_0 = np.array([i for _ in range(3)]) context0_1 = np.array([i for _ in range(4)]) obs0_0 = np.array([i for _ in range(5)]) obs0_1 = np.array([i for _ in range(6)]) reward = i obs1_0 = np.array([i+1 for _ in range(5)]) obs1_1 = np.array([i+1 for _ in range(6)]) context1_0 = np.array([i for _ in range(3)]) context1_1 = np.array([i for _ in range(4)]) done = False is_final_step = False evaluate = False policy.store_transition( obs0={"a": obs0_0, "b": obs0_1}, context0={"a": context0_0, "b": context0_1}, action={"a": action_0, "b": action_1}, reward={"a": reward, "b": reward}, obs1={"a": obs1_0, "b": obs1_1}, context1={"a": context1_0, "b": context1_1}, done=done, is_final_step=is_final_step, evaluate=evaluate, env_num=0, ) # =================================================================== # # test for agent a # # =================================================================== # obs_t = policy.agents["a"].replay_buffer.obs_t action_t = policy.agents["a"].replay_buffer.action_t reward = policy.agents["a"].replay_buffer.reward done = policy.agents["a"].replay_buffer.done # check the various attributes np.testing.assert_almost_equal( obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3.]]) ) np.testing.assert_almost_equal( action_t[:4, :], np.array([[0.], [1.], [2.], [3.]]) ) np.testing.assert_almost_equal( reward[:4], np.array([0., 1., 2., 3.]) ) np.testing.assert_almost_equal( done[:4], [0., 0., 0., 0.] ) # =================================================================== # # test for agent b # # =================================================================== # obs_t = policy.agents["b"].replay_buffer.obs_t action_t = policy.agents["b"].replay_buffer.action_t reward = policy.agents["b"].replay_buffer.reward done = policy.agents["b"].replay_buffer.done # check the various attributes np.testing.assert_almost_equal( obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]]) ) np.testing.assert_almost_equal( action_t[:4, :], np.array([[0., 0.], [1., 1.], [2., 2.], [3., 3.]]) ) np.testing.assert_almost_equal( reward[:4], np.array([0., 1., 2., 3.]) ) np.testing.assert_almost_equal( done[:4], [0., 0., 0., 0.] ) def test_store_transition_2(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = False policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() for i in range(4): obs0 = np.array([i for _ in range(2)]) context0 = np.array([i for _ in range(3)]) action = np.array([i for _ in range(1)]) reward = i obs1 = np.array([i+1 for _ in range(2)]) context1 = np.array([i for _ in range(3)]) is_final_step = False evaluate = False policy.store_transition( obs0={"a": obs0, "b": obs0 + 1}, context0={"a": context0, "b": context0 + 1}, action={"a": action, "b": action + 1}, reward={"a": reward, "b": reward + 1}, obs1={"a": obs1, "b": obs1 + 1}, context1={"a": context1, "b": context1 + 1}, done=0., is_final_step=is_final_step, evaluate=evaluate, env_num=0, ) # extract the attributes obs_t = policy.agents["policy"].replay_buffer.obs_t action_t = policy.agents["policy"].replay_buffer.action_t reward = policy.agents["policy"].replay_buffer.reward done = policy.agents["policy"].replay_buffer.done # check the various attributes np.testing.assert_almost_equal( obs_t[:8, :], np.array([[0., 0., 0., 0., 0.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.], [2., 2., 2., 2., 2.], [3., 3., 3., 3., 3.], [3., 3., 3., 3., 3.], [4., 4., 4., 4., 4.]]) ) np.testing.assert_almost_equal( action_t[:8, :], np.array([[0.], [1.], [1.], [2.], [2.], [3.], [3.], [4.]]) ) np.testing.assert_almost_equal( reward[:8], np.array([0., 1., 1., 2., 2., 3., 3., 4.]) ) np.testing.assert_almost_equal( done[:8], [0., 0., 0., 0., 0., 0., 0., 0.] ) class TestTD3MultiFeedForwardPolicy(unittest.TestCase): """Test MultiFeedForwardPolicy in hbaselines/multi_fcnet/td3.py.""" def setUp(self): self.sess = tf.compat.v1.Session() # Shared policy parameters self.policy_params_shared = { 'sess': self.sess, 'ac_space': Box(low=-1, high=1, shape=(1,)), 'co_space': Box(low=-2, high=2, shape=(2,)), 'ob_space': Box(low=-3, high=3, shape=(3,)), 'all_ob_space': Box(low=-3, high=3, shape=(10,)), 'layers': [256, 256], 'verbose': 0, } self.policy_params_shared.update(TD3_PARAMS.copy()) self.policy_params_shared.update(MULTI_FEEDFORWARD_PARAMS.copy()) self.policy_params_shared['shared'] = True # Independent policy parameters self.policy_params_independent = { 'sess': self.sess, 'ac_space': { 'a': Box(low=-1, high=1, shape=(1,)), 'b': Box(low=-2, high=2, shape=(2,)), }, 'co_space': { 'a': Box(low=-3, high=3, shape=(3,)), 'b': Box(low=-4, high=4, shape=(4,)), }, 'ob_space': { 'a': Box(low=-5, high=5, shape=(5,)), 'b': Box(low=-6, high=6, shape=(6,)), }, 'all_ob_space': Box(low=-6, high=6, shape=(18,)), 'layers': [256, 256], 'verbose': 0, } self.policy_params_independent.update(TD3_PARAMS.copy()) self.policy_params_independent.update(MULTI_FEEDFORWARD_PARAMS.copy()) self.policy_params_independent['shared'] = False def tearDown(self): self.sess.close() del self.policy_params_shared del self.policy_params_independent # Clear the graph. tf.compat.v1.reset_default_graph() def test_init_1(self): """Check the functionality of the __init__() method. This method is tested for the following features: 1. The proper structure graph was generated. 2. All input placeholders are correct. This is done for the following cases: 1. maddpg = False, shared = False 2. maddpg = False, shared = True 3. maddpg = True, shared = False 4. maddpg = True, shared = True """ policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = False policy = TD3MultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['a/model/pi/fc0/bias:0', 'a/model/pi/fc0/kernel:0', 'a/model/pi/fc1/bias:0', 'a/model/pi/fc1/kernel:0', 'a/model/pi/output/bias:0', 'a/model/pi/output/kernel:0', 'a/model/qf_0/fc0/bias:0', 'a/model/qf_0/fc0/kernel:0', 'a/model/qf_0/fc1/bias:0', 'a/model/qf_0/fc1/kernel:0', 'a/model/qf_0/qf_output/bias:0', 'a/model/qf_0/qf_output/kernel:0', 'a/model/qf_1/fc0/bias:0', 'a/model/qf_1/fc0/kernel:0', 'a/model/qf_1/fc1/bias:0', 'a/model/qf_1/fc1/kernel:0', 'a/model/qf_1/qf_output/bias:0', 'a/model/qf_1/qf_output/kernel:0', 'a/target/pi/fc0/bias:0', 'a/target/pi/fc0/kernel:0', 'a/target/pi/fc1/bias:0', 'a/target/pi/fc1/kernel:0', 'a/target/pi/output/bias:0', 'a/target/pi/output/kernel:0', 'a/target/qf_0/fc0/bias:0', 'a/target/qf_0/fc0/kernel:0', 'a/target/qf_0/fc1/bias:0', 'a/target/qf_0/fc1/kernel:0', 'a/target/qf_0/qf_output/bias:0', 'a/target/qf_0/qf_output/kernel:0', 'a/target/qf_1/fc0/bias:0', 'a/target/qf_1/fc0/kernel:0', 'a/target/qf_1/fc1/bias:0', 'a/target/qf_1/fc1/kernel:0', 'a/target/qf_1/qf_output/bias:0', 'a/target/qf_1/qf_output/kernel:0', 'b/model/pi/fc0/bias:0', 'b/model/pi/fc0/kernel:0', 'b/model/pi/fc1/bias:0', 'b/model/pi/fc1/kernel:0', 'b/model/pi/output/bias:0', 'b/model/pi/output/kernel:0', 'b/model/qf_0/fc0/bias:0', 'b/model/qf_0/fc0/kernel:0', 'b/model/qf_0/fc1/bias:0', 'b/model/qf_0/fc1/kernel:0', 'b/model/qf_0/qf_output/bias:0', 'b/model/qf_0/qf_output/kernel:0', 'b/model/qf_1/fc0/bias:0', 'b/model/qf_1/fc0/kernel:0', 'b/model/qf_1/fc1/bias:0', 'b/model/qf_1/fc1/kernel:0', 'b/model/qf_1/qf_output/bias:0', 'b/model/qf_1/qf_output/kernel:0', 'b/target/pi/fc0/bias:0', 'b/target/pi/fc0/kernel:0', 'b/target/pi/fc1/bias:0', 'b/target/pi/fc1/kernel:0', 'b/target/pi/output/bias:0', 'b/target/pi/output/kernel:0', 'b/target/qf_0/fc0/bias:0', 'b/target/qf_0/fc0/kernel:0', 'b/target/qf_0/fc1/bias:0', 'b/target/qf_0/fc1/kernel:0', 'b/target/qf_0/qf_output/bias:0', 'b/target/qf_0/qf_output/kernel:0', 'b/target/qf_1/fc0/bias:0', 'b/target/qf_1/fc0/kernel:0', 'b/target/qf_1/fc1/bias:0', 'b/target/qf_1/fc1/kernel:0', 'b/target/qf_1/qf_output/bias:0', 'b/target/qf_1/qf_output/kernel:0'] ) # Check observation/action/context spaces of the agents self.assertEqual(policy.agents['a'].ac_space, self.policy_params_independent['ac_space']['a']) self.assertEqual(policy.agents['a'].ob_space, self.policy_params_independent['ob_space']['a']) self.assertEqual(policy.agents['a'].co_space, self.policy_params_independent['co_space']['a']) self.assertEqual(policy.agents['b'].ac_space, self.policy_params_independent['ac_space']['b']) self.assertEqual(policy.agents['b'].ob_space, self.policy_params_independent['ob_space']['b']) self.assertEqual(policy.agents['b'].co_space, self.policy_params_independent['co_space']['b']) # Check the instantiation of the class attributes. self.assertTrue(not policy.shared) self.assertTrue(not policy.maddpg) def test_init_2(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = False policy = TD3MultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['model/pi/fc0/bias:0', 'model/pi/fc0/kernel:0', 'model/pi/fc1/bias:0', 'model/pi/fc1/kernel:0', 'model/pi/output/bias:0', 'model/pi/output/kernel:0', 'model/qf_0/fc0/bias:0', 'model/qf_0/fc0/kernel:0', 'model/qf_0/fc1/bias:0', 'model/qf_0/fc1/kernel:0', 'model/qf_0/qf_output/bias:0', 'model/qf_0/qf_output/kernel:0', 'model/qf_1/fc0/bias:0', 'model/qf_1/fc0/kernel:0', 'model/qf_1/fc1/bias:0', 'model/qf_1/fc1/kernel:0', 'model/qf_1/qf_output/bias:0', 'model/qf_1/qf_output/kernel:0', 'target/pi/fc0/bias:0', 'target/pi/fc0/kernel:0', 'target/pi/fc1/bias:0', 'target/pi/fc1/kernel:0', 'target/pi/output/bias:0', 'target/pi/output/kernel:0', 'target/qf_0/fc0/bias:0', 'target/qf_0/fc0/kernel:0', 'target/qf_0/fc1/bias:0', 'target/qf_0/fc1/kernel:0', 'target/qf_0/qf_output/bias:0', 'target/qf_0/qf_output/kernel:0', 'target/qf_1/fc0/bias:0', 'target/qf_1/fc0/kernel:0', 'target/qf_1/fc1/bias:0', 'target/qf_1/fc1/kernel:0', 'target/qf_1/qf_output/bias:0', 'target/qf_1/qf_output/kernel:0'] ) # Check observation/action/context spaces of the agents self.assertEqual(policy.agents['policy'].ac_space, self.policy_params_shared['ac_space']) self.assertEqual(policy.agents['policy'].ob_space, self.policy_params_shared['ob_space']) self.assertEqual(policy.agents['policy'].co_space, self.policy_params_shared['co_space']) # Check the instantiation of the class attributes. self.assertTrue(policy.shared) self.assertTrue(not policy.maddpg) def test_init_3(self): policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = True policy = TD3MultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['a/model/centralized_qf_0/fc0/bias:0', 'a/model/centralized_qf_0/fc0/kernel:0', 'a/model/centralized_qf_0/fc1/bias:0', 'a/model/centralized_qf_0/fc1/kernel:0', 'a/model/centralized_qf_0/qf_output/bias:0', 'a/model/centralized_qf_0/qf_output/kernel:0', 'a/model/centralized_qf_1/fc0/bias:0', 'a/model/centralized_qf_1/fc0/kernel:0', 'a/model/centralized_qf_1/fc1/bias:0', 'a/model/centralized_qf_1/fc1/kernel:0', 'a/model/centralized_qf_1/qf_output/bias:0', 'a/model/centralized_qf_1/qf_output/kernel:0', 'a/model/pi/fc0/bias:0', 'a/model/pi/fc0/kernel:0', 'a/model/pi/fc1/bias:0', 'a/model/pi/fc1/kernel:0', 'a/model/pi/output/bias:0', 'a/model/pi/output/kernel:0', 'a/target/centralized_qf_0/fc0/bias:0', 'a/target/centralized_qf_0/fc0/kernel:0', 'a/target/centralized_qf_0/fc1/bias:0', 'a/target/centralized_qf_0/fc1/kernel:0', 'a/target/centralized_qf_0/qf_output/bias:0', 'a/target/centralized_qf_0/qf_output/kernel:0', 'a/target/centralized_qf_1/fc0/bias:0', 'a/target/centralized_qf_1/fc0/kernel:0', 'a/target/centralized_qf_1/fc1/bias:0', 'a/target/centralized_qf_1/fc1/kernel:0', 'a/target/centralized_qf_1/qf_output/bias:0', 'a/target/centralized_qf_1/qf_output/kernel:0', 'a/target/pi/fc0/bias:0', 'a/target/pi/fc0/kernel:0', 'a/target/pi/fc1/bias:0', 'a/target/pi/fc1/kernel:0', 'a/target/pi/output/bias:0', 'a/target/pi/output/kernel:0', 'b/model/centralized_qf_0/fc0/bias:0', 'b/model/centralized_qf_0/fc0/kernel:0', 'b/model/centralized_qf_0/fc1/bias:0', 'b/model/centralized_qf_0/fc1/kernel:0', 'b/model/centralized_qf_0/qf_output/bias:0', 'b/model/centralized_qf_0/qf_output/kernel:0', 'b/model/centralized_qf_1/fc0/bias:0', 'b/model/centralized_qf_1/fc0/kernel:0', 'b/model/centralized_qf_1/fc1/bias:0', 'b/model/centralized_qf_1/fc1/kernel:0', 'b/model/centralized_qf_1/qf_output/bias:0', 'b/model/centralized_qf_1/qf_output/kernel:0', 'b/model/pi/fc0/bias:0', 'b/model/pi/fc0/kernel:0', 'b/model/pi/fc1/bias:0', 'b/model/pi/fc1/kernel:0', 'b/model/pi/output/bias:0', 'b/model/pi/output/kernel:0', 'b/target/centralized_qf_0/fc0/bias:0', 'b/target/centralized_qf_0/fc0/kernel:0', 'b/target/centralized_qf_0/fc1/bias:0', 'b/target/centralized_qf_0/fc1/kernel:0', 'b/target/centralized_qf_0/qf_output/bias:0', 'b/target/centralized_qf_0/qf_output/kernel:0', 'b/target/centralized_qf_1/fc0/bias:0', 'b/target/centralized_qf_1/fc0/kernel:0', 'b/target/centralized_qf_1/fc1/bias:0', 'b/target/centralized_qf_1/fc1/kernel:0', 'b/target/centralized_qf_1/qf_output/bias:0', 'b/target/centralized_qf_1/qf_output/kernel:0', 'b/target/pi/fc0/bias:0', 'b/target/pi/fc0/kernel:0', 'b/target/pi/fc1/bias:0', 'b/target/pi/fc1/kernel:0', 'b/target/pi/output/bias:0', 'b/target/pi/output/kernel:0'] ) # Check observation/action/context spaces of the agents for key in policy.ac_space.keys(): self.assertEqual(int(policy.all_obs_ph[key].shape[-1]), policy.all_ob_space.shape[0]) self.assertEqual(int(policy.all_obs1_ph[key].shape[-1]), policy.all_ob_space.shape[0]) self.assertEqual(int(policy.all_action_ph[key].shape[-1]), sum(policy.ac_space[key].shape[0] for key in policy.ac_space.keys())) self.assertEqual(int(policy.action_ph[key].shape[-1]), policy.ac_space[key].shape[0]) self.assertEqual(int(policy.obs_ph[key].shape[-1]), int(policy.ob_space[key].shape[0] + policy.co_space[key].shape[0])) self.assertEqual(int(policy.obs1_ph[key].shape[-1]), int(policy.ob_space[key].shape[0] + policy.co_space[key].shape[0])) # Check the instantiation of the class attributes. self.assertTrue(not policy.shared) self.assertTrue(policy.maddpg) def test_init_4(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = True policy = TD3MultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['model/centralized_qf_0/fc0/bias:0', 'model/centralized_qf_0/fc0/kernel:0', 'model/centralized_qf_0/fc1/bias:0', 'model/centralized_qf_0/fc1/kernel:0', 'model/centralized_qf_0/qf_output/bias:0', 'model/centralized_qf_0/qf_output/kernel:0', 'model/centralized_qf_1/fc0/bias:0', 'model/centralized_qf_1/fc0/kernel:0', 'model/centralized_qf_1/fc1/bias:0', 'model/centralized_qf_1/fc1/kernel:0', 'model/centralized_qf_1/qf_output/bias:0', 'model/centralized_qf_1/qf_output/kernel:0', 'model/pi/fc0/bias:0', 'model/pi/fc0/kernel:0', 'model/pi/fc1/bias:0', 'model/pi/fc1/kernel:0', 'model/pi/output/bias:0', 'model/pi/output/kernel:0', 'target/centralized_qf_0/fc0/bias:0', 'target/centralized_qf_0/fc0/kernel:0', 'target/centralized_qf_0/fc1/bias:0', 'target/centralized_qf_0/fc1/kernel:0', 'target/centralized_qf_0/qf_output/bias:0', 'target/centralized_qf_0/qf_output/kernel:0', 'target/centralized_qf_1/fc0/bias:0', 'target/centralized_qf_1/fc0/kernel:0', 'target/centralized_qf_1/fc1/bias:0', 'target/centralized_qf_1/fc1/kernel:0', 'target/centralized_qf_1/qf_output/bias:0', 'target/centralized_qf_1/qf_output/kernel:0', 'target/pi/fc0/bias:0', 'target/pi/fc0/kernel:0', 'target/pi/fc1/bias:0', 'target/pi/fc1/kernel:0', 'target/pi/output/bias:0', 'target/pi/output/kernel:0'] ) # Check observation/action/context spaces of the agents self.assertEqual(int(policy.all_obs_ph.shape[-1]), policy.all_ob_space.shape[0]) self.assertEqual(int(policy.all_obs1_ph.shape[-1]), policy.all_ob_space.shape[0]) self.assertEqual(int(policy.all_action_ph.shape[-1]), policy.n_agents * policy.ac_space.shape[0]) self.assertEqual(int(policy.action_ph[0].shape[-1]), policy.ac_space.shape[0]) self.assertEqual(int(policy.obs_ph[0].shape[-1]), int(policy.ob_space.shape[0] + policy.co_space.shape[0])) self.assertEqual(int(policy.obs1_ph[0].shape[-1]), int(policy.ob_space.shape[0] + policy.co_space.shape[0])) # Check the instantiation of the class attributes. self.assertTrue(policy.shared) self.assertTrue(policy.maddpg) def test_initialize_1(self): """Check the functionality of the initialize() method. This test validates that the target variables are properly initialized when initialize is called. This is done for the following cases: 1. maddpg = False, shared = False 2. maddpg = False, shared = True 3. maddpg = True, shared = False 4. maddpg = True, shared = True """ policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = False policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'a/model/pi/fc0/bias:0', 'a/model/pi/fc0/kernel:0', 'a/model/pi/fc1/bias:0', 'a/model/pi/fc1/kernel:0', 'a/model/pi/output/bias:0', 'a/model/pi/output/kernel:0', 'a/model/qf_0/fc0/bias:0', 'a/model/qf_0/fc0/kernel:0', 'a/model/qf_0/fc1/bias:0', 'a/model/qf_0/fc1/kernel:0', 'a/model/qf_0/qf_output/bias:0', 'a/model/qf_0/qf_output/kernel:0', 'a/model/qf_1/fc0/bias:0', 'a/model/qf_1/fc0/kernel:0', 'a/model/qf_1/fc1/bias:0', 'a/model/qf_1/fc1/kernel:0', 'a/model/qf_1/qf_output/bias:0', 'a/model/qf_1/qf_output/kernel:0', 'b/model/pi/fc0/bias:0', 'b/model/pi/fc0/kernel:0', 'b/model/pi/fc1/bias:0', 'b/model/pi/fc1/kernel:0', 'b/model/pi/output/bias:0', 'b/model/pi/output/kernel:0', 'b/model/qf_0/fc0/bias:0', 'b/model/qf_0/fc0/kernel:0', 'b/model/qf_0/fc1/bias:0', 'b/model/qf_0/fc1/kernel:0', 'b/model/qf_0/qf_output/bias:0', 'b/model/qf_0/qf_output/kernel:0', 'b/model/qf_1/fc0/bias:0', 'b/model/qf_1/fc0/kernel:0', 'b/model/qf_1/fc1/bias:0', 'b/model/qf_1/fc1/kernel:0', 'b/model/qf_1/qf_output/bias:0', 'b/model/qf_1/qf_output/kernel:0', ] target_var_list = [ 'a/target/pi/fc0/bias:0', 'a/target/pi/fc0/kernel:0', 'a/target/pi/fc1/bias:0', 'a/target/pi/fc1/kernel:0', 'a/target/pi/output/bias:0', 'a/target/pi/output/kernel:0', 'a/target/qf_0/fc0/bias:0', 'a/target/qf_0/fc0/kernel:0', 'a/target/qf_0/fc1/bias:0', 'a/target/qf_0/fc1/kernel:0', 'a/target/qf_0/qf_output/bias:0', 'a/target/qf_0/qf_output/kernel:0', 'a/target/qf_1/fc0/bias:0', 'a/target/qf_1/fc0/kernel:0', 'a/target/qf_1/fc1/bias:0', 'a/target/qf_1/fc1/kernel:0', 'a/target/qf_1/qf_output/bias:0', 'a/target/qf_1/qf_output/kernel:0', 'b/target/pi/fc0/bias:0', 'b/target/pi/fc0/kernel:0', 'b/target/pi/fc1/bias:0', 'b/target/pi/fc1/kernel:0', 'b/target/pi/output/bias:0', 'b/target/pi/output/kernel:0', 'b/target/qf_0/fc0/bias:0', 'b/target/qf_0/fc0/kernel:0', 'b/target/qf_0/fc1/bias:0', 'b/target/qf_0/fc1/kernel:0', 'b/target/qf_0/qf_output/bias:0', 'b/target/qf_0/qf_output/kernel:0', 'b/target/qf_1/fc0/bias:0', 'b/target/qf_1/fc0/kernel:0', 'b/target/qf_1/fc1/bias:0', 'b/target/qf_1/fc1/kernel:0', 'b/target/qf_1/qf_output/bias:0', 'b/target/qf_1/qf_output/kernel:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_initialize_2(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = False policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'model/pi/fc0/bias:0', 'model/pi/fc0/kernel:0', 'model/pi/fc1/bias:0', 'model/pi/fc1/kernel:0', 'model/pi/output/bias:0', 'model/pi/output/kernel:0', 'model/qf_0/fc0/bias:0', 'model/qf_0/fc0/kernel:0', 'model/qf_0/fc1/bias:0', 'model/qf_0/fc1/kernel:0', 'model/qf_0/qf_output/bias:0', 'model/qf_0/qf_output/kernel:0', 'model/qf_1/fc0/bias:0', 'model/qf_1/fc0/kernel:0', 'model/qf_1/fc1/bias:0', 'model/qf_1/fc1/kernel:0', 'model/qf_1/qf_output/bias:0', 'model/qf_1/qf_output/kernel:0', ] target_var_list = [ 'target/pi/fc0/bias:0', 'target/pi/fc0/kernel:0', 'target/pi/fc1/bias:0', 'target/pi/fc1/kernel:0', 'target/pi/output/bias:0', 'target/pi/output/kernel:0', 'target/qf_0/fc0/bias:0', 'target/qf_0/fc0/kernel:0', 'target/qf_0/fc1/bias:0', 'target/qf_0/fc1/kernel:0', 'target/qf_0/qf_output/bias:0', 'target/qf_0/qf_output/kernel:0', 'target/qf_1/fc0/bias:0', 'target/qf_1/fc0/kernel:0', 'target/qf_1/fc1/bias:0', 'target/qf_1/fc1/kernel:0', 'target/qf_1/qf_output/bias:0', 'target/qf_1/qf_output/kernel:0' ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_initialize_3(self): policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = True policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'a/model/centralized_qf_0/fc0/bias:0', 'a/model/centralized_qf_0/fc0/kernel:0', 'a/model/centralized_qf_0/fc1/bias:0', 'a/model/centralized_qf_0/fc1/kernel:0', 'a/model/centralized_qf_0/qf_output/bias:0', 'a/model/centralized_qf_0/qf_output/kernel:0', 'a/model/centralized_qf_1/fc0/bias:0', 'a/model/centralized_qf_1/fc0/kernel:0', 'a/model/centralized_qf_1/fc1/bias:0', 'a/model/centralized_qf_1/fc1/kernel:0', 'a/model/centralized_qf_1/qf_output/bias:0', 'a/model/centralized_qf_1/qf_output/kernel:0', 'a/model/pi/fc0/bias:0', 'a/model/pi/fc0/kernel:0', 'a/model/pi/fc1/bias:0', 'a/model/pi/fc1/kernel:0', 'a/model/pi/output/bias:0', 'a/model/pi/output/kernel:0', 'b/model/centralized_qf_0/fc0/bias:0', 'b/model/centralized_qf_0/fc0/kernel:0', 'b/model/centralized_qf_0/fc1/bias:0', 'b/model/centralized_qf_0/fc1/kernel:0', 'b/model/centralized_qf_0/qf_output/bias:0', 'b/model/centralized_qf_0/qf_output/kernel:0', 'b/model/centralized_qf_1/fc0/bias:0', 'b/model/centralized_qf_1/fc0/kernel:0', 'b/model/centralized_qf_1/fc1/bias:0', 'b/model/centralized_qf_1/fc1/kernel:0', 'b/model/centralized_qf_1/qf_output/bias:0', 'b/model/centralized_qf_1/qf_output/kernel:0', 'b/model/pi/fc0/bias:0', 'b/model/pi/fc0/kernel:0', 'b/model/pi/fc1/bias:0', 'b/model/pi/fc1/kernel:0', 'b/model/pi/output/bias:0', 'b/model/pi/output/kernel:0', ] target_var_list = [ 'a/target/centralized_qf_0/fc0/bias:0', 'a/target/centralized_qf_0/fc0/kernel:0', 'a/target/centralized_qf_0/fc1/bias:0', 'a/target/centralized_qf_0/fc1/kernel:0', 'a/target/centralized_qf_0/qf_output/bias:0', 'a/target/centralized_qf_0/qf_output/kernel:0', 'a/target/centralized_qf_1/fc0/bias:0', 'a/target/centralized_qf_1/fc0/kernel:0', 'a/target/centralized_qf_1/fc1/bias:0', 'a/target/centralized_qf_1/fc1/kernel:0', 'a/target/centralized_qf_1/qf_output/bias:0', 'a/target/centralized_qf_1/qf_output/kernel:0', 'a/target/pi/fc0/bias:0', 'a/target/pi/fc0/kernel:0', 'a/target/pi/fc1/bias:0', 'a/target/pi/fc1/kernel:0', 'a/target/pi/output/bias:0', 'a/target/pi/output/kernel:0', 'b/target/centralized_qf_0/fc0/bias:0', 'b/target/centralized_qf_0/fc0/kernel:0', 'b/target/centralized_qf_0/fc1/bias:0', 'b/target/centralized_qf_0/fc1/kernel:0', 'b/target/centralized_qf_0/qf_output/bias:0', 'b/target/centralized_qf_0/qf_output/kernel:0', 'b/target/centralized_qf_1/fc0/bias:0', 'b/target/centralized_qf_1/fc0/kernel:0', 'b/target/centralized_qf_1/fc1/bias:0', 'b/target/centralized_qf_1/fc1/kernel:0', 'b/target/centralized_qf_1/qf_output/bias:0', 'b/target/centralized_qf_1/qf_output/kernel:0', 'b/target/pi/fc0/bias:0', 'b/target/pi/fc0/kernel:0', 'b/target/pi/fc1/bias:0', 'b/target/pi/fc1/kernel:0', 'b/target/pi/output/bias:0', 'b/target/pi/output/kernel:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_initialize_4(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = True policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'model/centralized_qf_0/fc0/bias:0', 'model/centralized_qf_0/fc0/kernel:0', 'model/centralized_qf_0/fc1/bias:0', 'model/centralized_qf_0/fc1/kernel:0', 'model/centralized_qf_0/qf_output/bias:0', 'model/centralized_qf_0/qf_output/kernel:0', 'model/centralized_qf_1/fc0/bias:0', 'model/centralized_qf_1/fc0/kernel:0', 'model/centralized_qf_1/fc1/bias:0', 'model/centralized_qf_1/fc1/kernel:0', 'model/centralized_qf_1/qf_output/bias:0', 'model/centralized_qf_1/qf_output/kernel:0', 'model/pi/fc0/bias:0', 'model/pi/fc0/kernel:0', 'model/pi/fc1/bias:0', 'model/pi/fc1/kernel:0', 'model/pi/output/bias:0', 'model/pi/output/kernel:0', ] target_var_list = [ 'target/centralized_qf_0/fc0/bias:0', 'target/centralized_qf_0/fc0/kernel:0', 'target/centralized_qf_0/fc1/bias:0', 'target/centralized_qf_0/fc1/kernel:0', 'target/centralized_qf_0/qf_output/bias:0', 'target/centralized_qf_0/qf_output/kernel:0', 'target/centralized_qf_1/fc0/bias:0', 'target/centralized_qf_1/fc0/kernel:0', 'target/centralized_qf_1/fc1/bias:0', 'target/centralized_qf_1/fc1/kernel:0', 'target/centralized_qf_1/qf_output/bias:0', 'target/centralized_qf_1/qf_output/kernel:0', 'target/pi/fc0/bias:0', 'target/pi/fc0/kernel:0', 'target/pi/fc1/bias:0', 'target/pi/fc1/kernel:0', 'target/pi/output/bias:0', 'target/pi/output/kernel:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_store_transition_1(self): """Check the functionality of the store_transition() method. This test checks for the following cases: 1. maddpg = True, shared = False 2. maddpg = True, shared = True """ policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = True policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() for i in range(4): action_0 = np.array([i for _ in range(1)]) action_1 = np.array([i for _ in range(2)]) context0_0 = np.array([i for _ in range(3)]) context0_1 = np.array([i for _ in range(4)]) obs0_0 = np.array([i for _ in range(5)]) obs0_1 = np.array([i for _ in range(6)]) reward = i obs1_0 = np.array([i+1 for _ in range(5)]) obs1_1 = np.array([i+1 for _ in range(6)]) context1_0 = np.array([i for _ in range(3)]) context1_1 = np.array([i for _ in range(4)]) done = False is_final_step = False evaluate = False all_obs0 = np.array([i for _ in range(18)]) all_obs1 = np.array([i+1 for _ in range(18)]) policy.store_transition( obs0={"a": obs0_0, "b": obs0_1}, context0={"a": context0_0, "b": context0_1}, action={"a": action_0, "b": action_1}, reward={"a": reward, "b": reward}, obs1={"a": obs1_0, "b": obs1_1}, context1={"a": context1_0, "b": context1_1}, done=done, is_final_step=is_final_step, evaluate=evaluate, env_num=0, all_obs0=all_obs0, all_obs1=all_obs1, ) # =================================================================== # # test for agent a # # =================================================================== # obs_t = policy.replay_buffer["a"].obs_t action_t = policy.replay_buffer["a"].action_t reward = policy.replay_buffer["a"].reward done = policy.replay_buffer["a"].done all_obs_t = policy.replay_buffer["a"].all_obs_t # check the various attributes np.testing.assert_almost_equal( obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3.]]) ) np.testing.assert_almost_equal( action_t[:4, :], np.array([[0.], [1.], [2.], [3.]]) ) np.testing.assert_almost_equal( reward[:4], np.array([0., 1., 2., 3.]) ) np.testing.assert_almost_equal( done[:4], [0., 0., 0., 0.] ) np.testing.assert_almost_equal( all_obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]]) ) # =================================================================== # # test for agent b # # =================================================================== # obs_t = policy.replay_buffer["b"].obs_t action_t = policy.replay_buffer["b"].action_t reward = policy.replay_buffer["b"].reward done = policy.replay_buffer["b"].done all_obs_t = policy.replay_buffer["b"].all_obs_t # check the various attributes np.testing.assert_almost_equal( obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]]) ) np.testing.assert_almost_equal( action_t[:4, :], np.array([[0., 0.], [1., 1.], [2., 2.], [3., 3.]]) ) np.testing.assert_almost_equal( reward[:4], np.array([0., 1., 2., 3.]) ) np.testing.assert_almost_equal( done[:4], [0., 0., 0., 0.] ) np.testing.assert_almost_equal( all_obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]]) ) def test_store_transition_2(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = True policy_params["n_agents"] = 2 policy = TD3MultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() for i in range(4): obs0 = np.array([i for _ in range(2)]) context0 = np.array([i for _ in range(3)]) action = np.array([i for _ in range(1)]) reward = i obs1 = np.array([i+1 for _ in range(2)]) context1 = np.array([i for _ in range(3)]) is_final_step = False evaluate = False all_obs0 = np.array([i for _ in range(10)]) all_obs1 = np.array([i+1 for _ in range(10)]) policy.store_transition( obs0={"a": obs0, "b": obs0 + 1}, context0={"a": context0, "b": context0 + 1}, action={"a": action, "b": action + 1}, reward={"a": reward, "b": reward + 1}, obs1={"a": obs1, "b": obs1 + 1}, context1={"a": context1, "b": context1 + 1}, done=0., is_final_step=is_final_step, evaluate=evaluate, env_num=0, all_obs0=all_obs0, all_obs1=all_obs1, ) # extract the attributes obs_t = policy.replay_buffer.obs_t action_t = policy.replay_buffer.action reward = policy.replay_buffer.reward done = policy.replay_buffer.done all_obs_t = policy.replay_buffer.all_obs_t # check the various attributes np.testing.assert_almost_equal( obs_t[0][:4, :], np.array([[0., 0., 0., 0., 0.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.], [3., 3., 3., 3., 3.]]) ) np.testing.assert_almost_equal( action_t[0][:4, :], np.array([[0.], [1.], [2.], [3.]]) ) np.testing.assert_almost_equal( reward[:4], np.array([0., 1., 2., 3.]) ) np.testing.assert_almost_equal( done[:4], [0., 0., 0., 0.] ) np.testing.assert_almost_equal( all_obs_t[:4, :], np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [2., 2., 2., 2., 2., 2., 2., 2., 2., 2.], [3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]]) ) class TestSACMultiFeedForwardPolicy(unittest.TestCase): """Test MultiFeedForwardPolicy in hbaselines/multi_fcnet/sac.py.""" def setUp(self): self.sess = tf.compat.v1.Session() # Shared policy parameters self.policy_params_shared = { 'sess': self.sess, 'ac_space': Box(low=-1, high=1, shape=(1,)), 'co_space': Box(low=-2, high=2, shape=(2,)), 'ob_space': Box(low=-3, high=3, shape=(3,)), 'all_ob_space': Box(low=-3, high=3, shape=(10,)), 'layers': [256, 256], 'verbose': 0, } self.policy_params_shared.update(SAC_PARAMS.copy()) self.policy_params_shared.update(MULTI_FEEDFORWARD_PARAMS.copy()) self.policy_params_shared['shared'] = True # Independent policy parameters self.policy_params_independent = { 'sess': self.sess, 'ac_space': { 'a': Box(low=-1, high=1, shape=(1,)), 'b': Box(low=-2, high=2, shape=(2,)), }, 'co_space': { 'a': Box(low=-3, high=3, shape=(3,)), 'b': Box(low=-4, high=4, shape=(4,)), }, 'ob_space': { 'a': Box(low=-5, high=5, shape=(5,)), 'b': Box(low=-6, high=6, shape=(6,)), }, 'all_ob_space': Box(low=-6, high=6, shape=(18,)), 'layers': [256, 256], 'verbose': 0, } self.policy_params_independent.update(SAC_PARAMS.copy()) self.policy_params_independent.update(MULTI_FEEDFORWARD_PARAMS.copy()) self.policy_params_independent['shared'] = False def tearDown(self): self.sess.close() del self.policy_params_shared del self.policy_params_independent # Clear the graph. tf.compat.v1.reset_default_graph() def test_init_1(self): """Check the functionality of the __init__() method. This method is tested for the following features: 1. The proper structure graph was generated. 2. All input placeholders are correct. This is done for the following cases: 1. maddpg = False, shared = False 2. maddpg = False, shared = True 3. maddpg = True, shared = False 4. maddpg = True, shared = True """ policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = False policy = SACMultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['a/model/log_alpha:0', 'a/model/pi/fc0/bias:0', 'a/model/pi/fc0/kernel:0', 'a/model/pi/fc1/bias:0', 'a/model/pi/fc1/kernel:0', 'a/model/pi/log_std/bias:0', 'a/model/pi/log_std/kernel:0', 'a/model/pi/mean/bias:0', 'a/model/pi/mean/kernel:0', 'a/model/value_fns/qf1/fc0/bias:0', 'a/model/value_fns/qf1/fc0/kernel:0', 'a/model/value_fns/qf1/fc1/bias:0', 'a/model/value_fns/qf1/fc1/kernel:0', 'a/model/value_fns/qf1/qf_output/bias:0', 'a/model/value_fns/qf1/qf_output/kernel:0', 'a/model/value_fns/qf2/fc0/bias:0', 'a/model/value_fns/qf2/fc0/kernel:0', 'a/model/value_fns/qf2/fc1/bias:0', 'a/model/value_fns/qf2/fc1/kernel:0', 'a/model/value_fns/qf2/qf_output/bias:0', 'a/model/value_fns/qf2/qf_output/kernel:0', 'a/model/value_fns/vf/fc0/bias:0', 'a/model/value_fns/vf/fc0/kernel:0', 'a/model/value_fns/vf/fc1/bias:0', 'a/model/value_fns/vf/fc1/kernel:0', 'a/model/value_fns/vf/vf_output/bias:0', 'a/model/value_fns/vf/vf_output/kernel:0', 'a/target/value_fns/vf/fc0/bias:0', 'a/target/value_fns/vf/fc0/kernel:0', 'a/target/value_fns/vf/fc1/bias:0', 'a/target/value_fns/vf/fc1/kernel:0', 'a/target/value_fns/vf/vf_output/bias:0', 'a/target/value_fns/vf/vf_output/kernel:0', 'b/model/log_alpha:0', 'b/model/pi/fc0/bias:0', 'b/model/pi/fc0/kernel:0', 'b/model/pi/fc1/bias:0', 'b/model/pi/fc1/kernel:0', 'b/model/pi/log_std/bias:0', 'b/model/pi/log_std/kernel:0', 'b/model/pi/mean/bias:0', 'b/model/pi/mean/kernel:0', 'b/model/value_fns/qf1/fc0/bias:0', 'b/model/value_fns/qf1/fc0/kernel:0', 'b/model/value_fns/qf1/fc1/bias:0', 'b/model/value_fns/qf1/fc1/kernel:0', 'b/model/value_fns/qf1/qf_output/bias:0', 'b/model/value_fns/qf1/qf_output/kernel:0', 'b/model/value_fns/qf2/fc0/bias:0', 'b/model/value_fns/qf2/fc0/kernel:0', 'b/model/value_fns/qf2/fc1/bias:0', 'b/model/value_fns/qf2/fc1/kernel:0', 'b/model/value_fns/qf2/qf_output/bias:0', 'b/model/value_fns/qf2/qf_output/kernel:0', 'b/model/value_fns/vf/fc0/bias:0', 'b/model/value_fns/vf/fc0/kernel:0', 'b/model/value_fns/vf/fc1/bias:0', 'b/model/value_fns/vf/fc1/kernel:0', 'b/model/value_fns/vf/vf_output/bias:0', 'b/model/value_fns/vf/vf_output/kernel:0', 'b/target/value_fns/vf/fc0/bias:0', 'b/target/value_fns/vf/fc0/kernel:0', 'b/target/value_fns/vf/fc1/bias:0', 'b/target/value_fns/vf/fc1/kernel:0', 'b/target/value_fns/vf/vf_output/bias:0', 'b/target/value_fns/vf/vf_output/kernel:0'] ) # Check observation/action/context spaces of the agents self.assertEqual(policy.agents['a'].ac_space, self.policy_params_independent['ac_space']['a']) self.assertEqual(policy.agents['a'].ob_space, self.policy_params_independent['ob_space']['a']) self.assertEqual(policy.agents['a'].co_space, self.policy_params_independent['co_space']['a']) self.assertEqual(policy.agents['b'].ac_space, self.policy_params_independent['ac_space']['b']) self.assertEqual(policy.agents['b'].ob_space, self.policy_params_independent['ob_space']['b']) self.assertEqual(policy.agents['b'].co_space, self.policy_params_independent['co_space']['b']) # Check the instantiation of the class attributes. self.assertTrue(not policy.shared) self.assertTrue(not policy.maddpg) def test_init_2(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = False policy = SACMultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['model/log_alpha:0', 'model/pi/fc0/bias:0', 'model/pi/fc0/kernel:0', 'model/pi/fc1/bias:0', 'model/pi/fc1/kernel:0', 'model/pi/log_std/bias:0', 'model/pi/log_std/kernel:0', 'model/pi/mean/bias:0', 'model/pi/mean/kernel:0', 'model/value_fns/qf1/fc0/bias:0', 'model/value_fns/qf1/fc0/kernel:0', 'model/value_fns/qf1/fc1/bias:0', 'model/value_fns/qf1/fc1/kernel:0', 'model/value_fns/qf1/qf_output/bias:0', 'model/value_fns/qf1/qf_output/kernel:0', 'model/value_fns/qf2/fc0/bias:0', 'model/value_fns/qf2/fc0/kernel:0', 'model/value_fns/qf2/fc1/bias:0', 'model/value_fns/qf2/fc1/kernel:0', 'model/value_fns/qf2/qf_output/bias:0', 'model/value_fns/qf2/qf_output/kernel:0', 'model/value_fns/vf/fc0/bias:0', 'model/value_fns/vf/fc0/kernel:0', 'model/value_fns/vf/fc1/bias:0', 'model/value_fns/vf/fc1/kernel:0', 'model/value_fns/vf/vf_output/bias:0', 'model/value_fns/vf/vf_output/kernel:0', 'target/value_fns/vf/fc0/bias:0', 'target/value_fns/vf/fc0/kernel:0', 'target/value_fns/vf/fc1/bias:0', 'target/value_fns/vf/fc1/kernel:0', 'target/value_fns/vf/vf_output/bias:0', 'target/value_fns/vf/vf_output/kernel:0'] ) # Check observation/action/context spaces of the agents self.assertEqual(policy.agents['policy'].ac_space, self.policy_params_shared['ac_space']) self.assertEqual(policy.agents['policy'].ob_space, self.policy_params_shared['ob_space']) self.assertEqual(policy.agents['policy'].co_space, self.policy_params_shared['co_space']) # Check the instantiation of the class attributes. self.assertTrue(policy.shared) self.assertTrue(not policy.maddpg) def test_init_3(self): policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = True policy = SACMultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['a/model/centralized_value_fns/qf1/fc0/bias:0', 'a/model/centralized_value_fns/qf1/fc0/kernel:0', 'a/model/centralized_value_fns/qf1/fc1/bias:0', 'a/model/centralized_value_fns/qf1/fc1/kernel:0', 'a/model/centralized_value_fns/qf1/qf_output/bias:0', 'a/model/centralized_value_fns/qf1/qf_output/kernel:0', 'a/model/centralized_value_fns/qf2/fc0/bias:0', 'a/model/centralized_value_fns/qf2/fc0/kernel:0', 'a/model/centralized_value_fns/qf2/fc1/bias:0', 'a/model/centralized_value_fns/qf2/fc1/kernel:0', 'a/model/centralized_value_fns/qf2/qf_output/bias:0', 'a/model/centralized_value_fns/qf2/qf_output/kernel:0', 'a/model/centralized_value_fns/vf/fc0/bias:0', 'a/model/centralized_value_fns/vf/fc0/kernel:0', 'a/model/centralized_value_fns/vf/fc1/bias:0', 'a/model/centralized_value_fns/vf/fc1/kernel:0', 'a/model/centralized_value_fns/vf/vf_output/bias:0', 'a/model/centralized_value_fns/vf/vf_output/kernel:0', 'a/model/log_alpha:0', 'a/model/pi/fc0/bias:0', 'a/model/pi/fc0/kernel:0', 'a/model/pi/fc1/bias:0', 'a/model/pi/fc1/kernel:0', 'a/model/pi/log_std/bias:0', 'a/model/pi/log_std/kernel:0', 'a/model/pi/mean/bias:0', 'a/model/pi/mean/kernel:0', 'a/target/centralized_value_fns/vf/fc0/bias:0', 'a/target/centralized_value_fns/vf/fc0/kernel:0', 'a/target/centralized_value_fns/vf/fc1/bias:0', 'a/target/centralized_value_fns/vf/fc1/kernel:0', 'a/target/centralized_value_fns/vf/vf_output/bias:0', 'a/target/centralized_value_fns/vf/vf_output/kernel:0', 'b/model/centralized_value_fns/qf1/fc0/bias:0', 'b/model/centralized_value_fns/qf1/fc0/kernel:0', 'b/model/centralized_value_fns/qf1/fc1/bias:0', 'b/model/centralized_value_fns/qf1/fc1/kernel:0', 'b/model/centralized_value_fns/qf1/qf_output/bias:0', 'b/model/centralized_value_fns/qf1/qf_output/kernel:0', 'b/model/centralized_value_fns/qf2/fc0/bias:0', 'b/model/centralized_value_fns/qf2/fc0/kernel:0', 'b/model/centralized_value_fns/qf2/fc1/bias:0', 'b/model/centralized_value_fns/qf2/fc1/kernel:0', 'b/model/centralized_value_fns/qf2/qf_output/bias:0', 'b/model/centralized_value_fns/qf2/qf_output/kernel:0', 'b/model/centralized_value_fns/vf/fc0/bias:0', 'b/model/centralized_value_fns/vf/fc0/kernel:0', 'b/model/centralized_value_fns/vf/fc1/bias:0', 'b/model/centralized_value_fns/vf/fc1/kernel:0', 'b/model/centralized_value_fns/vf/vf_output/bias:0', 'b/model/centralized_value_fns/vf/vf_output/kernel:0', 'b/model/log_alpha:0', 'b/model/pi/fc0/bias:0', 'b/model/pi/fc0/kernel:0', 'b/model/pi/fc1/bias:0', 'b/model/pi/fc1/kernel:0', 'b/model/pi/log_std/bias:0', 'b/model/pi/log_std/kernel:0', 'b/model/pi/mean/bias:0', 'b/model/pi/mean/kernel:0', 'b/target/centralized_value_fns/vf/fc0/bias:0', 'b/target/centralized_value_fns/vf/fc0/kernel:0', 'b/target/centralized_value_fns/vf/fc1/bias:0', 'b/target/centralized_value_fns/vf/fc1/kernel:0', 'b/target/centralized_value_fns/vf/vf_output/bias:0', 'b/target/centralized_value_fns/vf/vf_output/kernel:0'] ) # Check observation/action/context spaces of the agents for key in policy.ac_space.keys(): self.assertEqual(int(policy.all_obs_ph[key].shape[-1]), int(policy.all_ob_space.shape[0])) self.assertEqual(int(policy.all_obs1_ph[key].shape[-1]), int(policy.all_ob_space.shape[0])) self.assertEqual(int(policy.all_action_ph[key].shape[-1]), sum(policy.ac_space[key].shape[0] for key in policy.ac_space.keys())) self.assertEqual(int(policy.action_ph[key].shape[-1]), int(policy.ac_space[key].shape[0])) self.assertEqual(int(policy.obs_ph[key].shape[-1]), int(policy.ob_space[key].shape[0] + policy.co_space[key].shape[0])) self.assertEqual(int(policy.obs1_ph[key].shape[-1]), int(policy.ob_space[key].shape[0] + policy.co_space[key].shape[0])) # Check the instantiation of the class attributes. self.assertTrue(not policy.shared) self.assertTrue(policy.maddpg) def test_init_4(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = True policy = SACMultiFeedForwardPolicy(**policy_params) self.assertListEqual( sorted([var.name for var in get_trainable_vars()]), ['model/centralized_value_fns/qf1/fc0/bias:0', 'model/centralized_value_fns/qf1/fc0/kernel:0', 'model/centralized_value_fns/qf1/fc1/bias:0', 'model/centralized_value_fns/qf1/fc1/kernel:0', 'model/centralized_value_fns/qf1/qf_output/bias:0', 'model/centralized_value_fns/qf1/qf_output/kernel:0', 'model/centralized_value_fns/qf2/fc0/bias:0', 'model/centralized_value_fns/qf2/fc0/kernel:0', 'model/centralized_value_fns/qf2/fc1/bias:0', 'model/centralized_value_fns/qf2/fc1/kernel:0', 'model/centralized_value_fns/qf2/qf_output/bias:0', 'model/centralized_value_fns/qf2/qf_output/kernel:0', 'model/centralized_value_fns/vf/fc0/bias:0', 'model/centralized_value_fns/vf/fc0/kernel:0', 'model/centralized_value_fns/vf/fc1/bias:0', 'model/centralized_value_fns/vf/fc1/kernel:0', 'model/centralized_value_fns/vf/vf_output/bias:0', 'model/centralized_value_fns/vf/vf_output/kernel:0', 'model/log_alpha:0', 'model/pi/fc0/bias:0', 'model/pi/fc0/kernel:0', 'model/pi/fc1/bias:0', 'model/pi/fc1/kernel:0', 'model/pi/log_std/bias:0', 'model/pi/log_std/kernel:0', 'model/pi/mean/bias:0', 'model/pi/mean/kernel:0', 'target/centralized_value_fns/vf/fc0/bias:0', 'target/centralized_value_fns/vf/fc0/kernel:0', 'target/centralized_value_fns/vf/fc1/bias:0', 'target/centralized_value_fns/vf/fc1/kernel:0', 'target/centralized_value_fns/vf/vf_output/bias:0', 'target/centralized_value_fns/vf/vf_output/kernel:0'] ) # Check observation/action/context spaces of the agents self.assertEqual(int(policy.all_obs_ph.shape[-1]), policy.all_ob_space.shape[0]) self.assertEqual(int(policy.all_obs1_ph.shape[-1]), policy.all_ob_space.shape[0]) self.assertEqual(int(policy.all_action_ph.shape[-1]), policy.n_agents * policy.ac_space.shape[0]) self.assertEqual(int(policy.action_ph[0].shape[-1]), policy.ac_space.shape[0]) self.assertEqual(int(policy.obs_ph[0].shape[-1]), int(policy.ob_space.shape[0] + policy.co_space.shape[0])) self.assertEqual(int(policy.obs1_ph[0].shape[-1]), int(policy.ob_space.shape[0] + policy.co_space.shape[0])) # Check the instantiation of the class attributes. self.assertTrue(policy.shared) self.assertTrue(policy.maddpg) def test_initialize_1(self): """Check the functionality of the initialize() method. This test validates that the target variables are properly initialized when initialize is called. This is done for the following cases: 1. maddpg = False, shared = False 2. maddpg = False, shared = True 3. maddpg = True, shared = False 4. maddpg = True, shared = True """ policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = False policy = SACMultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'a/model/value_fns/vf/fc0/kernel:0', 'a/model/value_fns/vf/fc0/bias:0', 'a/model/value_fns/vf/fc1/kernel:0', 'a/model/value_fns/vf/fc1/bias:0', 'a/model/value_fns/vf/vf_output/kernel:0', 'a/model/value_fns/vf/vf_output/bias:0', 'b/model/value_fns/vf/fc0/kernel:0', 'b/model/value_fns/vf/fc0/bias:0', 'b/model/value_fns/vf/fc1/kernel:0', 'b/model/value_fns/vf/fc1/bias:0', 'b/model/value_fns/vf/vf_output/kernel:0', 'b/model/value_fns/vf/vf_output/bias:0', ] target_var_list = [ 'a/target/value_fns/vf/fc0/kernel:0', 'a/target/value_fns/vf/fc0/bias:0', 'a/target/value_fns/vf/fc1/kernel:0', 'a/target/value_fns/vf/fc1/bias:0', 'a/target/value_fns/vf/vf_output/kernel:0', 'a/target/value_fns/vf/vf_output/bias:0', 'b/target/value_fns/vf/fc0/kernel:0', 'b/target/value_fns/vf/fc0/bias:0', 'b/target/value_fns/vf/fc1/kernel:0', 'b/target/value_fns/vf/fc1/bias:0', 'b/target/value_fns/vf/vf_output/kernel:0', 'b/target/value_fns/vf/vf_output/bias:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_initialize_2(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = False policy = SACMultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'model/value_fns/vf/fc0/kernel:0', 'model/value_fns/vf/fc0/bias:0', 'model/value_fns/vf/fc1/kernel:0', 'model/value_fns/vf/fc1/bias:0', 'model/value_fns/vf/vf_output/kernel:0', 'model/value_fns/vf/vf_output/bias:0', ] target_var_list = [ 'target/value_fns/vf/fc0/kernel:0', 'target/value_fns/vf/fc0/bias:0', 'target/value_fns/vf/fc1/kernel:0', 'target/value_fns/vf/fc1/bias:0', 'target/value_fns/vf/vf_output/kernel:0', 'target/value_fns/vf/vf_output/bias:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_initialize_3(self): policy_params = self.policy_params_independent.copy() policy_params["maddpg"] = True policy = SACMultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'a/model/centralized_value_fns/vf/fc0/kernel:0', 'a/model/centralized_value_fns/vf/fc0/bias:0', 'a/model/centralized_value_fns/vf/fc1/kernel:0', 'a/model/centralized_value_fns/vf/fc1/bias:0', 'a/model/centralized_value_fns/vf/vf_output/kernel:0', 'a/model/centralized_value_fns/vf/vf_output/bias:0', 'b/model/centralized_value_fns/vf/fc0/kernel:0', 'b/model/centralized_value_fns/vf/fc0/bias:0', 'b/model/centralized_value_fns/vf/fc1/kernel:0', 'b/model/centralized_value_fns/vf/fc1/bias:0', 'b/model/centralized_value_fns/vf/vf_output/kernel:0', 'b/model/centralized_value_fns/vf/vf_output/bias:0', ] target_var_list = [ 'a/target/centralized_value_fns/vf/fc0/kernel:0', 'a/target/centralized_value_fns/vf/fc0/bias:0', 'a/target/centralized_value_fns/vf/fc1/kernel:0', 'a/target/centralized_value_fns/vf/fc1/bias:0', 'a/target/centralized_value_fns/vf/vf_output/kernel:0', 'a/target/centralized_value_fns/vf/vf_output/bias:0', 'b/target/centralized_value_fns/vf/fc0/kernel:0', 'b/target/centralized_value_fns/vf/fc0/bias:0', 'b/target/centralized_value_fns/vf/fc1/kernel:0', 'b/target/centralized_value_fns/vf/fc1/bias:0', 'b/target/centralized_value_fns/vf/vf_output/kernel:0', 'b/target/centralized_value_fns/vf/vf_output/bias:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) def test_initialize_4(self): policy_params = self.policy_params_shared.copy() policy_params["maddpg"] = True policy = SACMultiFeedForwardPolicy(**policy_params) # Initialize the variables of the policy. policy.sess.run(tf.compat.v1.global_variables_initializer()) # Run the initialize method. policy.initialize() model_var_list = [ 'model/centralized_value_fns/vf/fc0/bias:0', 'model/centralized_value_fns/vf/fc0/kernel:0', 'model/centralized_value_fns/vf/fc1/bias:0', 'model/centralized_value_fns/vf/fc1/kernel:0', 'model/centralized_value_fns/vf/vf_output/bias:0', 'model/centralized_value_fns/vf/vf_output/kernel:0', ] target_var_list = [ 'target/centralized_value_fns/vf/fc0/bias:0', 'target/centralized_value_fns/vf/fc0/kernel:0', 'target/centralized_value_fns/vf/fc1/bias:0', 'target/centralized_value_fns/vf/fc1/kernel:0', 'target/centralized_value_fns/vf/vf_output/bias:0', 'target/centralized_value_fns/vf/vf_output/kernel:0', ] for model, target in zip(model_var_list, target_var_list): with tf.compat.v1.variable_scope( tf.compat.v1.get_variable_scope(), reuse=True): model_val = policy.sess.run(model) target_val = policy.sess.run(target) np.testing.assert_almost_equal(model_val, target_val) if __name__ == '__main__': unittest.main()
[ "unittest.main", "hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy", "hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy", "hbaselines.utils.tf_util.get_trainable_vars", "hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy", "numpy.testing.assert_almost_equal", "hbaselines.algorithms.off_policy.TD3_PARAMS.copy", "tensorflow.compat.v1.get_variable_scope", "tensorflow.compat.v1.Session", "numpy.array", "gym.spaces.Box", "tensorflow.compat.v1.reset_default_graph", "hbaselines.algorithms.off_policy.SAC_PARAMS.copy", "tensorflow.compat.v1.global_variables_initializer" ]
[((73124, 73139), 'unittest.main', 'unittest.main', ([], {}), '()\n', (73137, 73139), False, 'import unittest\n'), ((718, 740), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), '()\n', (738, 740), True, 'import tensorflow as tf\n'), ((2397, 2431), 'tensorflow.compat.v1.reset_default_graph', 'tf.compat.v1.reset_default_graph', ([], {}), '()\n', (2429, 2431), True, 'import tensorflow as tf\n'), ((2807, 2849), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (2832, 2849), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((5300, 5362), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['done[:4]', '[0.0, 0.0, 0.0, 0.0]'], {}), '(done[:4], [0.0, 0.0, 0.0, 0.0])\n', (5330, 5362), True, 'import numpy as np\n'), ((6500, 6562), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['done[:4]', '[0.0, 0.0, 0.0, 0.0]'], {}), '(done[:4], [0.0, 0.0, 0.0, 0.0])\n', (6530, 6562), True, 'import numpy as np\n'), ((6747, 6789), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (6772, 6789), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((8910, 8996), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['done[:8]', '[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]'], {}), '(done[:8], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0])\n', (8940, 8996), True, 'import numpy as np\n'), ((9191, 9213), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), '()\n', (9211, 9213), True, 'import tensorflow as tf\n'), ((10870, 10904), 'tensorflow.compat.v1.reset_default_graph', 'tf.compat.v1.reset_default_graph', ([], {}), '()\n', (10902, 10904), True, 'import tensorflow as tf\n'), ((11499, 11541), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (11524, 11541), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((15829, 15871), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (15854, 15871), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((18157, 18199), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (18182, 18199), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((23306, 23348), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (23331, 23348), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((26773, 26815), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (26798, 26815), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((30567, 30609), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (30592, 30609), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((32798, 32840), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (32823, 32840), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((37167, 37209), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (37192, 37209), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((39909, 39951), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (39934, 39951), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((42614, 42676), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['done[:4]', '[0.0, 0.0, 0.0, 0.0]'], {}), '(done[:4], [0.0, 0.0, 0.0, 0.0])\n', (42644, 42676), True, 'import numpy as np\n'), ((44400, 44462), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['done[:4]', '[0.0, 0.0, 0.0, 0.0]'], {}), '(done[:4], [0.0, 0.0, 0.0, 0.0])\n', (44430, 44462), True, 'import numpy as np\n'), ((45242, 45284), 'hbaselines.multi_fcnet.td3.MultiFeedForwardPolicy', 'TD3MultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (45267, 45284), True, 'from hbaselines.multi_fcnet.td3 import MultiFeedForwardPolicy as TD3MultiFeedForwardPolicy\n'), ((47360, 47422), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['done[:4]', '[0.0, 0.0, 0.0, 0.0]'], {}), '(done[:4], [0.0, 0.0, 0.0, 0.0])\n', (47390, 47422), True, 'import numpy as np\n'), ((47963, 47985), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), '()\n', (47983, 47985), True, 'import tensorflow as tf\n'), ((49642, 49676), 'tensorflow.compat.v1.reset_default_graph', 'tf.compat.v1.reset_default_graph', ([], {}), '()\n', (49674, 49676), True, 'import tensorflow as tf\n'), ((50271, 50313), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (50296, 50313), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((54741, 54783), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (54766, 54783), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((57145, 57187), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (57170, 57187), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((62449, 62491), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (62474, 62491), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((65992, 66034), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (66017, 66034), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((68010, 68052), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (68035, 68052), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((69402, 69444), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (69427, 69444), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((71707, 71749), 'hbaselines.multi_fcnet.sac.MultiFeedForwardPolicy', 'SACMultiFeedForwardPolicy', ([], {}), '(**policy_params)\n', (71732, 71749), True, 'from hbaselines.multi_fcnet.sac import MultiFeedForwardPolicy as SACMultiFeedForwardPolicy\n'), ((870, 901), 'gym.spaces.Box', 'Box', ([], {'low': '(-1)', 'high': '(1)', 'shape': '(1,)'}), '(low=-1, high=1, shape=(1,))\n', (873, 901), False, 'from gym.spaces import Box\n'), ((927, 958), 'gym.spaces.Box', 'Box', ([], {'low': '(-2)', 'high': '(2)', 'shape': '(2,)'}), '(low=-2, high=2, shape=(2,))\n', (930, 958), False, 'from gym.spaces import Box\n'), ((984, 1015), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(3,)'}), '(low=-3, high=3, shape=(3,))\n', (987, 1015), False, 'from gym.spaces import Box\n'), ((1045, 1077), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(10,)'}), '(low=-3, high=3, shape=(10,))\n', (1048, 1077), False, 'from gym.spaces import Box\n'), ((1190, 1207), 'hbaselines.algorithms.off_policy.TD3_PARAMS.copy', 'TD3_PARAMS.copy', ([], {}), '()\n', (1205, 1207), False, 'from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS\n'), ((1250, 1281), 'hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy', 'MULTI_FEEDFORWARD_PARAMS.copy', ([], {}), '()\n', (1279, 1281), False, 'from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS\n'), ((1924, 1956), 'gym.spaces.Box', 'Box', ([], {'low': '(-6)', 'high': '(6)', 'shape': '(18,)'}), '(low=-6, high=6, shape=(18,))\n', (1927, 1956), False, 'from gym.spaces import Box\n'), ((2074, 2091), 'hbaselines.algorithms.off_policy.TD3_PARAMS.copy', 'TD3_PARAMS.copy', ([], {}), '()\n', (2089, 2091), False, 'from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS\n'), ((2139, 2170), 'hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy', 'MULTI_FEEDFORWARD_PARAMS.copy', ([], {}), '()\n', (2168, 2170), False, 'from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS\n'), ((2925, 2968), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (2966, 2968), True, 'import tensorflow as tf\n'), ((4827, 5015), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, \n 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0, \n 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]])\n', (4835, 5015), True, 'import numpy as np\n'), ((5132, 5170), 'numpy.array', 'np.array', (['[[0.0], [1.0], [2.0], [3.0]]'], {}), '([[0.0], [1.0], [2.0], [3.0]])\n', (5140, 5170), True, 'import numpy as np\n'), ((5254, 5284), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (5262, 5284), True, 'import numpy as np\n'), ((5979, 6206), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]])\n', (5987, 6206), True, 'import numpy as np\n'), ((6316, 6374), 'numpy.array', 'np.array', (['[[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]'], {}), '([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]])\n', (6324, 6374), True, 'import numpy as np\n'), ((6454, 6484), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (6462, 6484), True, 'import numpy as np\n'), ((6865, 6908), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (6906, 6908), True, 'import tensorflow as tf\n'), ((8269, 8510), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0,\n 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, \n 3.0, 3.0, 3.0], [3.0, 3.0, 3.0, 3.0, 3.0], [4.0, 4.0, 4.0, 4.0, 4.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, \n 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0], [\n 3.0, 3.0, 3.0, 3.0, 3.0], [3.0, 3.0, 3.0, 3.0, 3.0], [4.0, 4.0, 4.0, \n 4.0, 4.0]])\n', (8277, 8510), True, 'import numpy as np\n'), ((8702, 8768), 'numpy.array', 'np.array', (['[[0.0], [1.0], [1.0], [2.0], [2.0], [3.0], [3.0], [4.0]]'], {}), '([[0.0], [1.0], [1.0], [2.0], [2.0], [3.0], [3.0], [4.0]])\n', (8710, 8768), True, 'import numpy as np\n'), ((8848, 8898), 'numpy.array', 'np.array', (['[0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0]'], {}), '([0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0])\n', (8856, 8898), True, 'import numpy as np\n'), ((9343, 9374), 'gym.spaces.Box', 'Box', ([], {'low': '(-1)', 'high': '(1)', 'shape': '(1,)'}), '(low=-1, high=1, shape=(1,))\n', (9346, 9374), False, 'from gym.spaces import Box\n'), ((9400, 9431), 'gym.spaces.Box', 'Box', ([], {'low': '(-2)', 'high': '(2)', 'shape': '(2,)'}), '(low=-2, high=2, shape=(2,))\n', (9403, 9431), False, 'from gym.spaces import Box\n'), ((9457, 9488), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(3,)'}), '(low=-3, high=3, shape=(3,))\n', (9460, 9488), False, 'from gym.spaces import Box\n'), ((9518, 9550), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(10,)'}), '(low=-3, high=3, shape=(10,))\n', (9521, 9550), False, 'from gym.spaces import Box\n'), ((9663, 9680), 'hbaselines.algorithms.off_policy.TD3_PARAMS.copy', 'TD3_PARAMS.copy', ([], {}), '()\n', (9678, 9680), False, 'from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS\n'), ((9723, 9754), 'hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy', 'MULTI_FEEDFORWARD_PARAMS.copy', ([], {}), '()\n', (9752, 9754), False, 'from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS\n'), ((10397, 10429), 'gym.spaces.Box', 'Box', ([], {'low': '(-6)', 'high': '(6)', 'shape': '(18,)'}), '(low=-6, high=6, shape=(18,))\n', (10400, 10429), False, 'from gym.spaces import Box\n'), ((10547, 10564), 'hbaselines.algorithms.off_policy.TD3_PARAMS.copy', 'TD3_PARAMS.copy', ([], {}), '()\n', (10562, 10564), False, 'from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS\n'), ((10612, 10643), 'hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy', 'MULTI_FEEDFORWARD_PARAMS.copy', ([], {}), '()\n', (10641, 10643), False, 'from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS\n'), ((26891, 26934), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (26932, 26934), True, 'import tensorflow as tf\n'), ((30365, 30418), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (30395, 30418), True, 'import numpy as np\n'), ((30685, 30728), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (30726, 30728), True, 'import tensorflow as tf\n'), ((32592, 32645), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (32622, 32645), True, 'import numpy as np\n'), ((32916, 32959), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (32957, 32959), True, 'import tensorflow as tf\n'), ((36966, 37019), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (36996, 37019), True, 'import numpy as np\n'), ((37285, 37328), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (37326, 37328), True, 'import tensorflow as tf\n'), ((39481, 39534), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (39511, 39534), True, 'import numpy as np\n'), ((40027, 40070), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (40068, 40070), True, 'import tensorflow as tf\n'), ((42141, 42329), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, \n 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0, \n 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]])\n', (42149, 42329), True, 'import numpy as np\n'), ((42446, 42484), 'numpy.array', 'np.array', (['[[0.0], [1.0], [2.0], [3.0]]'], {}), '([[0.0], [1.0], [2.0], [3.0]])\n', (42454, 42484), True, 'import numpy as np\n'), ((42568, 42598), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (42576, 42598), True, 'import numpy as np\n'), ((42790, 43189), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0,\n 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0,\n 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, \n 3.0, 3.0, 3.0]])\n', (42798, 43189), True, 'import numpy as np\n'), ((43879, 44106), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]])\n', (43887, 44106), True, 'import numpy as np\n'), ((44216, 44274), 'numpy.array', 'np.array', (['[[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]'], {}), '([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]])\n', (44224, 44274), True, 'import numpy as np\n'), ((44354, 44384), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (44362, 44384), True, 'import numpy as np\n'), ((44576, 44975), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0,\n 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0], [3.0,\n 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, \n 3.0, 3.0, 3.0]])\n', (44584, 44975), True, 'import numpy as np\n'), ((45360, 45403), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (45401, 45403), True, 'import tensorflow as tf\n'), ((46932, 47055), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0,\n 2.0], [3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, \n 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0]])\n', (46940, 47055), True, 'import numpy as np\n'), ((47192, 47230), 'numpy.array', 'np.array', (['[[0.0], [1.0], [2.0], [3.0]]'], {}), '([[0.0], [1.0], [2.0], [3.0]])\n', (47200, 47230), True, 'import numpy as np\n'), ((47314, 47344), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (47322, 47344), True, 'import numpy as np\n'), ((47536, 47763), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, \n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0,\n 2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]])\n', (47544, 47763), True, 'import numpy as np\n'), ((48115, 48146), 'gym.spaces.Box', 'Box', ([], {'low': '(-1)', 'high': '(1)', 'shape': '(1,)'}), '(low=-1, high=1, shape=(1,))\n', (48118, 48146), False, 'from gym.spaces import Box\n'), ((48172, 48203), 'gym.spaces.Box', 'Box', ([], {'low': '(-2)', 'high': '(2)', 'shape': '(2,)'}), '(low=-2, high=2, shape=(2,))\n', (48175, 48203), False, 'from gym.spaces import Box\n'), ((48229, 48260), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(3,)'}), '(low=-3, high=3, shape=(3,))\n', (48232, 48260), False, 'from gym.spaces import Box\n'), ((48290, 48322), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(10,)'}), '(low=-3, high=3, shape=(10,))\n', (48293, 48322), False, 'from gym.spaces import Box\n'), ((48435, 48452), 'hbaselines.algorithms.off_policy.SAC_PARAMS.copy', 'SAC_PARAMS.copy', ([], {}), '()\n', (48450, 48452), False, 'from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS\n'), ((48495, 48526), 'hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy', 'MULTI_FEEDFORWARD_PARAMS.copy', ([], {}), '()\n', (48524, 48526), False, 'from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS\n'), ((49169, 49201), 'gym.spaces.Box', 'Box', ([], {'low': '(-6)', 'high': '(6)', 'shape': '(18,)'}), '(low=-6, high=6, shape=(18,))\n', (49172, 49201), False, 'from gym.spaces import Box\n'), ((49319, 49336), 'hbaselines.algorithms.off_policy.SAC_PARAMS.copy', 'SAC_PARAMS.copy', ([], {}), '()\n', (49334, 49336), False, 'from hbaselines.algorithms.off_policy import SAC_PARAMS, TD3_PARAMS\n'), ((49384, 49415), 'hbaselines.algorithms.off_policy.MULTI_FEEDFORWARD_PARAMS.copy', 'MULTI_FEEDFORWARD_PARAMS.copy', ([], {}), '()\n', (49413, 49415), False, 'from hbaselines.algorithms.off_policy import MULTI_FEEDFORWARD_PARAMS\n'), ((66110, 66153), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (66151, 66153), True, 'import tensorflow as tf\n'), ((67808, 67861), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (67838, 67861), True, 'import numpy as np\n'), ((68128, 68171), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (68169, 68171), True, 'import tensorflow as tf\n'), ((69196, 69249), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (69226, 69249), True, 'import numpy as np\n'), ((69520, 69563), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (69561, 69563), True, 'import tensorflow as tf\n'), ((71506, 71559), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (71536, 71559), True, 'import numpy as np\n'), ((71825, 71868), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (71866, 71868), True, 'import tensorflow as tf\n'), ((73037, 73090), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['model_val', 'target_val'], {}), '(model_val, target_val)\n', (73067, 73090), True, 'import numpy as np\n'), ((1496, 1527), 'gym.spaces.Box', 'Box', ([], {'low': '(-1)', 'high': '(1)', 'shape': '(1,)'}), '(low=-1, high=1, shape=(1,))\n', (1499, 1527), False, 'from gym.spaces import Box\n'), ((1550, 1581), 'gym.spaces.Box', 'Box', ([], {'low': '(-2)', 'high': '(2)', 'shape': '(2,)'}), '(low=-2, high=2, shape=(2,))\n', (1553, 1581), False, 'from gym.spaces import Box\n'), ((1645, 1676), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(3,)'}), '(low=-3, high=3, shape=(3,))\n', (1648, 1676), False, 'from gym.spaces import Box\n'), ((1699, 1730), 'gym.spaces.Box', 'Box', ([], {'low': '(-4)', 'high': '(4)', 'shape': '(4,)'}), '(low=-4, high=4, shape=(4,))\n', (1702, 1730), False, 'from gym.spaces import Box\n'), ((1794, 1825), 'gym.spaces.Box', 'Box', ([], {'low': '(-5)', 'high': '(5)', 'shape': '(5,)'}), '(low=-5, high=5, shape=(5,))\n', (1797, 1825), False, 'from gym.spaces import Box\n'), ((1848, 1879), 'gym.spaces.Box', 'Box', ([], {'low': '(-6)', 'high': '(6)', 'shape': '(6,)'}), '(low=-6, high=6, shape=(6,))\n', (1851, 1879), False, 'from gym.spaces import Box\n'), ((9969, 10000), 'gym.spaces.Box', 'Box', ([], {'low': '(-1)', 'high': '(1)', 'shape': '(1,)'}), '(low=-1, high=1, shape=(1,))\n', (9972, 10000), False, 'from gym.spaces import Box\n'), ((10023, 10054), 'gym.spaces.Box', 'Box', ([], {'low': '(-2)', 'high': '(2)', 'shape': '(2,)'}), '(low=-2, high=2, shape=(2,))\n', (10026, 10054), False, 'from gym.spaces import Box\n'), ((10118, 10149), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(3,)'}), '(low=-3, high=3, shape=(3,))\n', (10121, 10149), False, 'from gym.spaces import Box\n'), ((10172, 10203), 'gym.spaces.Box', 'Box', ([], {'low': '(-4)', 'high': '(4)', 'shape': '(4,)'}), '(low=-4, high=4, shape=(4,))\n', (10175, 10203), False, 'from gym.spaces import Box\n'), ((10267, 10298), 'gym.spaces.Box', 'Box', ([], {'low': '(-5)', 'high': '(5)', 'shape': '(5,)'}), '(low=-5, high=5, shape=(5,))\n', (10270, 10298), False, 'from gym.spaces import Box\n'), ((10321, 10352), 'gym.spaces.Box', 'Box', ([], {'low': '(-6)', 'high': '(6)', 'shape': '(6,)'}), '(low=-6, high=6, shape=(6,))\n', (10324, 10352), False, 'from gym.spaces import Box\n'), ((48741, 48772), 'gym.spaces.Box', 'Box', ([], {'low': '(-1)', 'high': '(1)', 'shape': '(1,)'}), '(low=-1, high=1, shape=(1,))\n', (48744, 48772), False, 'from gym.spaces import Box\n'), ((48795, 48826), 'gym.spaces.Box', 'Box', ([], {'low': '(-2)', 'high': '(2)', 'shape': '(2,)'}), '(low=-2, high=2, shape=(2,))\n', (48798, 48826), False, 'from gym.spaces import Box\n'), ((48890, 48921), 'gym.spaces.Box', 'Box', ([], {'low': '(-3)', 'high': '(3)', 'shape': '(3,)'}), '(low=-3, high=3, shape=(3,))\n', (48893, 48921), False, 'from gym.spaces import Box\n'), ((48944, 48975), 'gym.spaces.Box', 'Box', ([], {'low': '(-4)', 'high': '(4)', 'shape': '(4,)'}), '(low=-4, high=4, shape=(4,))\n', (48947, 48975), False, 'from gym.spaces import Box\n'), ((49039, 49070), 'gym.spaces.Box', 'Box', ([], {'low': '(-5)', 'high': '(5)', 'shape': '(5,)'}), '(low=-5, high=5, shape=(5,))\n', (49042, 49070), False, 'from gym.spaces import Box\n'), ((49093, 49124), 'gym.spaces.Box', 'Box', ([], {'low': '(-6)', 'high': '(6)', 'shape': '(6,)'}), '(low=-6, high=6, shape=(6,))\n', (49096, 49124), False, 'from gym.spaces import Box\n'), ((30201, 30234), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (30232, 30234), True, 'import tensorflow as tf\n'), ((32428, 32461), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (32459, 32461), True, 'import tensorflow as tf\n'), ((36802, 36835), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (36833, 36835), True, 'import tensorflow as tf\n'), ((39317, 39350), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (39348, 39350), True, 'import tensorflow as tf\n'), ((67644, 67677), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (67675, 67677), True, 'import tensorflow as tf\n'), ((69032, 69065), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (69063, 69065), True, 'import tensorflow as tf\n'), ((71342, 71375), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (71373, 71375), True, 'import tensorflow as tf\n'), ((72873, 72906), 'tensorflow.compat.v1.get_variable_scope', 'tf.compat.v1.get_variable_scope', ([], {}), '()\n', (72904, 72906), True, 'import tensorflow as tf\n'), ((11613, 11633), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (11631, 11633), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((15943, 15963), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (15961, 15963), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((18271, 18291), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (18289, 18291), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((23420, 23440), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (23438, 23440), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((50385, 50405), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (50403, 50405), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((54855, 54875), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (54873, 54875), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((57259, 57279), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (57277, 57279), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n'), ((62563, 62583), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', ([], {}), '()\n', (62581, 62583), False, 'from hbaselines.utils.tf_util import get_trainable_vars\n')]
#!/usr/bin/env python # -*- code:utf-8 -*- ''' @Author: tyhye.wang @Date: 2018-06-16 08:05:43 @Last Modified by: tyhye.wang @Last Modified time: 2018-06-16 08:05:43 One metric object extend from the Metric. This metric is designed for person re-id retrival ''' from mxnet.metric import EvalMetric from mxnet.metric import check_label_shapes import numpy as np from tqdm import tqdm class ReID_Metric(EvalMetric): """The Metric for Re-ID evaluation. Parameters ---------- name : str Name of this metric instance for display. output_names : list of str, or None Name of predictions that should be used when updating with update_dict. By default include all predictions. label_names : list of str, or None Name of labels that should be used when updating with update_dict. By default include all labels. """ def __init__(self, isnorm=True, name='CMC&mAP', output_names=None, label_names=None): self.isnorm = isnorm self.query_features = [] self.query_labels = [] self.query_cams = [] self.gallery_features = [] self.gallery_labels = [] self.gallery_cams = [] # self._kwargs = kwargs super(ReID_Metric, self).__init__(name=name, output_names=output_names, label_names=label_names) def reset(self): """Resets the internal evaluation result to initial state.""" self.query_features.clear() self.query_labels.clear() self.query_cams.clear() self.gallery_features.clear() self.gallery_labels.clear() self.gallery_cams.clear() self.reidmetric = None def __str__(self): return "EvalMetric: {}".format(dict(self.get_name_value())) def get_config(self): """Save configurations of metric. Can be recreated from configs with metric.create(**config) """ config = self._kwargs.copy() config.update({ 'metric': self.__class__.__name__, 'name': self.name, 'output_names': self.output_names, 'label_names': self.label_names}) return config def update_dict(self, labels, features, cams, type='query'): """Update the internal evaluation with named label and pred Parameters ---------- labels : OrderedDict of str -> NDArray name to array mapping for labels. preds : OrderedDict of str -> NDArray name to array mapping of predicted outputs. """ pass # if self.output_names is not None: # pred = [pred[name] for name in self.output_names] # else: # pred = list(pred.values()) # if self.label_names is not None: # label = [label[name] for name in self.label_names] # else: # label = list(label.values()) # self.update(label, pred) def update(self, features, cams, labels, feature_type='query'): """Updates the features of the `type`. Parameters ---------- features : list of `NDArray` cams: list of `NDArray` The camids of the data. labels : list of `NDArray` The labels of the data. feature_type: str `query` or `gallery` """ self.reidmetric = None if feature_type == 'query': features_list = self.query_features cams_list = self.query_cams labels_list = self.query_labels else: features_list = self.gallery_features cams_list = self.gallery_cams labels_list = self.gallery_labels features = features.asnumpy() if self.isnorm: fnorm = np.sqrt(np.sum(features ** 2, axis=1, keepdims=True)) features = features / fnorm features_list.append(features) cams_list.append(cams.asnumpy()) labels_list.append(labels.asnumpy()) def get(self): """Gets the current evaluation result. Returns ------- names : list of str Name of the metrics. reid-metrics : CMC list & mAP Value of the evaluations. """ if self.reidmetric is not None: return (self.name, self.reidmetric) else: query_features = np.concatenate(self.query_features, axis=0) query_cams = np.concatenate(self.query_cams, axis=0) query_labels = np.concatenate(self.query_labels, axis=0) gallery_features = np.concatenate(self.gallery_features, axis=0) gallery_cams = np.concatenate(self.gallery_cams, axis=0) gallery_labels = np.concatenate(self.gallery_labels, axis=0) query_size = len(query_labels) print("Now is Calculating CMC & mAP: ") CMC = np.zeros(len(gallery_labels)).astype('int32') ap = 0.0 # distance = np.matmul(query_features, gallery_features.T) for i in tqdm(range(query_size), ncols=80): ap_tmp, CMC_tmp = evaluate_oneitem(query_features[i], query_labels[i], query_cams[i], gallery_features, gallery_labels, gallery_cams) if CMC_tmp[0] == -1: continue CMC = CMC + CMC_tmp ap += ap_tmp CMC = CMC.astype('float') CMC = CMC/query_size # average CMC mAP = ap/query_size self.reidmetric = (CMC, mAP) return (self.name, self.reidmetric) # Evaluate function def evaluate_oneitem(qf, ql, qc, gf, gl, gc): query = qf score = np.dot(gf, query) # predict index index = np.argsort(score) # from small to large index = index[::-1] #index = index[0:2000] # good index query_index = np.argwhere(gl == ql) camera_index = np.argwhere(gc == qc) good_index = np.setdiff1d(query_index, camera_index, assume_unique=True) junk_index1 = np.argwhere(gl == -1) junk_index2 = np.intersect1d(query_index, camera_index) junk_index = np.append(junk_index2, junk_index1) # .flatten()) CMC_tmp = compute_mAP_(index, good_index, junk_index) return CMC_tmp # compute map def compute_mAP_(index, good_index, junk_index): ap = 0 cmc = np.zeros(len(index)) if good_index.size == 0: # if empty cmc[0] = -1 return ap, cmc # remove junk_index mask = np.in1d(index, junk_index, invert=True) index = index[mask] # find good_index index ngood = len(good_index) mask = np.in1d(index, good_index) rows_good = np.argwhere(mask == True) rows_good = rows_good.flatten() cmc[rows_good[0]:] = 1 for i in range(ngood): d_recall = 1.0/ngood precision = (i+1)*1.0/(rows_good[i]+1) if rows_good[i] != 0: old_precision = i*1.0/rows_good[i] else: old_precision = 1.0 ap = ap + d_recall*(old_precision + precision)/2 return ap, cmc
[ "numpy.sum", "numpy.setdiff1d", "numpy.argsort", "numpy.append", "numpy.argwhere", "numpy.dot", "numpy.intersect1d", "numpy.concatenate", "numpy.in1d" ]
[((6011, 6028), 'numpy.dot', 'np.dot', (['gf', 'query'], {}), '(gf, query)\n', (6017, 6028), True, 'import numpy as np\n'), ((6061, 6078), 'numpy.argsort', 'np.argsort', (['score'], {}), '(score)\n', (6071, 6078), True, 'import numpy as np\n'), ((6188, 6209), 'numpy.argwhere', 'np.argwhere', (['(gl == ql)'], {}), '(gl == ql)\n', (6199, 6209), True, 'import numpy as np\n'), ((6229, 6250), 'numpy.argwhere', 'np.argwhere', (['(gc == qc)'], {}), '(gc == qc)\n', (6240, 6250), True, 'import numpy as np\n'), ((6268, 6327), 'numpy.setdiff1d', 'np.setdiff1d', (['query_index', 'camera_index'], {'assume_unique': '(True)'}), '(query_index, camera_index, assume_unique=True)\n', (6280, 6327), True, 'import numpy as np\n'), ((6346, 6367), 'numpy.argwhere', 'np.argwhere', (['(gl == -1)'], {}), '(gl == -1)\n', (6357, 6367), True, 'import numpy as np\n'), ((6386, 6427), 'numpy.intersect1d', 'np.intersect1d', (['query_index', 'camera_index'], {}), '(query_index, camera_index)\n', (6400, 6427), True, 'import numpy as np\n'), ((6445, 6480), 'numpy.append', 'np.append', (['junk_index2', 'junk_index1'], {}), '(junk_index2, junk_index1)\n', (6454, 6480), True, 'import numpy as np\n'), ((6801, 6840), 'numpy.in1d', 'np.in1d', (['index', 'junk_index'], {'invert': '(True)'}), '(index, junk_index, invert=True)\n', (6808, 6840), True, 'import numpy as np\n'), ((6932, 6958), 'numpy.in1d', 'np.in1d', (['index', 'good_index'], {}), '(index, good_index)\n', (6939, 6958), True, 'import numpy as np\n'), ((6975, 7000), 'numpy.argwhere', 'np.argwhere', (['(mask == True)'], {}), '(mask == True)\n', (6986, 7000), True, 'import numpy as np\n'), ((4467, 4510), 'numpy.concatenate', 'np.concatenate', (['self.query_features'], {'axis': '(0)'}), '(self.query_features, axis=0)\n', (4481, 4510), True, 'import numpy as np\n'), ((4536, 4575), 'numpy.concatenate', 'np.concatenate', (['self.query_cams'], {'axis': '(0)'}), '(self.query_cams, axis=0)\n', (4550, 4575), True, 'import numpy as np\n'), ((4603, 4644), 'numpy.concatenate', 'np.concatenate', (['self.query_labels'], {'axis': '(0)'}), '(self.query_labels, axis=0)\n', (4617, 4644), True, 'import numpy as np\n'), ((4676, 4721), 'numpy.concatenate', 'np.concatenate', (['self.gallery_features'], {'axis': '(0)'}), '(self.gallery_features, axis=0)\n', (4690, 4721), True, 'import numpy as np\n'), ((4749, 4790), 'numpy.concatenate', 'np.concatenate', (['self.gallery_cams'], {'axis': '(0)'}), '(self.gallery_cams, axis=0)\n', (4763, 4790), True, 'import numpy as np\n'), ((4820, 4863), 'numpy.concatenate', 'np.concatenate', (['self.gallery_labels'], {'axis': '(0)'}), '(self.gallery_labels, axis=0)\n', (4834, 4863), True, 'import numpy as np\n'), ((3878, 3922), 'numpy.sum', 'np.sum', (['(features ** 2)'], {'axis': '(1)', 'keepdims': '(True)'}), '(features ** 2, axis=1, keepdims=True)\n', (3884, 3922), True, 'import numpy as np\n')]
# ------------------------------------------------------------------------------------------------------------------- # Method 2 in OpenCv # ------------------------------------------------------------------------------------------------------------------- import numpy as np import cv2 as cv from PIL import Image cap = cv.VideoCapture('/Users/zhou/Desktop/data/video_clip/train/IMG_00000.MOV') fgbg = cv.createBackgroundSubtractorMOG2(varThreshold=16, detectShadows=False) # fgbg = cv.bgsegm.createBackgroundSubtractorGMG(initializationFrames=200, decisionThreshold=0.85) kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(4,4)) X = True count_frame = 0 image_origin_list =[] cv.namedWindow( 'image', cv.WINDOW_NORMAL ) cv.resizeWindow('image', 1024, 1980) while(1): ret, frame = cap.read() # print( "Processing " + str( count_frame ) + "th frame" ) count_frame = count_frame+1 fgmask = fgbg.apply(frame) if count_frame%30 ==0: # print(frame.shape) image_origin= cv.cvtColor(frame, cv.COLOR_BGR2GRAY) fgmask = cv.morphologyEx( fgmask, cv.MORPH_OPEN, kernel, iterations=2) # fgmask = np.asarray( fgmask == 255, np.uint8 ) composite = np.concatenate((image_origin, fgmask), axis=0 ) print(count_frame) cv.imshow('image', composite) if count_frame == 510: composite = Image.fromarray( composite ) composite.save(str(count_frame) + ".png") k = cv.waitKey(100000) & 0xff k = cv.waitKey(5) & 0xff if k == 27: break cap.release() cv.destroyAllWindows() # ------------------------------------------------------------------------------------------------------------------- # Method 3 in openCv # ------------------------------------------------------------------------------------------------------------------- # import numpy as np # import cv2 as cv # import matplotlib # import matplotlib.pyplot as plt # # pip3 install Pillow # import os,sys # from PIL import Image # import glob # # filelist = glob.glob('/Users/zhou/Desktop/untitled folder/') # # # filelist = 'file1.bmp', 'file2.bmp', 'file3.bmp' # # filelist = np.sort(filelist).tolist() # # frame_data = np.array([np.array(Image.open(fname)) for fname in filelist]) # # # cap = cv.VideoCapture('/Users/zhou/Desktop/untitled folder/image_%05d.png') # cap = cv.VideoCapture("/Users/zhou/Desktop/data/video_clip/train/IMG_00002.MOV") # kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(3,3)) # fgbg = cv.bgsegm.createBackgroundSubtractorGMG(initializationFrames=200, decisionThreshold=0.85) # # fgbg = cv.bgsegm.createBackgroundSubtractorGSOC() # # # fgbg = cv.bgsegm.createBackgroundSubtractorCNT() # i = 1 # # attention: dead loop # while(1): # ret, frame = cap.read() # if ret: # print("Processing "+ str(i)+"th frame") # fgmask = fgbg.apply(frame) # fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel, iterations=2) # # im = Image.fromarray(fgmask) # # im.save( "image/image" + str(i) +".png" ) # cv.imshow('frame',fgmask) # i = i + 1 # k = cv.waitKey(1) & 0xff # if k == 27: # break # cap.release() # cv.destroyAllWindows() # ------------------------------------------------------------------------------------------------------------------- # Method 1 in openCv # ---------------------------------------------------------------------------------------------------------------- # import numpy as np # import cv2 as cv # cap = cv.VideoCapture('/Users/zhou/Desktop/data/video_clip/train/IMG_00002.MOV') # fgbg = cv.bgsegm.createBackgroundSubtractorMOG(history=500) # while(1): # ret, frame = cap.read() # fgmask = fgbg.apply(frame) # cv.imshow('frame',fgmask) # k = cv.waitKey(30) & 0xff # if k == 27: # break # cap.release() # cv.destroyAllWindows()
[ "cv2.createBackgroundSubtractorMOG2", "numpy.concatenate", "cv2.cvtColor", "cv2.getStructuringElement", "cv2.morphologyEx", "cv2.waitKey", "cv2.imshow", "cv2.VideoCapture", "PIL.Image.fromarray", "cv2.resizeWindow", "cv2.destroyAllWindows", "cv2.namedWindow" ]
[((321, 395), 'cv2.VideoCapture', 'cv.VideoCapture', (['"""/Users/zhou/Desktop/data/video_clip/train/IMG_00000.MOV"""'], {}), "('/Users/zhou/Desktop/data/video_clip/train/IMG_00000.MOV')\n", (336, 395), True, 'import cv2 as cv\n'), ((403, 474), 'cv2.createBackgroundSubtractorMOG2', 'cv.createBackgroundSubtractorMOG2', ([], {'varThreshold': '(16)', 'detectShadows': '(False)'}), '(varThreshold=16, detectShadows=False)\n', (436, 474), True, 'import cv2 as cv\n'), ((583, 633), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_ELLIPSE', '(4, 4)'], {}), '(cv.MORPH_ELLIPSE, (4, 4))\n', (607, 633), True, 'import cv2 as cv\n'), ((681, 722), 'cv2.namedWindow', 'cv.namedWindow', (['"""image"""', 'cv.WINDOW_NORMAL'], {}), "('image', cv.WINDOW_NORMAL)\n", (695, 722), True, 'import cv2 as cv\n'), ((725, 761), 'cv2.resizeWindow', 'cv.resizeWindow', (['"""image"""', '(1024)', '(1980)'], {}), "('image', 1024, 1980)\n", (740, 761), True, 'import cv2 as cv\n'), ((1576, 1598), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (1596, 1598), True, 'import cv2 as cv\n'), ((1002, 1039), 'cv2.cvtColor', 'cv.cvtColor', (['frame', 'cv.COLOR_BGR2GRAY'], {}), '(frame, cv.COLOR_BGR2GRAY)\n', (1013, 1039), True, 'import cv2 as cv\n'), ((1057, 1117), 'cv2.morphologyEx', 'cv.morphologyEx', (['fgmask', 'cv.MORPH_OPEN', 'kernel'], {'iterations': '(2)'}), '(fgmask, cv.MORPH_OPEN, kernel, iterations=2)\n', (1072, 1117), True, 'import cv2 as cv\n'), ((1196, 1242), 'numpy.concatenate', 'np.concatenate', (['(image_origin, fgmask)'], {'axis': '(0)'}), '((image_origin, fgmask), axis=0)\n', (1210, 1242), True, 'import numpy as np\n'), ((1281, 1310), 'cv2.imshow', 'cv.imshow', (['"""image"""', 'composite'], {}), "('image', composite)\n", (1290, 1310), True, 'import cv2 as cv\n'), ((1366, 1392), 'PIL.Image.fromarray', 'Image.fromarray', (['composite'], {}), '(composite)\n', (1381, 1392), False, 'from PIL import Image\n'), ((1503, 1516), 'cv2.waitKey', 'cv.waitKey', (['(5)'], {}), '(5)\n', (1513, 1516), True, 'import cv2 as cv\n'), ((1465, 1483), 'cv2.waitKey', 'cv.waitKey', (['(100000)'], {}), '(100000)\n', (1475, 1483), True, 'import cv2 as cv\n')]
import os import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne import find_events, Epochs, compute_covariance, make_ad_hoc_cov from mne.datasets import sample from mne.simulation import (simulate_sparse_stc, simulate_raw, add_noise, add_ecg, add_eog) # sfreq=300 # duration=300 def data_fun(times, amplitude=1, freq=10): """Generate sinusoidal data at amplitude (in nAm)""" data = amplitude * 1e-9 * np.sin(2. * np.pi * freq * times) return data from functools import partial def generate_combined_simulation(raw_fname, fwd, subject=None, subjects_dir=None, topdir=None, label_index=None, sine_amplitude=None, sine_frequency=None): """Create a combined dataset of simulated plus real data and save to the topdir/(subjid)_(AMP)_nAm_(HZ)_hz folder""" os.chdir(topdir) if label_index==None: print('Must provide a label index for simulation') exit(1) raw = mne.io.read_raw_fif(raw_fname) rng = np.random.RandomState(0) # random state (make reproducible) #Labels for simulation labels = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir ) labels_sim = [labels[label_index]] times = raw.times #[:int(raw.info['sfreq'] * epoch_duration)] src = fwd['src'] sig_generator = partial(data_fun, amplitude=sine_amplitude, freq=sine_frequency) stc = simulate_sparse_stc(src, n_dipoles=1, times=times, data_fun=sig_generator, labels=labels_sim, location='center', subjects_dir=subjects_dir) # Simulate raw data raw_sim = simulate_raw(raw.info, [stc] * 1, forward=fwd, verbose=True) #Load raw and save to outfolder raw.load_data() #Combine simulation w/raw comb_out_fname='{}_{}_label_{}_nAm_{}_hz_meg.fif'.format(subject, str(label_index), sine_amplitude, sine_frequency) # comb_out_fname = op.join(outfolder, outfolder+'_meg.fif') combined = raw.copy() combined._data += raw_sim.get_data() combined.save(comb_out_fname) print('Saved {}'.format(comb_out_fname)) #Save stc for later use stc_out_fname = op.join('{}_{}_label_{}_nAm_{}_hz-stc.fif'.format(subject, str(label_index), sine_amplitude, sine_frequency)) stc.save(stc_out_fname) @pytest.mark.sim def test_iterate_elekta_simulations(): from enigmeg.test_data.get_test_data import datasets topdir='/home/stoutjd/data/NEWTEST' #For elekta data elekta_dat = datasets().elekta subject = 'sub-CC320342' #elekta_dat['subject'] subjects_dir = '/data/CAMCAN/SUBJECTS_DIR' #elekta_dat['SUBJECTS_DIR'] raw_fname = elekta_dat['meg_rest'] eroom_fname = elekta_dat['meg_eroom'] trans_fname = elekta_dat['trans'] src_fname = elekta_dat['src'] bem_fname = elekta_dat['bem'] input_dir = elekta_dat['enigma_outputs'] raw=mne.io.read_raw_fif(raw_fname) fwd = mne.forward.make_forward_solution(raw.info, trans_fname, src_fname, bem_fname) import itertools amp_vals=np.arange(10, 100, 10) freq_vals=np.arange(5, 20, 5) label_index = np.arange(0,68) #For DK atlas amp_freq_label = itertools.product(amp_vals, freq_vals, label_index) output_dir = op.join(topdir, subject) if not op.exists(output_dir): os.mkdir(output_dir) #Load raw and save to outfolder raw.load_data() raw.resample(300) raw_out_fname = op.join(output_dir, '{}_raw_meg.fif'.format(subject)) raw.save(raw_out_fname, overwrite=True) for amp,freq,label_idx in amp_freq_label: generate_combined_simulation(raw_out_fname, fwd, subject=subject, subjects_dir=subjects_dir, topdir=output_dir, label_index=label_idx, sine_amplitude=amp, sine_frequency=freq)
[ "functools.partial", "os.mkdir", "mne.io.read_raw_fif", "os.path.join", "mne.read_labels_from_annot", "os.path.exists", "numpy.random.RandomState", "mne.simulation.simulate_raw", "numpy.arange", "numpy.sin", "itertools.product", "mne.forward.make_forward_solution", "mne.simulation.simulate_sparse_stc", "os.chdir", "enigmeg.test_data.get_test_data.datasets" ]
[((1084, 1100), 'os.chdir', 'os.chdir', (['topdir'], {}), '(topdir)\n', (1092, 1100), False, 'import os\n'), ((1217, 1247), 'mne.io.read_raw_fif', 'mne.io.read_raw_fif', (['raw_fname'], {}), '(raw_fname)\n', (1236, 1247), False, 'import mne\n'), ((1258, 1282), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (1279, 1282), True, 'import numpy as np\n'), ((1364, 1426), 'mne.read_labels_from_annot', 'mne.read_labels_from_annot', (['subject'], {'subjects_dir': 'subjects_dir'}), '(subject, subjects_dir=subjects_dir)\n', (1390, 1426), False, 'import mne\n'), ((1580, 1644), 'functools.partial', 'partial', (['data_fun'], {'amplitude': 'sine_amplitude', 'freq': 'sine_frequency'}), '(data_fun, amplitude=sine_amplitude, freq=sine_frequency)\n', (1587, 1644), False, 'from functools import partial\n'), ((1693, 1836), 'mne.simulation.simulate_sparse_stc', 'simulate_sparse_stc', (['src'], {'n_dipoles': '(1)', 'times': 'times', 'data_fun': 'sig_generator', 'labels': 'labels_sim', 'location': '"""center"""', 'subjects_dir': 'subjects_dir'}), "(src, n_dipoles=1, times=times, data_fun=sig_generator,\n labels=labels_sim, location='center', subjects_dir=subjects_dir)\n", (1712, 1836), False, 'from mne.simulation import simulate_sparse_stc, simulate_raw, add_noise, add_ecg, add_eog\n'), ((1939, 1999), 'mne.simulation.simulate_raw', 'simulate_raw', (['raw.info', '([stc] * 1)'], {'forward': 'fwd', 'verbose': '(True)'}), '(raw.info, [stc] * 1, forward=fwd, verbose=True)\n', (1951, 1999), False, 'from mne.simulation import simulate_sparse_stc, simulate_raw, add_noise, add_ecg, add_eog\n'), ((3582, 3612), 'mne.io.read_raw_fif', 'mne.io.read_raw_fif', (['raw_fname'], {}), '(raw_fname)\n', (3601, 3612), False, 'import mne\n'), ((3623, 3701), 'mne.forward.make_forward_solution', 'mne.forward.make_forward_solution', (['raw.info', 'trans_fname', 'src_fname', 'bem_fname'], {}), '(raw.info, trans_fname, src_fname, bem_fname)\n', (3656, 3701), False, 'import mne\n'), ((3786, 3808), 'numpy.arange', 'np.arange', (['(10)', '(100)', '(10)'], {}), '(10, 100, 10)\n', (3795, 3808), True, 'import numpy as np\n'), ((3824, 3843), 'numpy.arange', 'np.arange', (['(5)', '(20)', '(5)'], {}), '(5, 20, 5)\n', (3833, 3843), True, 'import numpy as np\n'), ((3863, 3879), 'numpy.arange', 'np.arange', (['(0)', '(68)'], {}), '(0, 68)\n', (3872, 3879), True, 'import numpy as np\n'), ((3919, 3970), 'itertools.product', 'itertools.product', (['amp_vals', 'freq_vals', 'label_index'], {}), '(amp_vals, freq_vals, label_index)\n', (3936, 3970), False, 'import itertools\n'), ((3993, 4017), 'os.path.join', 'op.join', (['topdir', 'subject'], {}), '(topdir, subject)\n', (4000, 4017), True, 'import os.path as op\n'), ((480, 514), 'numpy.sin', 'np.sin', (['(2.0 * np.pi * freq * times)'], {}), '(2.0 * np.pi * freq * times)\n', (486, 514), True, 'import numpy as np\n'), ((3186, 3196), 'enigmeg.test_data.get_test_data.datasets', 'datasets', ([], {}), '()\n', (3194, 3196), False, 'from enigmeg.test_data.get_test_data import datasets\n'), ((4029, 4050), 'os.path.exists', 'op.exists', (['output_dir'], {}), '(output_dir)\n', (4038, 4050), True, 'import os.path as op\n'), ((4060, 4080), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (4068, 4080), False, 'import os\n')]
import unittest import numpy as np import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from config import OptimizationConfigEuRoC from utils import to_quaternion, to_rotation, Isometry3d from feature import Feature from msckf import CAMState class TestFeature(unittest.TestCase): def test_feature_initialization(self): """ Test feature initialization. """ optimization_config = OptimizationConfigEuRoC() Feature.R_cam0_cam1 = np.identity(3) Feature.t_cam0_cam1 = np.zeros(3) # feature = np.array([0.5, 0., 0.]) feature = np.random.random(3) * 0.5 # Add 6 camera poses, all of which are able to see the # feature at the origin. For simplicity, the six camera # view are located at the six intersections between a # unit sphere and the coordinate system. And the z axes # of the camera frames are facing the origin. cam_poses = [ Isometry3d(np.array([ [0., 0., -1.], [1., 0., 0.], [0., -1., 0.]] ), np.array([1., 0., 0.])), Isometry3d(np.array([ [-1., 0., 0.], [0., 0., -1.], [0., -1., 0.]] ), np.array([0., 1., 0.])), Isometry3d(np.array([ [0., 0., 1.], [-1., 0., 0.], [0., -1., 0.]] ), np.array([-1., 0., 0.])), Isometry3d(np.array([ [1., 0., 0.], [0., 0., 1.], [0., -1., 0.]] ), np.array([0., -1., 0.])), Isometry3d(np.array([ [0., -1., 0.], [-1., 0., 0.], [0., 0., -1.]] ), np.array([0., 0., 1.])), Isometry3d(np.array([ [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] ), np.array([0., 0., -1.])), ] # Set the camera states cam_states = dict() for i in range(6): cam_state = CAMState(i) cam_state.timestamp = i cam_state.orientation = cam_poses[i].R cam_state.position = cam_poses[i].t cam_states[i] = cam_state # Compute measurements. measurements = [] for i in range(6): cam_pose_inv = cam_poses[i].inverse() p = cam_pose_inv.R @ feature + cam_pose_inv.t u, v = p[:2] / p[2] + np.random.randn(2) * 0.01 measurements.append(np.array([u, v, u, v])) # Initialize a feature object. feature_object = Feature(0, optimization_config=optimization_config) for i in range(6): feature_object.observations[i] = measurements[i] # Compute the 3d position of the feature. status = feature_object.initialize_position(cam_states) # Check the difference between the computed 3d # feature position and the groud truth. print('status:', status) print('ground truth position:\n', feature) print('estimated position:\n', feature_object.position) e = np.linalg.norm(feature - feature_object.position) print('error norm:', e) self.assertTrue(e < 0.05) if __name__ == '__main__': unittest.main()
[ "unittest.main", "msckf.CAMState", "numpy.random.randn", "config.OptimizationConfigEuRoC", "os.path.dirname", "numpy.zeros", "numpy.identity", "numpy.random.random", "numpy.linalg.norm", "numpy.array", "feature.Feature" ]
[((3433, 3448), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3446, 3448), False, 'import unittest\n'), ((91, 116), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (106, 116), False, 'import os\n'), ((470, 495), 'config.OptimizationConfigEuRoC', 'OptimizationConfigEuRoC', ([], {}), '()\n', (493, 495), False, 'from config import OptimizationConfigEuRoC\n'), ((527, 541), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (538, 541), True, 'import numpy as np\n'), ((573, 584), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (581, 584), True, 'import numpy as np\n'), ((2745, 2796), 'feature.Feature', 'Feature', (['(0)'], {'optimization_config': 'optimization_config'}), '(0, optimization_config=optimization_config)\n', (2752, 2796), False, 'from feature import Feature\n'), ((3276, 3325), 'numpy.linalg.norm', 'np.linalg.norm', (['(feature - feature_object.position)'], {}), '(feature - feature_object.position)\n', (3290, 3325), True, 'import numpy as np\n'), ((651, 670), 'numpy.random.random', 'np.random.random', (['(3)'], {}), '(3)\n', (667, 670), True, 'import numpy as np\n'), ((2170, 2181), 'msckf.CAMState', 'CAMState', (['i'], {}), '(i)\n', (2178, 2181), False, 'from msckf import CAMState\n'), ((1038, 1101), 'numpy.array', 'np.array', (['[[0.0, 0.0, -1.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]'], {}), '([[0.0, 0.0, -1.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]])\n', (1046, 1101), True, 'import numpy as np\n'), ((1160, 1185), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (1168, 1185), True, 'import numpy as np\n'), ((1209, 1273), 'numpy.array', 'np.array', (['[[-1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, -1.0, 0.0]]'], {}), '([[-1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, -1.0, 0.0]])\n', (1217, 1273), True, 'import numpy as np\n'), ((1332, 1357), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (1340, 1357), True, 'import numpy as np\n'), ((1381, 1444), 'numpy.array', 'np.array', (['[[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]'], {}), '([[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]])\n', (1389, 1444), True, 'import numpy as np\n'), ((1503, 1529), 'numpy.array', 'np.array', (['[-1.0, 0.0, 0.0]'], {}), '([-1.0, 0.0, 0.0])\n', (1511, 1529), True, 'import numpy as np\n'), ((1553, 1615), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]]'], {}), '([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]])\n', (1561, 1615), True, 'import numpy as np\n'), ((1674, 1700), 'numpy.array', 'np.array', (['[0.0, -1.0, 0.0]'], {}), '([0.0, -1.0, 0.0])\n', (1682, 1700), True, 'import numpy as np\n'), ((1724, 1788), 'numpy.array', 'np.array', (['[[0.0, -1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, -1.0]]'], {}), '([[0.0, -1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, -1.0]])\n', (1732, 1788), True, 'import numpy as np\n'), ((1847, 1872), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (1855, 1872), True, 'import numpy as np\n'), ((1896, 1957), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]'], {}), '([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])\n', (1904, 1957), True, 'import numpy as np\n'), ((2016, 2042), 'numpy.array', 'np.array', (['[0.0, 0.0, -1.0]'], {}), '([0.0, 0.0, -1.0])\n', (2024, 2042), True, 'import numpy as np\n'), ((2653, 2675), 'numpy.array', 'np.array', (['[u, v, u, v]'], {}), '([u, v, u, v])\n', (2661, 2675), True, 'import numpy as np\n'), ((2594, 2612), 'numpy.random.randn', 'np.random.randn', (['(2)'], {}), '(2)\n', (2609, 2612), True, 'import numpy as np\n')]
#! /usr/bin/python3 import sys from lxml import etree as ET import xml.etree.cElementTree as ET import pdb import random import logging import xml.dom.minidom import argparse import os import datetime import requests import csv import sqlite3 from xml.dom import minidom from copy import deepcopy from collections import namedtuple from collections import defaultdict from collections import OrderedDict from os import walk import numpy as np import scipy from scipy.spatial import distance import math import matplotlib.pyplot as plt import matplotlib.patches as patches import pandas from mpl_toolkits.mplot3d import Axes3D from sklearn.manifold import TSNE from PIL import Image from pathlib import Path g_x = 0 g_y = 1 g_unused = 2 g_small_img = 3 g_verbosity = 0 g_filetype = '' g_stats_zero = [] g_stats_many = [] g_objs_zero = [] g_objs_many = [] g_multi_ok = False g_argv = '' g_exec_name = 'bearID v0.1' g_box_attrs = {'height', 'left', 'top', 'width'} g_shape_parts_head = {'htop', 'head_top', 'top'} g_shape_parts_face = {'lear', 'leye', 'nose', 'rear', 'reye'} g_shape_parts_find = {'lear', 'leye', 'nose', 'rear', 'reye', 'htop', 'head_top'} g_shape_parts = {'lear', 'leye', 'nose', 'rear', 'reye', 'head_top'} all_labels = [] bc_labels=[ 'bc_adeane', 'bc_also', 'bc_amber', 'bc_aurora', 'bc_beatrice', 'bc_bella', 'bc_bellanore', 'bc_bracket', 'bc_bruno', 'bc_caramel', 'bc_chestnut', 'bc_cleo', 'bc_clyde', 'bc_coco', 'bc_cross-paw', 'bc_dani-bear', 'bc_diablo', 'bc_fisher', 'bc_flora', 'bc_frank', 'bc_freckles', 'bc_freda', 'bc_freya', 'bc_gary', 'bc_gc', 'bc_glory', 'bc_hoeya', 'bc_jaque', 'bc_kiokh', 'bc_kwatse', 'bc_lenore', 'bc_lillian', 'bc_lil-willy', 'bc_lucky', 'bc_matsui', 'bc_millerd', 'bc_mouse', 'bc_neana', 'bc_no-tail', 'bc_old-girl', 'bc_oso', 'bc_peanut', 'bc_pete', 'bc_pirate', 'bc_pretty-boy', 'bc_river', 'bc_sallie', 'bc_santa', 'bc_shaniqua', 'bc_simoom', 'bc_stella', 'bc_steve', 'bc_teddy-blonde', 'bc_teddy-brown', 'bc_toffee', 'bc_topaz', 'bc_trouble', 'bc_tuna', 'bc_ursa', 'kb_bc_m034' ] bf_labels = [ 'bf_032', 'bf_039', 'bf_045', 'bf_051', 'bf_068', 'bf_083', 'bf_089', 'bf_093', 'bf_094', 'bf_128', 'bf_130', 'bf_132', 'bf_151', 'bf_153', 'bf_171', 'bf_201', 'bf_218', 'bf_261', 'bf_263', 'bf_273', 'bf_274', 'bf_284', 'bf_289', 'bf_293', 'bf_294', 'bf_401', 'bf_402', 'bf_409', 'bf_410', 'bf_415', 'bf_425', 'bf_435', 'bf_451', 'bf_461', 'bf_469', 'bf_474', 'bf_477', 'bf_480', 'bf_482', 'bf_489', 'bf_500', 'bf_503', 'bf_504', 'bf_505', 'bf_510', 'bf_511', 'bf_600', 'bf_602', 'bf_603', 'bf_604', 'bf_610', 'bf_611', 'bf_613', 'bf_614', 'bf_615', 'bf_634', 'bf_700', 'bf_708', 'bf_717', 'bf_718', 'bf_719', 'bf_720', 'bf_744', 'bf_747', 'bf_755', 'bf_775', 'bf_813', 'bf_814', 'bf_818', 'bf_854', 'bf_856', 'bf_868', 'bf_879' ] all_labels = bc_labels + bf_labels coco_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] coco_classes = ["person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"] md_ids = [1, 2, 3] md_classes = ['animal', 'person', 'vehicle'] object_classes_d = defaultdict () ##------------------------------------------------------------ ## add indentations to xml content for readability ##------------------------------------------------------------ def prettify(elem) : # pdb.set_trace () rough_string = ET.tostring(elem, 'utf-8') reparsed = xml.dom.minidom.parseString(rough_string) pretty_print = '\n'.join( [line for line in reparsed.toprettyxml(indent=' '*2).split('\n') if line.strip()]) return pretty_print ##------------------------------------------------------------ ## add indentations ##------------------------------------------------------------ def indent(elem, level=0): i = "\n" + level*" " j = "\n" + (level-1)*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: indent(subelem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = j else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = j return elem ##------------------------------------------------------------ ## set global multi faces per image state ##------------------------------------------------------------ def set_multi_ok (state) : global g_multi_ok g_multi_ok = state ##------------------------------------------------------------ ## set global multi faces per image state ##------------------------------------------------------------ def get_multi_ok () : return g_multi_ok ##------------------------------------------------------------ ## set global verbosity ##------------------------------------------------------------ def set_verbosity (verbosity) : global g_verbosity g_verbosity = verbosity ##------------------------------------------------------------ ## get global verbosity ##------------------------------------------------------------ def get_verbosity () : return g_verbosity ##------------------------------------------------------------ ## set global filetype ##------------------------------------------------------------ def set_filetype (filetype) : global g_filetype g_filetype = filetype ##------------------------------------------------------------ ## get global filtype ##------------------------------------------------------------ def get_filetype () : return g_filetype ##------------------------------------------------------------ ## set global exec name ##------------------------------------------------------------ def set_exec_name (exec_name) : global g_exec_name g_exec_name = exec_name ##------------------------------------------------------------ ## get global filtype ##------------------------------------------------------------ def get_exec_name () : return g_exec_name ##------------------------------------------------------------ ## append to g_stats_zero ##------------------------------------------------------------ def g_stats_zero_append (filename) : global g_stats_zero g_stats_zero.append (filename) ##------------------------------------------------------------ ## append to g_objs_zero ##------------------------------------------------------------ def g_objs_zero_append (filename) : global g_objs_zero g_objs_zero.append (filename) ##------------------------------------------------------------ ## append to g_stats_many ##------------------------------------------------------------ def g_stats_many_append (filename) : global g_stats_many g_stats_many.append (filename) ##------------------------------------------------------------ ## append to g_objs_many ##------------------------------------------------------------ def g_objs_many_append (obj) : global g_objs_many g_objs_many.append (obj) ##------------------------------------------------------------ ##------------------------------------------------------------ def set_argv (argv) : global g_argv g_argv = ' '.join (argv) ##------------------------------------------------------------ ##------------------------------------------------------------ def get_argv () : return g_argv ##------------------------------------------------------------------------ # return count of specified pathed element from tree node # example of counting labels: # count_elem (root, "images image box label") ##------------------------------------------------------------------------ def count_elem (node, child_elem): count=0 elems = child_elem.split () if (len (elems) == 1): children = node.findall (child_elem) return len (children) # get the next child down, recurse elems = child_elem.split (' ', 1) for child in node.findall (elems[0]): count += count_elem (child, elems[1]) return count #--------------------------------------------------------------------------- # return count of faces/boxes in xml #--------------------------------------------------------------------------- def count_faces (faces_xml): tree = ET.parse (faces_xml) root = tree.getroot() count = count_elem (root, "images image box") return count #--------------------------------------------------------------------------- # insert element label to "images image box" with specified string #--------------------------------------------------------------------------- def add_box_label (tree, label_str): label_count=0 for images in tree.findall ('images'): for image in images.findall ('image'): for box in image.findall ('box'): curLabel = box.findall ('label') if len(curLabel) > 0: print(image.text + " has existing label of " + curLabel.text) continue label = ET.SubElement (box, 'label') # pdb.set_trace () label.text = label_str; label_count += 1 # print "added label" return label_count ##------------------------------------------------------------ ## read in image and determine ratio to scale to max values. ## return ratio ##------------------------------------------------------------ def get_downscale_ratio (imgfile, max_long, max_short) : img = Image.open (imgfile) w, h = img.size ratio = 1 if w * h < max_long * max_short : return ratio if w > h : if (max_long / w) < (max_short / h) : ratio = max_long / w else : ratio = max_short / h else : if (max_long / h) < (max_short / w) : ratio = max_long / h else : ratio = max_short / w return math.sqrt (ratio) ##------------------------------------------------------------ ## read in image and determine ratio to scale to max area. ## return ratio ##------------------------------------------------------------ def get_downscale_ratio (imgfile, max_area) : img = Image.open (imgfile) w, h = img.size img_size = w * h ratio = max_area / img_size # print ('orig size: ', img_size, ' ratio: ', ratio) if ratio > 1 : ratio = 1 return math.sqrt (ratio) ##------------------------------------------------------------ ## ## ##------------------------------------------------------------ def get_faces_boundary (image_tag) : max_left = 0 max_right = 0 max_top = 0 max_bottom = 0 for box in image_tag.findall ('box') : left = int (box.attrib.get ('left')) top = int (box.attrib.get ('head_top')) height = int (box.attrib.get ('height')) width = int (box.attrib.get ('width')) right = left + width bottom = top + height if left > max_left : max_left = left if right > max_right : max_right = right if top > max_top : max_top = top if bottom > max_bottom : max_bottom = bottom return max_left, max_top, max_right, max_bottom ##------------------------------------------------------------ ## crop image to max size or min of faces ## return new image ##------------------------------------------------------------ def crop_image (img, image_tag, max_x, max_y) : w, h = img.size # print ('in crop function: orig w x h ', w, h, '\n') if w * h < max_x * max_y : print (' -- no cropping') return img if w < h : print ('swapped x & y') tmp_x = max_x max_x = max_y max_y = tmp_x new_origin_x = 0 new_origin_y = 0 left, top, right, bottom = get_faces_boundary (image_tag) # print ('face boundary: ', left, top, right, bottom) faces_width = right - left faces_height = bottom - top if faces_width > max_x : ## faces larger than max image! max_x = faces_width if faces_height > max_y : ## faces height larger than max image! max_y = faces_height # doing proportion crop # pdb.set_trace () new_cropped_left = int (left / w * max_y) # new left after crop new_cropped_top = int (top / h * max_x) # new left after crop new_origin_left = left - new_cropped_left new_origin_top = top - new_cropped_top # print ('new origin (left,top): ', new_origin_left, new_origin_top) # print ('cropping to (l,t,r,b) :', new_origin_left, new_origin_top, new_origin_left+max_y, new_origin_top+max_x) cropped_img = img.crop ((new_origin_left, new_origin_top, new_origin_left+max_y, new_origin_top+max_x)) pan_boxes (image_tag, new_origin_left, new_origin_top) return cropped_img ##------------------------------------------------------------ ## downscale image by ratio ## return new image ##------------------------------------------------------------ def downscale_image (imgfile, ratio) : img = Image.open (imgfile) w, h = img.size new_w = int (w*ratio) new_h = int (h*ratio) resized_img = img.resize ((new_w, new_h)) return resized_img ##------------------------------------------------------------ ## downscale image and boxes by ratio ## return new image ##------------------------------------------------------------ def downscale_image_and_boxes (imgfile, image_tag, ratio) : resized_img = downscale_image (imgfile, ratio) for box_tag in image_tag.findall ('box') : scale_box (box_tag, ratio) return resized_img ##------------------------------------------------------------ ## return largest of any dimension of face ##------------------------------------------------------------ def get_min_img_face_size (image_tag) : min_face_size = 2000 for box_tag in image_tag.findall ('box') : for attrib in ('height', 'width') : val = box_tag.attrib.get (attrib) if val != None : val = int (val) if val < min_face_size : min_face_size = val else : print ('attrib ', attrib, 'not found') return min_face_size ##------------------------------------------------------------ ##------------------------------------------------------------ ##------------------------------------------------------------ ## scales attributes in box using ratio ## modifies: box (height, width, top, left), box.part (x, y) ##------------------------------------------------------------ def scale_box (box, pxRatio) : found_head = False for attrib in g_box_attrs: val = box.attrib.get (attrib) if val != None : val = int (val) box.set (attrib, str (int (val * pxRatio))) else : print ('attrib ', attrib, 'not found') for part in box.findall ('./part') : for attrib in ('x', 'y') : val = part.attrib.get (attrib) if val != None : val = int (val) part.set (attrib, str (int (val * pxRatio))) else : print ('attrib ', attrib, 'not found') ##------------------------------------------------------------ ## scales attributes in box using ratio ## modifies: box (height, width, top, left), box.part (x, y) ##------------------------------------------------------------ def pan_boxes (image_tag, new_origin_left, new_origin_top) : for box in image_tag.findall ('box') : val = box.attrib.get ('head_top') if val != None : val = int (val) box.set ('head_top', str (int (val - new_origin_top))) else : print ('attrib ', 'head_top', ' not found') val = box.attrib.get ('left') if val != None : val = int (val) box.set ('left', str (int (val - new_origin_left))) else : print ('attrib ', 'left', ' not found') for part in box.findall ('./part') : val = part.attrib.get ('x') if val != None : val = int (val) part.set ('x', str (int (val - new_origin_left ))) else : print ('attrib ', 'x', ' not found') val = part.attrib.get ('y') if val != None : val = int (val) part.set ('y', str (int (val - new_origin_top ))) else : print ('attrib ', 'y', ' not found') ##------------------------------------------------------------ # for each image in file if larger than max_dimension # - downscale to max_dimension or min_face_size # - if downscale to min_face_size, crop to max_dimension # - write image to parallel directory # (imageSource ->imageSourceSmall) # - write out xml with new info ##------------------------------------------------------------ def resize_face_file (orig_file, max_x=1500, max_y=2000, min_face_size=180) : root, tree = load_file (orig_file) print ('\n... processing file : ', orig_file) for image_tag in root.findall ('./images/image'): imgfile = image_tag.attrib.get ('file') ratio_downscale = get_downscale_ratio (imgfile, max_x, max_y) min_img_face_size = get_min_img_face_size (image_tag) ratio_min_face = min_face_size / min_img_face_size print ('..... resizing ', imgfile) print ('\tface size: ', min_img_face_size) #-test if min_img_face_size < 150 : print ('\tface less than 150.') elif min_img_face_size < 224 : print ('\tface less than 224.') # print ('ratio_min_face: ', ratio_min_face, '\n') #-test # print ('ratio_downscale: ', ratio_downscale, '\n') #-test if ratio_min_face > 1 : # orig face smaller than min, don't downscale resized_image = Image.open (imgfile) # print ('no scaling \n') #-test elif ratio_downscale > ratio_min_face : # larger ratio == less downscaling resized_image = downscale_image_and_boxes (imgfile, image_tag, ratio_downscale) # print ('scaling by image\n') #-test else : resized_image = downscale_image_and_boxes (imgfile, image_tag, ratio_min_face) # print ('scaling by min face\n') #-test resized_image = crop_image (resized_image, image_tag, max_x, max_y) new_imgfile = imgfile.replace ('imageSource', 'imageSourceSmall') new_imgfile_dir = os.path.dirname (new_imgfile) if not os.path.isdir (new_imgfile_dir) : os.makedirs (new_imgfile_dir) # imgfile_base, imgfile_ext = os.path.splitext (os.path.basename (imgfile)) #-test # new_imgfile = imgfile_base + '_resize' + imgfile_ext #-test # pdb.set_trace () resized_image.save (new_imgfile) print ('\t... writing image to : ', new_imgfile) image_tag.set ('file', new_imgfile) # fix xml image_tag filebase, fileext = os.path.splitext (orig_file) new_file = filebase + '_resize' + fileext print("\n... writing new face xml : ", new_file, "\n\n") indent (root) # pdb.set_trace () tree.write (new_file) return ##------------------------------------------------------------ # for each image in file, if larger than 1500 by 2000, # - downscale image and face info # - write image to parallel directory # - write out xml with new info ##------------------------------------------------------------ def downscale_face_file (orig_file, max_size, path_replace) : root, tree = load_file (orig_file) ET.SubElement (root, 'command').text = get_argv () print ('\n... downscaling : ', orig_file, ' to ', max_size, '\n') for image_tag in root.findall ('./images/image'): # get file and downscale imgfile = image_tag.attrib.get ('file') ratio = get_downscale_ratio (imgfile, max_size) downscaled_image = downscale_image_and_boxes (imgfile, image_tag, ratio) if path_replace[0] == '' : new_imgfile = './' + imgfile else : new_imgfile = imgfile.replace (path_replace[0], path_replace[1]) new_imgfile_dir = os.path.dirname (new_imgfile) if not os.path.isdir (new_imgfile_dir) : os.makedirs (new_imgfile_dir) print ('\t... writing new image to: ', new_imgfile, '\n') downscaled_image.save (new_imgfile) image_tag.set ('file', new_imgfile) # fix xml image_tag filebase, fileext = os.path.splitext (orig_file) new_file = filebase + '_tiny' + fileext print("\n\t... writing new face xml : ", new_file, "\n\n") indent (root) # pdb.set_trace () tree.write (new_file) return #--------------------------------------------------------------------------- # load file, return root #--------------------------------------------------------------------------- def load_file (file): tree = ET.parse (file) root = tree.getroot() return root, tree ##------------------------------------------------------------ ## load xml into dictionary of <string><element_list> ## ex: d["b-032"] = ["<Element 'chip' at 0x123,..,<Element 'chip' at 0x43] ## d["b-747"] = ["<Element 'chip' at 0x987,..,<Element 'chip' at 0x65] ## returns list of filenames. if filename_type == 'source', return ## chip source filenames ##------------------------------------------------------------ def load_objs (root, d_objs, filetype, filename_type='file') : ## print "loading chips" obj_filenames = [] if filetype == 'chips' : for chip in root.findall ('./chips/chip'): label_list = chip.findall ('label') filename = chip.attrib.get ('file') if len (label_list) < 1 : g_stats_zero_append (filename) print("no labels: ", label_list) continue if len (label_list) > 1 : g_stats_many_append (filename) print("too many labels: ", label_list) continue label = label_list[0].text if filename_type == 'source' : source_filename = get_chip_source_file (chip) obj_filenames.append (source_filename) else : obj_filenames.append (filename) d_objs[label].append(chip) elif filetype == 'images' : # pdb.set_trace () label = '' for image in root.findall ('./images/image'): facefile = image.attrib.get ('file') obj_filenames.append (facefile) d_objs[label].append(image) elif filetype == 'faces' : # pdb.set_trace () multi_faces = defaultdict(lambda:0) for image in root.findall ('./images/image'): box = image.findall ('box') facefile = image.attrib.get ('file') multi_faces[len(box)] += 1 if g_multi_ok is False : if len (box) == 0 : g_stats_zero_append (facefile) g_objs_zero_append (image) continue if len (box) > 1 : g_stats_many_append (facefile) g_objs_many_append (image) print ("Warning:", len (box), "boxes (faces) in file ", facefile) continue label_list = box[0].findall ('label') if len (label_list) == 0: pdb.set_trace () print ('Warning: file', facefile, 'is missing image label') continue label = label_list[0].text obj_filenames.append (facefile) d_objs[label].append(image) if get_verbosity () > 1 : print ('\nface count:') for key,val in multi_faces.items(): print ('\t',key, ':', val) elif filetype == 'pairs' : matched = 0 unmatched = 1 matched_cnt = 0 unmatched_cnt = 0 # pdb.set_trace () for pair in root.findall ('./pairs/pair_matched'): labels = pair.findall ('./chip/label') if len (labels) != 2 : print('Error: expecting only 2 chips in pair, got: ', labels) continue if labels[0].text != labels[1].text : print('error: labels should match: ', labels) matched_cnt += 1 d_objs[matched].append(labels[0]) obj_filenames.append (d_objs[matched]) for pair in root.findall ('./pairs/pair_unmatched'): labels = pair.findall ('./chip/label') if len (labels) != 2 : print('Error: expecting only 2 chips in pair, got: ', labels) continue if labels[0].text == labels[1].text : print('Error: labels should not match: ', labels) unmatched_cnt += 1 d_objs[unmatched].append(labels) obj_filenames.append (d_objs[unmatched]) elif filetype == 'embeddings' : for embedding in root.findall ('./embeddings/embedding'): label = embedding.find ('./label') # pdb.set_trace () embed_val = embedding.find ('./embed_val') vals_str = embed_val.text.split () embed_floats = [float (i) for i in vals_str] d_objs[label.text].append(embed_floats) elif filetype == 'embeds' : for embedding in root.findall ('./embeddings/embedding'): label = embedding.find ('./label') # pdb.set_trace () d_objs[label.text].append(embedding) else : print('Error: unknown filetype. Expected one of "faces", "chips", "embeddings", "embeds" or "pairs".') # pdb.set_trace () return obj_filenames ##------------------------------------------------------------ ## print closest n labels from dict ## x = sorted(d.items(), key=lambda x: x[1]) ## for dict of distances, return closest n labels ##------------------------------------------------------------ def print_nearest (e_dist_d, n) : sorted_e = sorted(e_dist_d.items(), key=lambda x: x[1]) nearests = [] for i in range (n) : label = sorted_e[i][0] nearests.append (label) print (i, ': ', label, ' : distance : ', sorted_e[i][1]) return nearests ##------------------------------------------------------------ ## given an embedding and a list of embeddings ## e.g. [x,y], [[a1,b1], [a2,b2], [a3,b3]] ## return list of distances ## e.g. [.4312, .9136, .29462] ##------------------------------------------------------------ def get_embed_distances_e_elist (embed, embeds) : e_array = np.array (embed) e_distances = [] # pdb.set_trace () for e in embeds: e1_array = np.array (e) dist = distance.euclidean (e_array, e1_array) e_distances.append (dist) return e_distances ##------------------------------------------------------------ ## given probe embedding and list gallery embeddings ## e.g. [x,y], [['bc_amber/a.jpg',[a1,b1]],['bf_032/bcd.jpg',[a2,b2], ## ['bc_amber/b.jpg',[a3,b3]] ## return list of each distance between embedding and those in list ## e.g. ["bella": .4312, "otis": .9136, "amber": .29462] ##------------------------------------------------------------ def get_embed_distances (embed, embed_list) : return 42 ##------------------------------------------------------------ ## given an embedding and dict of label averages ## e.g. [x,y], ["bella":[a1,b1], "otis":[a2,b2], "amber":[a3,b3]] ## return dict of each distance between embedding and averages ## e.g. ["bella": .4312, "otis": .9136, "amber": .29462] ##------------------------------------------------------------ def get_embed_distances (embeds_d, new_embed) : e_dist_d = OrderedDict () new_e_array = np.array (new_embed) for label, embed in list(embeds_d.items()): e_array = np.array (embed) e_dist_d [label] = distance.euclidean (e_array, new_e_array) pdb.set_trace () return e_dist_d ##------------------------------------------------------------ ## returns dict of embedding average (cluster center) ##------------------------------------------------------------ def get_embed_averages (embeds_d) : e_averages_d = defaultdict () for label, embeds in list(embeds_d.items()): e_array = np.array (embeds) e_mean = np.mean (e_array, axis=0, dtype=np.float64) e_averages_d [label] = e_mean.tolist () pdb.set_trace () pdb.set_trace () return e_averages_d ##------------------------------------------------------------ ## given embedding dict, print average, and distances ## from average ##------------------------------------------------------------ def print_e_stats (embeds_d) : e_averages_d = create_embed_label_averages (embeds_d) for label, embed_average in sorted(e_averages_d.items()): ## embeds = embeds_d[label] e_distances = get_embed_distances (embeds, embed_average) e_dist_fr_mean = [] # for e in embeds print ('do something') sorted_e = sorted(e_dist_d.items(), key=lambda x: x[1]) # for label, dist : # print (dist) # print all to csv and stdout ##------------------------------------------------------------ ## find nearests labels ##------------------------------------------------------------ def get_closest_averages (embeds_d, e, n) : e_averages_d = get_embed_averages (embeds_d) e_dist_d = get_embed_distances (e_dist_d, e) print_closest (e_dist_d, n) ##------------------------------------------------------------ ## find nearests embeddings ##------------------------------------------------------------ def get_closest_embeddings (embeds, e, n) : e_distances = get_embed_distances (embeds, e) e_distances_sorted = e_distances.sorted (e_distances, key = lambda x: x[1]) for i in range (n) : print (e_distances_sorted [i]) # print_closest (e_dist_d, n) ##------------------------------------------------------------ ## generate distance matrix ##------------------------------------------------------------ def gen_embed_distance_matrix (embeds, e) : e_dist_d = get_embed_distances (embeds, e) for i in range (n) : print_closest (e_dist_d, n) ##------------------------------------------------------------ ## flatten embed_d. change dict to list of tuples (label, val) ##------------------------------------------------------------ def flatten_embedsdict (embeds_d) : e_list = [] for label, embeds in embeds_d : for embed in embeds : filename = obj_get_filename (embed) e = [label, filename, key, val] e_list.append (e) return e_list ##------------------------------------------------------------ ## get list of embedding values from embeds list ## given: [[label, filename, embedding, img_filename], ... ] ##------------------------------------------------------------ def get_embed_vals_from_list (e_list) : e_vals_list = [] for i in range (len (e_list)) : e_vals_list.append (e_list[i][2]) return e_vals_list ##------------------------------------------------------------ ## get list of image filenames from embeds list ## given: [[label, filename, embedding, img_filename], ... ] ##------------------------------------------------------------ def get_img_files_from_list (e_list): e_imgs_list = [] for i in range (len (e_list)) : e_imgs_list.append (e_list[i][3]) return e_vals_list ##------------------------------------------------------------ ## return subpath n dirs above file ##------------------------------------------------------------ def subpath (filename, n) : fnames = os.path.split (filename) img_name = fnames[1] path = fnames[0] if not path : return filename for i in range (n) : fnames = os.path.split (path) base = fnames[1] path = fnames[0] img_name = base + '/' + img_name if not path : return img_name return img_name ##------------------------------------------------------------ ## get_embeddings from obj - given dict of embedding tags, ## embed values and filename to create flattened list ## of [label, embed_file, embed_floats, img_file, chip_file] ##------------------------------------------------------------ def get_embedding_list_from_objs (embeds_d) : embedding_list = [] for label, embeds in list (embeds_d.items ()) : for embed_tag in embeds : embed_val = embed_tag.find ('./embed_val') embed_filename = embed_tag.attrib.get ('file') # pdb.set_trace () embed_file = subpath (embed_filename, 2) vals_str = embed_val.text.split () embed_floats = [float (i) for i in vals_str] img_file = get_embed_chip_source_file (embed_tag) chip_file = get_embed_chip_file (embed_tag) embedding = [label, embed_file, embed_floats, img_file, chip_file] embedding_list.append (embedding) return embedding_list ##------------------------------------------------------------ ##------------------------------------------------------------ def get_embed_chip_source_file (embed_tag) : chip_tag = embed_tag.find ('./chip') img_filename = get_chip_source_file (chip_tag) return img_filename ##------------------------------------------------------------ ##------------------------------------------------------------ def get_embed_chip_file (embed_tag) : chip_tag = embed_tag.find ('./chip') img_filename = obj_get_filename (chip_tag) return img_filename ##------------------------------------------------------------ ## output csv of distances to each train embeddings ## given dist of test embeddings, dict of train embeddings ## and filename, write out matrix all train distances from ## each test embedding ##------------------------------------------------------------ def write_csv_embed_distances (probe_d, gallery_d, csv_file, db) : e_probe_list = get_embedding_list_from_objs (probe_d) e_gallery_list = get_embedding_list_from_objs (gallery_d) e_val_probe_list = get_embed_vals_from_list (e_probe_list) e_val_gallery_list = get_embed_vals_from_list (e_gallery_list) # pdb.set_trace () fp = open (csv_file, "w") closest_file = 'closests_' + csv_file matchinfo_file = 'matchinfo_' + current_datetime () + '.csv' fp_closest = open (closest_file, "w") fp_matchinfo = open (matchinfo_file, "w") print ('\n... writing nearest matches to', closest_file) # fp_closest.write ('test; idx closest label; closest label; distance; match; test img date; test img time; matched img date; matched img time: same match \n') fp_closest.write ('test; idx closest label; closest label; distance; match') # write header for i in range (len (e_gallery_list)) : fp.write (';' + e_gallery_list[i][0]) # fp.write (';' matched) fp.write ('\n') # pdb.set_trace () # write distances match_count = 0 for i in range (len (e_probe_list)) : # write label probe_label = e_probe_list[i][0] probe_imgname = e_probe_list[i][3] probe_embedding = e_val_probe_list[i] fp.write (probe_label) # pdb.set_trace () min_indices, min_distances = write_dist_csv (probe_embedding, e_val_gallery_list, fp) probe_info = e_probe_list[i] match_count += write_closests (e_gallery_list, fp_closest, min_indices, min_distances, probe_info, db, fp_matchinfo) fp.close () fp_closest.close () fp_matchinfo.close () if db is None : print ('\n... generated', closest_file) else : print ('\n... generated', closest_file, 'and', matchinfo_file) print ('\n\ttest labels :', str (len (e_probe_list))) print ('\tmatched labels:', str (match_count)) print ('\taccuracy :', str (match_count / len (e_probe_list))) print ('\n') ##------------------------------------------------------------ ## write closest neighbors to file. if match and has file info db, ## write data to file for viewing and checking for data bias (leak) ## format: label;distance; date1;time1,date2; time2; ## image1, image2, chip1, chip2 ## ## probe_info & e_gallery_list content: ## [label, embed_file, embed_floats, img_file, chip_file] ## returned from get_embedding_list_from_objs ##------------------------------------------------------------ def write_closests (e_gallery_list, fp, min_indices, min_distances, probe_info, db, fp_matchinfo) : # pdb.set_trace () label_idx = 0 img_idx = 3 chip_idx = 4 match = 0 probe_label = probe_info[label_idx] probe_image = probe_info[img_idx] probe_chip = probe_info[chip_idx] db_df = None if db is not None : db_df = pandas.read_csv (db, sep=';') probe_datetime = get_file_datetime ([probe_image], db_df) probe_date = probe_datetime [0] probe_time = probe_datetime [1] fp.write (probe_label) for i in range (len (min_indices)) : probe_min_date_match = 0 index = min_indices[i] dist = min_distances[i] min_label = e_gallery_list[index][label_idx] min_image = e_gallery_list[index][img_idx] min_chip = e_gallery_list[index][chip_idx] # pdb.set_trace () if min_label == probe_label : match = 1 # write out info if labels match and dates match i.e. potential bias if db is not None : # pdb.set_trace () min_datetime = get_file_datetime ([min_image], db_df) min_date = min_datetime [0] min_time = min_datetime [1] if min_date[0] == probe_date[0] : probe_min_date_match = 1 fp_matchinfo.write (min_label + ';' + str (dist) + ';' + str (probe_date[0]) + ';' + str (probe_time[0]) + ';' + str (min_date[0]) + ';' + str (min_time[0]) + ';' + probe_image + ';' + min_image + ';' + probe_chip + ';' + min_chip + ';' + str (probe_min_date_match) + '\n') fp.write ('; ' + str (i) + '; ' + min_label + '; ' + str (dist)) # fp.write (';' + min_image + ';' + str (min_date[0]) + ';' + str (min_time[0])) # fp.write (';' + probe_image + ';' + str (probe_date[0]) + ';' + str (probe_time[0])) fp.write ('; ' + str (match) + '\n') return match ##------------------------------------------------------------ ## output csv of distances to each train embeddings ## given filename of test embeddings, filename of train embeddings ## and csv output filename, write out matrix all train distances from ## each test embedding ##------------------------------------------------------------ def gen_embed_dist_csv (test_files, train_files, csv_file, db, filetype="embeds") : e_test_d = defaultdict (list) e_train_d = defaultdict (list) load_objs_from_files (test_files, e_test_d, filetype) load_objs_from_files (train_files, e_train_d, filetype) # pdb.set_trace () # with open (csv_file, 'w') as fp: # for i in range (len (e_test_list)) : # write train label across top # fp.printf (e_train_list) # write_csv (e_test_list[i], e_train_list, fp) write_csv_embed_distances (e_test_d, e_train_d, csv_file, db) ##------------------------------------------------------------ ## write_dist_csv - given emedding, list of embeddings, ## and file pointer, write out embedding distances into file ## separated by ';' ## also include min distance and index to its label ## returns index of nearest neighbor and distance to nearest neighbor ##------------------------------------------------------------ def write_dist_csv (e_test, e_train_list, fp) : e_distance_list = get_embed_distances_e_elist (e_test, e_train_list) for i in range (len (e_distance_list)) : fp.write ('; ' + str (e_distance_list[i])) index = range (len (e_distance_list)) index_list = [list(x) for x in zip(index, e_distance_list)] index_list.sort(key=lambda x:x[1]) nearest_n = 1 n = 0 min_distances = [] min_indices = [] for index_dist in index_list : if index_dist[1] == 0.0 : continue min_distances.append (index_dist[1]) min_indices.append (index_dist[0]) n += 1 if n == nearest_n : break fp.write ('; ' + str (min_distances) + '; ' + str (min_indices)) fp.write ('\n') return min_indices, min_distances ##------------------------------------------------------------ ## get_count_list ##------------------------------------------------------------ def get_count_list (counts_file) : nums = [] with open (counts_file) as fp: counts = fp.readlines () for count_str in counts: if not count_str.strip() : continue count = int (count_str) nums.append (count) return nums ##------------------------------------------------------------ ## Generate a new xml file with matching count of labels as ## specified in count list. Used to create new data set. ##------------------------------------------------------------ def xml_match_cnt (xml_files, counts_file, xml_out, filetype) : objs_d = defaultdict(list) obj_files = load_objs_from_files (xml_files, objs_d, filetype) if len (objs_d) == 0 : return match = [] counts = get_count_list (counts_file) counts.sort (reverse=True) found = False for count in counts: print ("... looking for ", count, "images.") random.shuffle (list(objs_d.items())) for label, objs in list(objs_d.items()): found = False if len (objs) < count : print ("...... label", label, "too few (0).") continue found = True print ("...... label", label, "matches at ", len (objs), ", needed ", count) random.shuffle (objs) match.extend (objs[:count]) objs_d.pop(label) break # here if unable to find enough images for current count if not found : print ("*** Error: unable to find match for ", count, " images.") write_xml_file (xml_out, match, filetype) print ("... wrote xml to file: ", xml_out) ##------------------------------------------------------------ ## print dictionary ##------------------------------------------------------------ def print_dict (chips_d) : for key, value in list(chips_d.items()): print(key) print(value) ##------------------------------------------------------------ ## ^^^^^^^^^^ START COMMENT ^^^^^^^^^^^^^^^^^^^^^^ ## ^^^^^^^^^^ END COMMENT ^^^^^^^^^^^^^^^^^^^^^^ ##------------------------------------------------------------ ## partition all files into x and y percent ##------------------------------------------------------------ def generate_partitions (files, x, y, output, split_by_label=False, shuffle=True, img_cnt_min=0, test_min=0, image_size_min=0, label_group_minimum=0, filetype="chips", split_by_day_grouping=False, csv_filename=None) : # print "partitioning chips into: ", x, " ", y # pdb.set_trace () chips_d = defaultdict(list) if split_by_label : split_type = 'by_label' elif split_by_day_grouping : split_type = 'day_grouping' # # load_objs_from_files (files, chips_d, filetype) chunks = partition_objs (files, x, y, shuffle, img_cnt_min, test_min, image_size_min, label_group_minimum, filetype, split_type, csv_filename) # chunks = partition_objs (chips_d, x, y, shuffle, img_cnt_min, test_min, image_size_min, filetype, day_grouping, csv_filename) # pdb.set_trace () file_x = output + "_" + str(x) + ".xml" file_y = output + "_" + str(y) + ".xml" file_small_img = file_unused = None if len (chunks) > g_unused : if len (chunks[g_unused]) > 0 : file_unused = output + "_unused" + ".xml" generate_xml_from_objs (chunk[g_unused], file_unused, filetype) print('\t', len (list_unused), 'labels unused, failing minimum # of images, written to file : \n\t', file_unused, '\n') if len (chunks) > g_small_img : if len (chunks[g_small_img]) > 0 : file_small_img = output + "_small_faceMeta" + ".xml" generate_xml_from_objs (chunk[g_small_img], file_small_img, filetype) print(len (list_small_img), 'unused chips below min size written to file : \n\t', file_small_img, '\n') # generate_partition_files (chunks, filenames, filetype) generate_xml_from_objs (chunk[g_x], file_x, filetype) generate_xml_from_objs (chunk[g_y], file_y, filetype) ##------------------------------------------------------------ ## remove chips with resolution below min ## returns list of tiny chips ##------------------------------------------------------------ def remove_tiny_chips (chips, image_size_min) : small_chips = [] for i in range (len (chips)-1, 0, -1) : res = chips[i].find ('resolution') if int (res.text) < image_size_min : small_chips.append (chips.pop (i)) return small_chips ##------------------------------------------------------------ ## given list of chips, return list of face images ##------------------------------------------------------------ def make_images_from_chips (chips) : faces = [chip.find ('source') for chip in chips] for face in faces : face.tag = 'image' return faces ##------------------------------------------------------------ ## returns true if includig new addition will get closer to nom_count ##------------------------------------------------------------ def new_row_closer_to_nom (nom_count, addition, cur_count, max_count) : nom_diff = abs (nom_count - cur_count) new_diff = abs (nom_count - (cur_count + addition)) if cur_count + addition > max_count : return False if new_diff < nom_diff : return True ##------------------------------------------------------------ ## given group_by pandas series index, return list of ## [label date] ##------------------------------------------------------------ def create_label_date_list_from_indices (groups, indices) : # pdb.set_trace () subgroup_data = [] for i in indices : row_tuple = groups.index[i] row = [row_tuple[0], row_tuple[1]] subgroup_data.append (row) return subgroup_data ##------------------------------------------------------------ ## given panda series with label-date group counts, split rows to match ## x and y partitions. return list of df row indices ## iterate through table, looking for common label, then split ##------------------------------------------------------------ def partition_df_rows_x (grouped, num_images, x, y) : pdb.set_trace () partition_margin = .5 min_count, nom_count, max_count = get_min_nom_max (num_images, x, y, partition_margin) print ('min:', min_count, '\tnom:', nom_count, '\tmax:', max_count) y_count = x_count = 0 x_done = False group_x = [] group_y = [] # keep adding to x until above min count for i in range (len (grouped)) : row_count = grouped[i] if x_done : y_count += row_count group_y.append (i) continue if new_row_closer_to_nom (nom_count, row_count, x_count, max_count) : x_count += row_count group_x.append (i) else : y_count += row_count group_y.append (i) if x_count >= nom_count : x_done = True if x_count < min_count or x_count > max_count : print ('\n\tWarning: x partition outside goal of ', min_count, 'and', max_count, '\n') print ('splitting', num_images, 'images into ratios of', x, 'and', y) print ('partition x:', x_count, 'images in ', len (group_x), 'groups.') print ('partition y:', y_count, 'images in ', len (group_y), 'groups.') return group_x, group_y ##------------------------------------------------------------ ## given panda series of label-date group counts, split rows to match ## x and y partitions. return list of df row indices ## iterate through list of label-day table. for each newly encountered ## label, get all the counts of that label (e.g. bc_bella [2,4,1,5,6,3,2]) ## split into x, y groups ([6,5,4,3],[2,2,1]) ##------------------------------------------------------------ def partition_df_rows (grouped, num_images, x, y) : # pdb.set_trace () v = grouped.values v_list = v.tolist () n_images = sum (v_list) # end debug partition_margin = .5 group_x = [] group_y = [] current_label = None processed_labels = [] # pdb.set_trace () y_count = 0 x_count = 0 x_group_label = [] y_group_label = [] label_y_count = label_x_count = 0 group_sum_x = 0 group_sum_y = 0 for i in range (len (grouped)) : label = grouped.index[i][0] if label != current_label : # pdb.set_trace () # ensure that x_group_label and y_group_label is empty if len (x_group_label) > 0 : print ('Error: switching labels but x group not empty') if len (y_group_label) > 0 : print ('Error: switching labels but y group not empty') if label in processed_labels : print ('Error: Already processed label', label) continue # maybe do something more? if current_label is not None : processed_labels.append (current_label) # wrap up current label if get_verbosity () > 1 : print ('x_count2:', label_x_count, '\ty_count:', label_y_count) if label_x_count != group_sum_x : print ('Error: Partition for', label, 'expects x : ', group_sum_x, ', got', label_x_count) if label_y_count != group_sum_y : print ('Error: Partition for', label, 'expects y : ', group_sum_y, ', got', label_y_count) x_count += label_x_count y_count += label_y_count label_y_count = label_x_count = 0 group_sum_x = group_sum_y = 0 # init new label current_label = label # get all groups of that label label_groups = grouped [label] # pdb.set_trace () if len (label_groups) < 3 and get_verbosity () > 1 : print ('label[0]:', label, ':', label_groups.index[0], ':', label_groups.iloc[0]) if len (label_groups) == 2 : print ('label[1]:', label, ':', label_groups.index[1], ':', label_groups.iloc[1]) # get partitions if get_verbosity () > 1 : print (current_label, end=' ') x_group_label, y_group_label = get_label_x_y_counts (label_groups, x, y, partition_margin) group_sum_x = sum (x_group_label) group_sum_y = sum (y_group_label) # pdb.set_trace () row_count = grouped[i] if row_count in x_group_label : label_x_count += row_count group_x.append (i) x_group_label.remove (row_count) else : if row_count not in y_group_label : print ('Error: group count on found in x nor y') label_y_count += row_count group_y.append (i) y_group_label.remove (row_count) x_count += label_x_count y_count += label_y_count # pdb.set_trace () min_count, nom_count, max_count = get_min_nom_max (num_images, x, y, partition_margin) if x_count < min_count or x_count > max_count : print ('\n\tWarning: Unable to partition within ', partition_margin, '% of ', x, 'between', min_count, 'and', max_count, '\n') print ('splitting', num_images, 'images into ratios of', x, 'and', y) print ('partition x:', x_count, 'images in ', len (group_x), 'groups.') print ('partition y:', y_count, 'images in ', len (group_y), 'groups.') return group_x, group_y ##------------------------------------------------------------ ## given list of dates for a label and count of images ## for each date, return list of numbers that make ## up partitions x and y ## e.g. [5,3,6,1,2,1,2,2,1] -> [6,5,3,2,2,2,1,1,1] ## returns [6,5,3,2,2] [2,1,1,1] ##------------------------------------------------------------ def get_label_x_y_counts (label_groups, x, y, partition_margin) : # get all values of the groups group_values = label_groups.values vals_list = group_values.tolist () vals_list.sort (reverse=True) num_label_images = sum (group_values) min_count, nom_count, max_count = get_min_nom_max (num_label_images, x, y, partition_margin) if get_verbosity () > 1 : print ('total:', num_label_images, '\tmin:', min_count, '\tnom:', nom_count, '\tmax:', max_count) label_y_count = label_x_count = 0 x_group = [] y_group = [] x_done = False # pdb.set_trace () # handle special case of 1 and 2 vals if len (vals_list) < 3 : x_group.append (vals_list[0]) label_x_count += vals_list[0] if len (vals_list) == 2 : label_y_count += vals_list[1] y_group.append (vals_list[1]) else : for i in range (len (vals_list)) : row_count = vals_list[i] # keep adding to group_x until above min count (x_done == True) if not x_done and new_row_closer_to_nom ( nom_count, row_count, label_x_count, max_count) : label_x_count += row_count x_group.append (row_count) else : label_y_count += row_count y_group.append (row_count) if label_x_count >= nom_count : x_done = True if get_verbosity () > 1 : print ('x_count1:', label_x_count, '\ty_count:', label_y_count) if label_x_count > max_count : print ('Warning: x_count above max. Values: ', vals_list) if label_x_count < min_count : print ('Warning: x_count below min. Values: ', vals_list) return x_group, y_group ##------------------------------------------------------------ ## don't need this ##------------------------------------------------------------ def get_num_label_images (grouped, idx, label) : count = 0 for i in range (idx, len (grouped)) : cur_label = grouped.index[i][0] if label == cur_label : count += grouped [i] else : return count ##------------------------------------------------------------ ## given groupings and label, extract group counts and indices ##------------------------------------------------------------ def get_label_db_info (grouped, label) : print ('function get_label_count needs to be implemented ') return 0, 0 # return label_count, groups, group_idxs ##------------------------------------------------------------ ##------------------------------------------------------------ def get_min_nom_max (count, x, y, margin=.5) : val_nom = int (count * x / 100) val_min = int (count * (x-margin) / 100) val_max = int (count * (x+margin) / 100) return val_min, val_nom, val_max ##------------------------------------------------------------ ## image = df.loc[i]['IMAGE'] ## given grouped dataframe, extract image names ## e.g. ## IMAGE LABEL DATE TEST_TRAIN DATE_TIME ## 637 imageSource... bc_steve 20150824 train 2015:08:24 14:31:05 ## 638 imageSource... bc_steve 20150824 test 2015:08:24 14:31:06 ## 639 imageSource... bc_steve 20150824 train 2015:08:24 14:31:33 ##------------------------------------------------------------ def get_images_from_group (groups, selected_rows) : images = [] pdb.set_trace () for label_date, group in groups: for index, row in group.iterrows () : image = row['IMAGE'] images.append (image) return images # label = label_date[0] # date = label_date[1] # groups.get_group ((label, date)) ##------------------------------------------------------------ ##------------------------------------------------------------ def images_from_label_date (groups, label_dates) : images = [] for label_date in label_dates : label = label_date[0] date = label_date[1] # print ('label_date :', label_date) # print ('label :', label) # print ('date :', date) # continue group = groups.get_group ((label, date)) for index, row in group.iterrows () : image = row['IMAGE'] images.append (image) pdb.set_trace () return images ##------------------------------------------------------------ ## given indices into table of (label, date), count ## return list of (label, date) at indices ##------------------------------------------------------------ def get_label_date_from_indices (label_day_group_counts, indices) : label_dates = [] for group_index in indices : label_date = label_day_group_counts.index[group_index] label_dates.append (label_date) return label_dates ##------------------------------------------------------------ # same?? as def xml_split_by_list (orig_file, new_files, output_file, filetype='faces') : ##------------------------------------------------------------ def split_chips_by_images (chips_d, images_x) : return 5 ##------------------------------------------------------------ # given dataframe with column name, return list of images ##------------------------------------------------------------ def get_image_list_from_df (df, img_column) : vals = [] for col_name, data in df.items () : if col_name == img_column : for i in range (len (data)) : val = data[i] vals.append (val) # pdb.set_trace () return vals ##------------------------------------------------------------ ##------------------------------------------------------------ def test_utils () : pdb.set_trace () print ('hello world!') ##------------------------------------------------------------ ## given list of images, return list of uniq label ##------------------------------------------------------------ def get_all_labels (objs_d) : labels = [] for label, objs in list(objs_d.items ()) : labels.append (label) return labels ##------------------------------------------------------------ ##------------------------------------------------------------ def get_file_datetime (obj_filenames, df_all) : parent_path='/home/data/bears/' # pdb.set_trace () ### fix path to ensure filename will match image field in csv filenames = [f.replace (parent_path, '') for f in obj_filenames] df_images = pandas.DataFrame (filenames, columns=['IMAGE']) # get table from list of images df_images_info = pandas.merge (df_all, df_images, on=['IMAGE'], how='inner') # get date and time from result dates = get_image_list_from_df (df_images_info, 'DATE') times = get_image_list_from_df (df_images_info, 'TIME') # datetime = [dates, times] return [dates, times] ##------------------------------------------------------------ ## given list of image filenames and csv of image info ## return dataframe of info for specified images ##------------------------------------------------------------ def get_files_info_df (obj_filenames, db_csv_filename, parent_path='/home/data/bears/') : # pdb.set_trace () ### fix path to ensure filename will match image field in csv filenames = [f.replace (parent_path, '') for f in obj_filenames] df_all = pandas.read_csv (db_csv_filename, sep=';') df_images = pandas.DataFrame (filenames, columns=['IMAGE']) num_input = len (obj_filenames) # get table from list of images df_images_info = pandas.merge (df_all, df_images, on=['IMAGE'], how='inner') return df_images_info ##------------------------------------------------------------ ## given a list of images, and csv of image info, ## return count of each label-day groups ##------------------------------------------------------------ def get_label_day_groups (obj_filenames, db_csv_filename) : df_images_table = get_files_info_df (obj_filenames, db_csv_filename) groups_label_date = df_images_table.groupby (['LABEL', 'DATE']) # pdb.set_trace () # groups_label_date.get_group (('bc_kwatse', 20110830)) # create table of count of each label-date group label_day_group_counts = groups_label_date.size () return label_day_group_counts ##------------------------------------------------------------ ## given label_date_groups, indices into group_list and image info ## return list of images from indices label_date_group_list ##------------------------------------------------------------ def get_images_from_indices (label_date_groups, group_indices, df_images_db) : # get [label, date] lists of each group # e.g. [['bc_adeane', 20140905], ['bc_also', 20160810]... ] label_date_list = create_label_date_list_from_indices ( label_date_groups, group_indices) images = get_images_for_label_dates (label_date_list, df_images_db) return images ##------------------------------------------------------------ ## given list of [label date], return images matching those labels and dates ##------------------------------------------------------------ def get_images_for_label_dates (label_date_list, df_images_db) : df_label_date = pandas.DataFrame (label_date_list, columns=['LABEL', 'DATE']) # join label_date list with images db to get images info df_label_date_info = pandas.merge (df_images_db, df_label_date, on=['LABEL', 'DATE'], how='inner') # extract images to list images = get_image_list_from_df (df_label_date_info, 'IMAGE') return images ##------------------------------------------------------------ # given obj dict, group into x and y with mutually exclusive # labels in each group ##------------------------------------------------------------ def partition_files_by_label (objs_d, num_images, x, y) : partition_margin = .5 objs_x = [] objs_y = [] min_count, nom_count, max_count = get_min_nom_max (num_images, x, y, partition_margin) labels=list(objs_d.keys()) random.shuffle (labels) x_count = 0 y_count = 0 label_x_cnt = 0 for label in labels : new_count = len (objs_d[label]) if new_row_closer_to_nom (nom_count, new_count, x_count, max_count) : x_count += new_count objs_x.extend (objs_d[label]) label_x_cnt += 1 else : y_count += new_count objs_y.extend (objs_d[label]) if get_verbosity () > 0 : print ('label split of', x, 'and', y, 'results in', str (x_count), 'and', str (y_count), 'images and label count of', str (label_x_cnt), 'and', str (len (labels)-label_x_cnt)) return objs_x, objs_y ##------------------------------------------------------------ ## given list of images, return list of only one image per day per label ##------------------------------------------------------------ def extract_single_label_group_image (chip_file, csv_filename, output_file) : objs_d = defaultdict(list) obj_filenames = load_objs_from_files ([chip_file], objs_d, 'chips', 'source') if get_verbosity () > 0 : print ('input number of images:', len (obj_filenames)) parent_path='/home/data/bears/' df_images_info = get_files_info_df (obj_filenames, csv_filename, parent_path) groups_label_date = df_images_info.groupby (['LABEL', 'DATE']) # [['bc_adeane', 20140905]:1,['bc_also', 20160810],5] .. []] # pdb.set_trace () label_day_group_counts = groups_label_date.size () if get_verbosity () > 0 : print ('number of label-day groups:', len (label_day_group_counts)) # get list of label-date # [['bc_adeane', 20140905],['bc_also', 20160810] .. []] label_date_list = create_label_date_list_from_indices ( label_day_group_counts, range (len (label_day_group_counts))) # for each label-day group, select random image to include singles = [] for label_date in label_date_list : images = get_images_for_label_dates ([label_date], df_images_info) image = random.choice (images) singles.append (image) localized_singles = [parent_path+s for s in singles] objs_singles, objs_not_singles = obj_split (objs_d, localized_singles, 'source', 'files') if get_verbosity () > 0 : print ('count of singles images :', len (objs_singles)) print ('count of extr images :', len (objs_not_singles)) generate_xml_from_objs (objs_singles, output_file) return ##------------------------------------------------------------ # partition by groups # if chips_d is None, then input was csv # 1. Read CSV # 2. Create grouping by label, date, image count # 3. partition into x, y # 4. generate list of label-dates for each group # 5. use label-dates list of label-dates generate two new xml # 6. IMAGE;LABEL;DATE;TEST_TRAIN;DATE_TIME # else # convert chips_d to chips_table # read CVS to cvs_df # select label, date from join chips with csv_df # A2 # A3 # A4 # use list of label-dates to generate two new xml # # # # ##------------------------------------------------------------ def partition_files_by_group (obj_filenames, objs_d, x, y, csv_filename, label_group_minimum) : parent_path='/home/data/bears/' pdb.set_trace () df_images_info = get_files_info_df (obj_filenames, csv_filename, parent_path) groups_label_date = df_images_info.groupby (['LABEL', 'DATE']) # [['bc_adeane', 20140905]:1,['bc_also', 20160810],5] .. []] label_day_group_counts = groups_label_date.size () # group_count_rand = label_day_group_counts.sample (frac=1) # randomize order # partition - looking for something like [1,2,3,7 ] [4,5,6,8,9,10] dropped_images_cnt = 0 labels = get_all_labels (objs_d) if label_group_minimum > 0 : label_day_group_counts, dropped_images_cnt = remove_labels_too_few (labels, label_day_group_counts, label_group_minimum); group_idx_x, group_idx_y = partition_df_rows (label_day_group_counts, len (obj_filenames)-dropped_images_cnt, int (x), int (y)) x_images_list = get_images_from_indices (label_day_group_counts, group_idx_x, df_images_info) y_images_list = get_images_from_indices (label_day_group_counts, group_idx_y, df_images_info) localized_images_x_list = [parent_path+s for s in x_images_list] localized_images_y_list = [parent_path+s for s in y_images_list] return localized_images_x_list, localized_images_y_list ##------------------------------------------------------------ ## remove labels that have fewer groups than min ##------------------------------------------------------------ def remove_labels_too_few (labels, label_day_group_counts, label_group_minimum) : # pdb.set_trace () dropped_labels = [] dropped_count = [] for label in labels : label_group_counts = label_day_group_counts [label] label_group_count_values = label_group_counts.values if len (label_group_count_values) < label_group_minimum : # pdb.set_trace () dropped_count.append (sum (label_group_count_values)) dropped_labels.append (label) label_day_group_counts = label_day_group_counts.drop(labels=label) print ('--------------------') print (sum (dropped_count), 'images and', len (dropped_labels), 'labeld were dropped due to label-date group minimum of', label_group_minimum) print ('--------------------') if get_verbosity () > 0 and len (dropped_labels) > 0 : print ('\nDropped labels and image counts:') print ('--------------------') for i in range (len (dropped_labels)) : print (dropped_labels[i], '; ', dropped_count[i]) return label_day_group_counts, sum (dropped_count) ##------------------------------------------------------------ ## partition chips into x and y percent ## will do one of: ## - split by label, ignoring dates ## - split across label, ignoring dates ## - split by label afer grouping images by date for each label ## - split across all labels afer grouping images by date for each label ## returns two lists of ##------------------------------------------------------------ def partition_objs (filenames, x, y, shuffle=True, img_cnt_min=0, test_minimum=0, image_size_min=0, label_group_minimum=0, filetype="chips", split_type="by_chips", csv_filename=None) : if get_verbosity () > 0 : print ("partitioning chips into: ", x, " ", y) print ('split type:', split_type) chunks = [] objs_d = defaultdict(list) if split_type == 'by_label' : filename_type = 'file' obj_filenames = load_objs_from_files (filenames, objs_d, filetype, filename_type) objs_x, objs_y = partition_files_by_label (objs_d, len (obj_filenames), x, y) chunks.append (objs_x) chunks.append (objs_y) return chunks if split_type == 'day_grouping' : ## if shuffle == False : print ("Warning: ignoring unsupported feature to split by label when grouped by day.") # use filenames from chip source since only image names are in db # get partitions by filenames filename_type = 'file' if filetype == 'chips' : filename_type = 'source' obj_filenames = load_objs_from_files (filenames, objs_d, filetype, filename_type) files_x, files_y = partition_files_by_group (obj_filenames, objs_d, x, y, csv_filename, label_group_minimum) objs_x, objs_not_x = obj_split (objs_d, files_x, filename_type) objs_y, objs_not_y = obj_split (objs_d, files_y, filename_type) chunks.append (objs_x) chunks.append (objs_y) return chunks # pdb.set_trace () chip_files = load_objs_from_files (filenames, objs_d, filetype) chunks_few = [] labels_few = [] if img_cnt_min != 0 : for label, chips in list(objs_d.items()): # remove chips below size minimum if len (chips) < img_cnt_min : chunks_few.extend (chips) labels_few.append (label) objs_d[label] = [] if len (labels_few) > 0 : print(len (labels_few), 'unused labels, each with less than ', img_cnt_min, 'images') print ('labels:',labels_few) else : print('All labels used.') if (shuffle == True) : ## concat all labels, then split ## TODO check for image_size_min all_chips=[] for label, chips in list(objs_d.items()): all_chips.extend (chips) if image_size_min != 0 : small_chips = remove_tiny_chips (all_chips, image_size_min) random.shuffle (all_chips) partition = int(round(len(all_chips) * float (x) / float (100))) # print "partition value : ", partition chunks.append (all_chips[:partition]) chunks.append (all_chips[partition:]) print("\nmixed partition of ", x, ", len : ", len (chunks[0])) print("shuffled partition of ", y, ", len : ", len (chunks[1])) print("shuffled total of ", len (chunks[0]) + len (chunks[1])) # print "chips count: ", len (all_chips) if len (labels_few) > 0 : chunks.append (chunks_few) else : chunks.append ([]) else : ## split per label, then combine into chunks # pdb.set_trace () chunks_x = [] chunks_y = [] small_images_chips = [] chip_cnt = 0 for label, chips in list(objs_d.items()): # remove chips below size minimum if image_size_min != 0 : small_images_chips.extend (remove_tiny_chips (chips, image_size_min)) random.shuffle (chips) chip_cnt += len (chips) partition = int(round(len(chips) * float (x) / float (100))) chunks_x.extend (chips[:partition]) chunks_y.extend (chips[partition:]) chunks.append (chunks_x) chunks.append (chunks_y) print() print(len (chunks_x), ' chips in individual partition of', x) print(len (chunks_y), ' chips in individual partition of', y) print(chip_cnt, 'total', filetype) print() if len (labels_few) > 0 : chunks.append (chunks_few) else : chunks.append ([]) if len (small_images_chips) : # files_small = [chip.attrib.get ('file') for chip in small_images_chips] # img_list = '\n '.join (files_small) # print img_list print(len (small_images_chips), 'images unused due to size below', image_size_min) small_images_faces = make_images_from_chips (small_images_chips) chunks.append (small_images_faces) else : print('All chips used.\n') chunks.append ([]) # pdb.set_trace () return chunks ##------------------------------------------------------------ ## split defaultdict<string><list> into n equal random parts ## returns array (list of n lists) ## By default, all labels are combined, shuffled, then split. ## If shuffle is False, shuffle each label, split, then added to chunks ## ##------------------------------------------------------------ def split_chips_into_n (chips_d, n, shuffle_mode) : chips_d_items = list(chips_d.items ()) all_chips_cnt = sum ([len (chips) for label, chips in chips_d_items]) mode_text = '' if shuffle_mode == 0 : ## concat all labels, then split chunks=[] all_chips=[] for label, chips in chips_d_items : all_chips.extend (chips) random.shuffle (all_chips) chunk_size = len(all_chips) / float (n) print("\nshuffled fold size : ", int (chunk_size)) print("chips count: ", all_chips_cnt) mode_text = 'All chips are mixed together then divided info each fold.' for i in range (n): start = int(round(chunk_size * i)) end = int(round(chunk_size * (i+1))) # print "start : ", start # print "end : ", end chunks.append (all_chips[start:end]) elif shuffle_mode == 1 : ## split per label, then combine into chunks # pdb.set_trace () chunks = [[] for i in range(n)] # create n empty lists mode_text = ' chips of each label are split evenly into each fold.' for label, chips in chips_d_items : random.shuffle (chips) chunk_size = len(chips) / float (n) j = list(range(n)) # randomize order of fold assignment since many labels # have few chips. prevents single chips from all being # in same fold. random.shuffle (j) for i in range (n): start = int(round(chunk_size * i)) end = int(round(chunk_size * (i+1))) chunks[j[i]].extend (chips[start:end]) else : ## split across labels ## TODO : split labels here chunks = [[] for i in range(n)] # create n empty lists random.shuffle (chips_d_items) # randomize order of fold assignment j = list(range(n)) random.shuffle (j) chunk_size = len (chips_d_items) / float (n) # pdb.set_trace () for i in range (n): start = int(round(chunk_size * i)) end = int(round(chunk_size * (i+1))) labels_list = chips_d_items[start:end] for label, chips in labels_list : chunks[j[i]].extend (chips) print(len (chips_d), 'total labels, split into', n, 'folds = ~', int (len (chips_d) / float (n))) print(all_chips_cnt, 'total chips, split into', n, 'folds = ~', int (all_chips_cnt / float (n))) print(' ', mode_text) folds_cnt = [len (fold) for fold in chunks] labels_cnt = [[] for i in range (n)] for i in range (n) : labels = [(chip.find ('label')).text for chip in chunks[i]] labels_cnt[i] = len (set (labels)) print('count per fold:') print(' ', folds_cnt, 'sum: ', sum (folds_cnt)) print('labels per fold:') print(' ', labels_cnt) # pdb.set_trace () return chunks ##------------------------------------------------------------ ## create n sets of trees of train & validate content ## then write xml files ##------------------------------------------------------------ def generate_folds_files (train_list, validate_list, filename) : n = len (train_list) # write 2 files for each fold print("\nGenerated", n, "sets of folds files: ") for i in range(n) : t_root, t_chips = create_new_tree_w_element () for j in range (len (train_list[i])) : chip = train_list[i][j] t_chips.append (chip) v_root, v_chips = create_new_tree_w_element () for j in range (len (validate_list[i])) : chip = validate_list[i][j] v_chips.append (chip) tree_train = ET.ElementTree (t_root) tree_validate = ET.ElementTree (v_root) t_name = filename + "_train_" + str(i) + ".xml" v_name = filename + "_validate_" + str(i) + ".xml" indent (t_root) indent (v_root) tree_train.write (t_name) tree_validate.write (v_name) print("\t", t_name, "\n\t", v_name) print("") ##------------------------------------------------------------ ## create each xml tree for x and y partition ## then write xml files ##------------------------------------------------------------ def generate_xml_from_objs (obj_list, filename, filetype="chips") : root, objs = create_new_tree_w_element (filetype) for obj in obj_list : objs.append (obj) indent (root) tree_x = ET.ElementTree (root) tree_x.write (filename, encoding='ISO-8859-1') print("\nGenerated xml file: \n\t", filename, "\n") ##------------------------------------------------------------ ## create n sets of train & validate files ## split list into n chunks ## foreach i in n: chunks[n] is in validate, the rest in train ## returns list of train content and list of validate content ## to be consumed by generate_folds_files ##------------------------------------------------------------ def generate_folds_content (chips_d, n_folds, shuffle=True) : n = int (n_folds) validate_list = [] train_list = [[] for i in range(n)] chunks = split_chips_into_n (chips_d, n, shuffle) for i in range (n): validate_list.append (chunks[i]) # pdb.set_trace() for j in range (n): if (j == i): continue train_list[i].extend (chunks[j]) return train_list, validate_list ##------------------------------------------------------------ ## creates new tree, add standard file heading, ## then add specified element. returns root and new element ##------------------------------------------------------------ def create_new_tree_w_element (filetype="chips") : r = ET.Element ('dataset') r_c = ET.SubElement (r, 'comment').text = 'generated by ' + g_exec_name curtime = datetime.datetime.now().strftime("%Y%m%d:%H%M") ET.SubElement (r, 'date').text = filetype + ' file generated at ' + curtime ET.SubElement (r, 'cwd').text = os.getcwd () ET.SubElement (r, 'command').text = get_argv () ET.SubElement (r, 'filetype').text = get_filetype () if filetype in ['faces', 'images'] : elem_name = "images" else : elem_name = filetype r_elem = ET.SubElement (r, elem_name) return r, r_elem ##------------------------------------------------------------ ## ##------------------------------------------------------------ def write_file_with_label (xml_file_in, xml_file_out, key): tree_i = ET.parse (xml_file) root_i = tree.getroot() for chip in root_i.findall ('./chips/chip'): label_list = chip.findall ('label') if len (label_list) > 1 : print("too many labels: ", label_list) continue label = label_list[0].text if label != key : root.remove (chip) indent (root_i) tree_i.write (xml_file_out) ##------------------------------------------------------------ ## ##------------------------------------------------------------ def unpath_chips (xml_files, append): # pdb.set_trace () for xml_file in xml_files: root, tree = load_file (xml_file) for chip in root.findall ('./chips/chip'): label_list = chip.findall ('label') pathed_chipfile = chip.attrib.get ('file') unpathed_chipfile = os.path.basename (pathed_chipfile) # pdb.set_trace () chip.set ('file', unpathed_chipfile) # print " ", pathed_chipfile # print " ---> ", unpathed_chipfile basename, ext = os.path.splitext(xml_file) if append: xml_file_unpathed = xml_file + "_unpathed" else: xml_file_unpathed = basename + "_unpathed" + ext # pdb.set_trace () if get_verbosity () > 1 : print("\n\twriting unpath chips to file: ", xml_file_unpathed, "\n") indent (root) tree.write (xml_file_unpathed) ##------------------------------------------------------------ ## return flattened list of all xml files ##------------------------------------------------------------ def generate_xml_file_list (inputfiles): f = [] for i in inputfiles : if os.path.isdir (i) : files = get_xml_files (i) f.extend (files) else : f.append (i) return f ##------------------------------------------------------------ ## return flattened list of all image files (jpg, jpeg, png) ##------------------------------------------------------------ def get_dirs_images (filenames, exts=['.jpg', '.jpeg', '.png']): imgs = [] # print ('getting images for : ', filenames) for filename in filenames : if filename[0]=='.' : continue for ext in exts: if filename.lower().endswith (ext.lower()) : imgs.append (filename) break return imgs ##------------------------------------------------------------ ## load objs from list of files into objs_d ## if filename is directory, load all its xml files ## objs_d is dictionary of <string><element_list> ## ex: d["b-032"] = ["<Element 'chip' at 0x123,..,<Element 'chip' at 0x43] ## d["b-747"] = ["<Element 'chip' at 0x987,..,<Element 'chip' at 0x65] ## return list of files in metadata ##------------------------------------------------------------ def load_objs_from_files (filenames, objs_d, filetype="chips", filename_type='file'): objfiles = [] # print "in load_objs_from_files" ## load all chips into objs_d # print("\nLoading", filetype, "for files: ") for file in filenames: print("\nLoading ", file) # pdb.set_trace() root, tree = load_file (file) objfiles.extend (load_objs (root, objs_d, filetype, filename_type)) # pdb.set_trace() return objfiles ##------------------------------------------------------------ ## ##------------------------------------------------------------ ##------------------------------------------------------------ ## filter chips : ## given list of chip files, and circle defined by ## pt and distance, return chips with nose in circle ##------------------------------------------------------------ def filter_chips (infiles, pt, distance, outfile): chips_d = defaultdict(list) objfiles = load_objs_from_files (infiles, chips_d) l_eye, r_eye, nose, noses = get_chip_face_stats (chips_d) # pdb.set_trace () if (pt[0] == 0) and (pt[1] == 0): nose_x = noses[0] nose_y = noses[1] else: nose_x = pt[0] nose_y = pt[1] if distance == 0: ## use 1/2 distance between eyes distance = (l_eye[0]-r_eye[0])/2 chips_list, x_list, y_list, label_count = get_chips_noses_in_circle ( chips_d, nose_x, nose_y, distance) y_list_flip = [] for y in y_list : y_list_flip.append (0-y) have_display = "DISPLAY" in os.environ if have_display: # plt.autoscale(enable=True, axis='both', tight=None) plt.axis('equal') plt.axis('off') plt.scatter (l_eye[0], 0-l_eye[1], c='blue', s=64) plt.scatter (r_eye[0], 0-r_eye[1], c='blue', s=64) plt.scatter (x_list, y_list_flip, c='green', s=16) plt.scatter (nose_x, 0-nose_y, c='red', s=128) #plt.imsave ("noses.jpg", format="png") plt.savefig ("nose_fig.png") plt.show () write_chip_file (chips_list, outfile) print('----------------------------------') print('eyes:', r_eye, l_eye) print('center:', nose_x, nose_y) print('radius:', distance) print('----------------------------------') print(len (x_list), 'chips matched from', chips_count (chips_d)) print('with', label_count, 'labels from original', len (chips_d)) print(' chips written to file:', outfile) print('') # pdb.set_trace () ##------------------------------------------------------------ ## return count of chips in dict ##------------------------------------------------------------ def chips_count (chips_d): count = 0 for key, chips in sorted(chips_d.items()): ## list of chips count += len (chips) return count ##------------------------------------------------------------ ## return chips with noses within ## circle of radius d, centered at x,y ##------------------------------------------------------------ def get_chips_noses_in_circle (chips_d, pt_x, pt_y, distance): x_list = [] y_list = [] filtered_chips = [] # pdb.set_trace () ## comparing with squares since sqrt is slow distance = distance**2 label_count = 0 for key, chips in sorted(chips_d.items()): ## list of chips chip_count = 0 for chip in chips: for part in chip.findall ('part'): name = part.attrib.get ('name') if name == "nose" : nose_x = int (part.attrib.get ('x')) nose_y = int (part.attrib.get ('y')) ## check to see if within specified dist d = (pt_x-nose_x)**2 + (pt_y-nose_y)**2 if d <= distance: x_list.append (nose_x) y_list.append (nose_y) filtered_chips.append (chip) chip_count = 1 if chip_count > 0: label_count += 1 return filtered_chips, x_list, y_list, label_count ##------------------------------------------------------------ ## given chip list, write to xml file ##------------------------------------------------------------ def write_chip_file (chips, outfile): root, chips_elem = create_new_tree_w_element () for chip in chips: chips_elem.append (chip) indent (root) tree = ET.ElementTree (root) tree.write (outfile) ##------------------------------------------------------------ ## given list, write to xml file ##------------------------------------------------------------ def write_xml_file (outfile, tags, filetype): root, tags_elem = create_new_tree_w_element (filetype) for tag in tags : tags_elem.append (tag) indent (root) tree = ET.ElementTree (root) tree.write (outfile) ##------------------------------------------------------------ ## get chip face stats : ## nose (x, y), eye1 (x,y), eye2 (x, y), eye dist ## collect all nose_x, nose_y, get average ## get first chip, extract eye1, eye2, get distance ##------------------------------------------------------------ def chip_face_stats (filenames): chips_d = defaultdict(list) objfiles = load_objs_from_files (filenames, chips_d) l_eye, r_eye, nose, noses = get_chip_face_stats (chips_d) have_display = "DISPLAY" in os.environ if not have_display: return display_hist_heat (noses) display_hist (noses) band_width, bands = get_dist_hist (noses) default_dist = (l_eye[0] - r_eye[0]) / 2 display_dist_hist (bands, band_width, default_dist) plt.show () ##------------------------------------------------------------ ## plot nose dist histogram ##------------------------------------------------------------ def display_dist_hist (bands, band_width, default_dist=0, label_x='', label_y='', title=''): band_label = [(x+1) * band_width for x in range(len(bands))] # pdb.set_trace () # plt.autoscale(enable=True, axis='both', tight=None) # plt.axis('equal') fig3 = plt.figure() if not title : plt.title ('distance histogram. default @' + str (default_dist)) plt.axis('on') if not label_y : plt.ylabel('face count') if not label_x : plt.xlabel('distance') plt.bar (band_label, bands, 7, color='green') if default_dist : plt.bar (default_dist, max(bands), 7, color='red') # plt.scatter (band_label, bands, c='green', s=16) # plt.savefig ("nose_fig.png") ##------------------------------------------------------------ ## plot histogram heatmap ##------------------------------------------------------------ def display_hist_heat (noses): x = noses[0] y = noses[1] # Plot data fig1 = plt.figure() plt.title ('nose histogram.') plt.plot(x,y,'.r') plt.xlabel('x') plt.ylabel('y') # Estimate the 2D histogram nbins = 10 H, xedges, yedges = np.histogram2d(x,y,bins=nbins) # H needs to be rotated and flipped H = np.rot90(H) H = np.flipud(H) # Mask zeros Hmasked = np.ma.masked_where(H==0,H) # Mask pixels with a value of zero # Plot 2D histogram using pcolor fig2 = plt.figure() plt.title ('nose histogram heat map: ' + str (nbins) + ' bins.') plt.pcolormesh(xedges,yedges,Hmasked) plt.xlabel('x') plt.ylabel('y') cbar = plt.colorbar() cbar.ax.set_ylabel('Counts') # plt.show () ##------------------------------------------------------------ ## return list of paired tuple ##------------------------------------------------------------ def create_tuple_pair (label1, image1, label2, image2): return ((label1, image1), (label2, image2)) ##------------------------------------------------------------ ## generate all possible index pairs of images of given label ## return list of list. one list per label of all combination ## for that label ##------------------------------------------------------------ def gen_all_matched_obj_pairs (chips_d): matched_lists = [] matched_pairs = [] chips_list = sorted(chips_d.items()) label_count = len (chips_list) for label1 in range (label_count) : # for each label matched_pairs = [] chip1s_cnt = len (chips_list[label1][1]) # pdb.set_trace () for i in range (chip1s_cnt) : # iterate thru images for j in range (i+1, chip1s_cnt) : pairs = create_tuple_pair (label1, i, label1, j) matched_pairs.append (pairs) # pdb.set_trace () matched_lists.append (matched_pairs) # pdb.set_trace () return matched_lists ##------------------------------------------------------------ ## generate all possible index pairs of images of different labels ## return array of lists. List indices >= to first index will be null. ## i.e. len (lists[4][2]) = 0 . len (lists [2][4] = unmatched pairs ## for bear 2 and bear 4 ## e.g. unmatched images for labels 5, 3 ## will be in lists[3][5] ## Need to have this table to counter labels with lots of images. ## If we were to only generate list of unmatched images for a ## label, it would be weighted towards the labels with greater ## images. To use this table, select a random label1, then a ## random label2, then select random entry of list in this table. ##------------------------------------------------------------ def gen_all_unmatched_obj_pairs (chips_d): unmatched_lists = [] unmatched_sublist = [] unmatchted_pairs = [] chips_list = sorted(chips_d.items()) label_count = len (chips_list) for label1 in range (label_count) : unmatched_sublist = [] for x in range (label1+1) : # empty out lower indices unmatched_sublist.append ('') chip1s_cnt = len (chips_list[label1][1]) for label2 in range (label1+1, label_count) : unmatched_pairs = [] chip2s_cnt = len (chips_list[label2][1]) for i in range (chip1s_cnt) : for j in range (chip2s_cnt) : pairs = create_tuple_pair (label1, i, label2, j) unmatched_pairs.append (pairs) unmatched_sublist.append (unmatched_pairs) # pdb.set_trace () unmatched_lists.append (unmatched_sublist) return unmatched_lists ##------------------------------------------------------------ ## write out N pairs of matched pairs and M pairs of unmatched pairs ##------------------------------------------------------------ def generate_chip_pairs (input_files, matched_cnt, unmatched_cnt, triplets, output): chips_d = defaultdict(list) load_objs_from_files (input_files, chips_d) if triplets > 0 : unmatched_cnt = matched_cnt = triplets selected_matched_indices, selected_unmatched_indices = get_selected_pair_indices (chips_d, matched_cnt, unmatched_cnt, triplets) matched_chips = create_chip_list (chips_d, selected_matched_indices) unmatched_chips = create_chip_list (chips_d, selected_unmatched_indices) ## create xml content root, chips = create_new_tree_w_element ('pairs') elem_name = "pair_matched" for i in range (0, len (matched_chips), 2) : # create new matched pair element, then put 2 chips under it pair = ET.SubElement (chips, elem_name) pair.append (matched_chips[i]) pair.append (matched_chips[i+1]) # pdb.set_trace () elem_name = "pair_unmatched" for i in range (0, len (unmatched_chips), 2) : # create new matched pair element, then put 2 chips under it pair = ET.SubElement (chips, elem_name) pair.append (unmatched_chips[i]) pair.append (unmatched_chips[i+1]) # pdb.set_trace () if matched_cnt == 0 : matched_cnt = len (selected_matched_indices) if unmatched_cnt == 0 : unmatched_cnt = len (selected_unmatched_indices) ## write out file print('\nWriting', matched_cnt, 'matched pairs and', unmatched_cnt, 'unmatched pairs to file:') print('\t', output, '\n') indent (root) tree = ET.ElementTree (root) tree.write (output) ##------------------------------------------------------------ ## return two lists of pairs for matched and unmatched ## generate a list of all possible indices for matching and ## unmatching pairs for each label. store in table of labels ## select random label, then select random un/matching pair of label ##------------------------------------------------------------ def get_selected_pair_indices (chips_d, matched_cnt, unmatched_cnt, triplet=0) : all_matched_pairs_arr = gen_all_matched_obj_pairs (chips_d) all_unmatched_pairs_3arr = gen_all_unmatched_obj_pairs (chips_d) selected_matched_list = [] selected_unmatched_list = [] label_cnt = len (chips_d) max_matched_cnt = sum ([len (pairs_list) for pairs_list in all_matched_pairs_arr]) max_unmatched_cnt = sum ([len (pairs_list) for pairs_arr in all_unmatched_pairs_3arr for pairs_list in pairs_arr]) # pdb.set_trace () if matched_cnt == 0 : matched_cnt = max_matched_cnt if matched_cnt > max_matched_cnt : print(' *** requesting more matched pairs than exists.') print(' *** creating max number of matched pairs.') matched_cnt = max_matched_cnt if unmatched_cnt == 0 : unmatched_cnt = max_unmatched_cnt if unmatched_cnt > max_unmatched_cnt : print(' *** requesting more unmatched pairs than exists.') print(' *** creating max number of unmatched pairs.') unmatched_cnt = max_unmatched_cnt # pdb.set_trace () # need to start with matched set to ensure there is a set i = 0 if matched_cnt == max_matched_cnt : # getting ALL matched pairs selected_matched_list = [pair for pair_list in all_matched_pairs_arr for pair in pair_list] i = matched_cnt while i < matched_cnt : x = random.randint(0,label_cnt-1) img_cnt = len (all_matched_pairs_arr[x]) if img_cnt == 0 : continue label_list = all_matched_pairs_arr[x] z = random.randint(0,img_cnt-1) # if looking for triplet, find unmatched set now if triplet > 0 : w = random.randint(0, 1) # pick one of 2 sets set1 = label_list[z][w] # anchor label_y = label_x = set1[0] while label_y == label_x : label_y = random.randint(0,label_cnt-1) if label_x > label_y : label_list_u = all_unmatched_pairs_3arr[label_y][label_x] else : label_list_u = all_unmatched_pairs_3arr[label_x][label_y] img_cnt_u = len (label_list_u) # need to find anchor set1 then move entry to selected found_match = False for u in range (img_cnt_u-1) : # pdb.set_trace () if set1 in label_list_u[u]: # take first match rather than find all and random select selected_unmatched_list.append (label_list_u.pop(u)) found_match = True break if not found_match : print('Unable to find unmatch set for anchor', set1, ', trying again.') continue selected_matched_list.append (label_list.pop(z)) i += 1 if triplet > 0 : return selected_matched_list, selected_unmatched_list i = 0 if unmatched_cnt == max_unmatched_cnt : # getting ALL unmatched pairs selected_unmatched_list = [pair for pairs_arr in all_unmatched_pairs_3arr for pair_list in pairs_arr for pair in pair_list] i = unmatched_cnt while i < unmatched_cnt : y = x = random.randint(0,label_cnt-1) while y == x : y = random.randint(0,label_cnt-1) if x > y : label_list = all_unmatched_pairs_3arr[y][x] else : label_list = all_unmatched_pairs_3arr[x][y] # pdb.set_trace () img_cnt = len (label_list) if img_cnt == 0 : continue z = random.randint(0,img_cnt-1) # move entry to selected selected_unmatched_list.append (label_list.pop(z)) i += 1 return selected_matched_list, selected_unmatched_list ##------------------------------------------------------------ ## create lists of chips pairs given indices in the form: ## [ ((l1, image1), (l2, image2)), ... ] ##------------------------------------------------------------ def create_chip_list (chips_d, indices) : chips_list = sorted (chips_d.items()) chips = [] # label, chips in chips_d.items(): for pair in indices : l1 = pair[0][0] i1 = pair[0][1] l2 = pair[1][0] i2 = pair[1][1] # print '((', l1, i1, '), (', l2, i2, '))' # l, 1, i : is to access the list of (label,chips) chip1 = chips_list[l1][1][i1] chip2 = chips_list[l2][1][i2] chips.append (chip1) chips.append (chip2) return chips ##------------------------------------------------------------ ## plot histogram of points, of nxn bins ##------------------------------------------------------------ def display_hist (noses): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # x, y = np.random.rand(2, 100) * 4 x = noses[0] y = noses[1] nbins = 10 hist, xedges, yedges = np.histogram2d(x, y, bins=nbins) # Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos, # ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid # with indexing='ij'. # xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25) plt.title ('nose histogram : ' + str (nbins) + ' bins.') xpos, ypos = np.meshgrid(xedges[:-1] + 1.0, yedges[:-1] + 1.0) xpos = xpos.flatten('F') ypos = ypos.flatten('F') zpos = np.zeros_like(xpos) # Construct arrays with the dimensions for the 16 bars. #dx = 0.5 * np.ones_like(zpos) dx = 1.0 * np.ones_like(zpos) dy = dx.copy() dz = hist.flatten() ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='y', zsort='average') # plt.show() ##------------------------------------------------------------ ## plot distance histogram from mean. ##------------------------------------------------------------ def get_dist_hist (noses, band_width=0): x_list = noses[0] y_list = noses[1] sorted_x = sorted (x_list) sorted_y = sorted (y_list) nose_x = sum (x_list) / len (x_list) nose_y = sum (y_list) / len (y_list) band_count = 30 if band_width == 0 : x_dist = sorted_x[-1] - sorted_x[0] y_dist = sorted_y[-1] - sorted_y[0] dist = math.sqrt (x_dist**2 + y_dist**2) band_width = int (dist/band_count) bands = [0] * (band_count + 1) # pdb.set_trace () for i in range (len (y_list)) : pt_x = x_list[i] pt_y = y_list[i] d = math.sqrt ((pt_x-nose_x)**2 + (pt_y-nose_y)**2) band = int (d/band_width) bands[band] += 1 print('nose count: ', len (x_list)) end = len (bands) - 1 # pdb.set_trace () for i in range (end, 0, -1) : if bands[i] : end = i+1 break cnt = 0 for i in range (len(bands)) : print('--- ', i, ':', bands[i]) cnt += bands[i] print('# bands : ', end) print('band width : ', band_width) print('total in bands : ', cnt) return band_width, bands[:end] ##------------------------------------------------------------ ## given dict of chips, return eyes and list of noses ##------------------------------------------------------------ # def get_face_stats (objs_d, verbose=1, filetype='chips'): def get_chip_face_stats (chips_d, verbose=1): x_list = [] y_list = [] # pdb.set_trace () get_reye = True get_leye = True all_chips = sorted(chips_d.items()) for key, chips in all_chips : ## list of chips for chip in chips : for part in chip.findall ('part'): name = part.attrib.get ('name') if get_leye : if name == "leye" : leye_x = int (part.attrib.get ('x')) leye_y = int (part.attrib.get ('y')) get_leye = False continue if get_reye : if name == "reye" : reye_x = int (part.attrib.get ('x')) reye_y = int (part.attrib.get ('y')) get_reye = False continue if name == "nose" : x = int (part.attrib.get ('x')) y = int (part.attrib.get ('y')) x_list.append (x) y_list.append (y) nose_x = sum (x_list) / len (x_list) nose_y = sum (y_list) / len (y_list) if verbose > 0 : print('average nose : ', nose_x, nose_y) print('median nose : ', np.median (x_list), np.median (y_list)) print('reye : ', reye_x, reye_y) print('leye : ', leye_x, leye_y) return [leye_x, leye_y], [reye_x, reye_y], [nose_x, nose_y], [x_list, y_list] ##------------------------------------------------------------ ## print pairs stats ##------------------------------------------------------------ def print_pairs_stats (objs_d, verbosity) : matched = 0 unmatched = 1 matched_list = objs_d[matched] unmatched_list = objs_d[unmatched] # pdb.set_trace () # get unique list of entries, then show count matched_labels = [label.text for label in matched_list] unmatched_labels = [(label[0].text, label[1].text) for label in unmatched_list] flatten_unmatched = [label for tupl in unmatched_labels for label in tupl] if verbosity > 1 : print('------------------------') print('--- matched stats:--- ') print('------------------------') for i in sorted (set (all_labels)): print(i, '\t,\t', matched_labels.count (i)) print('------------------------') print(' matched pairs: ', len (matched_labels)) if verbosity > 1 : print('------------------------') print('--- unmatched stats:--- ') print('------------------------') for i in sorted (set (all_labels)): print(i, '\t,\t', flatten_unmatched.count (i)) print('unmatched pairs: ', len (unmatched_labels)) ##------------------------------------------------------------ ## prints: ## min size, ## max size, ## resolution of min image, ## resoulution of max image ## count of each diffent types of images ## img.format (), img.size ##------------------------------------------------------------ def print_imgs_stats (img_files) : imgs_d = defaultdict(int) # print (len (img_files), ': ', img_files) for i in range (len (img_files)) : # all labels img = Image.open (img_files[i]) imgs_d [img.format] += 1 if img.format == 'MPO' : mpo_file = img_files[i] width, height = img.size size = width * height if i == 0 : min_size = size max_size = size min_img = img max_img = img min_img_file = img_files[i] max_img_file = img_files[i] if size < min_size : min_size = size min_img = img min_img_file = img_files[i] elif size > max_size : max_size = size max_img = img max_img_file = img_files[i] print ('min image : ', min_img_file) print ('resolution: ', min_img.width, min_img.height) print ('min size : ', min_size) print ('max image : ', max_img_file) print ('resolution: ', max_img.width, max_img.height) print ('max size : ', max_size) for img_format, count in imgs_d.items () : ## iterate through all chips print (img_format, ' : ', count) print ('\n\t MPO : ', mpo_file) return ##------------------------------------------------------------ ## return label stats in file ##------------------------------------------------------------ def get_obj_stats (filenames, print_files=False, filetype="chips", verbosity=1, write_stats=False, print_all=False): objs_d = defaultdict(list) objfiles = load_objs_from_files (filenames, objs_d, filetype) # pdb.set_trace () if filetype == "images" : print_imgs_stats (objfiles) return if filetype == "pairs" : print_pairs_stats (objs_d, verbosity) return print('') all_objs = sorted(objs_d.items()) img_cnt_per_label = [len (objs) for key, objs in all_objs] obj_count = sum (img_cnt_per_label) if verbosity > 1: for key, objs in all_objs : print (key, ':', len (objs)) if print_all : for label in sorted (set (all_labels)): if get_verbosity () > 2 or len (objs_d[label]) > 0 : print(label, ' :', len (objs_d[label])) u_combos = 0 chips_count_list = img_cnt_per_label diff_chip_count = obj_count # pdb.set_trace () for i in range (len (chips_count_list)-1) : # all labels i_count = len (all_objs[i][1]) # count of ith label diff_chip_count -= i_count # count of different labels u_combos += (i_count * diff_chip_count) print('-----------------------------') print(' total', filetype, ':', obj_count) print(' # bears :', len (chips_count_list)) if len (chips_count_list) > 0: print(' average', filetype, 'per bear :', obj_count / len (chips_count_list)) print(' median', filetype, 'per bear :', np.median (img_cnt_per_label)) combos = sum ([(n*(n-1)/2) for n in img_cnt_per_label if n > 1]) print(' possible matched sets :', combos) print('possible unmatched sets :', u_combos) # display_dist_hist (img_cnt_per_label, 2, 0, 'bear index', '# images') have_display = "DISPLAY" in os.environ if (get_verbosity () > 2) : if have_display: #plt.hist(img_cnt_per_label, len(objs_d)/5, facecolor='blue', alpha=0.5) hist_info = plt.hist(img_cnt_per_label, 20, facecolor='blue', alpha=0.5) plt.title('histogram of ' + filetype + ' count per bear') plt.xlabel('# chips per bear (total=' + str (obj_count) + ')') plt.ylabel('# bears (total=' + str (len (objs_d)) + ')') hist_obj_cnt_file = 'hist_obj_cnt.png' plt.savefig (hist_obj_cnt_file) print('\n--- histogram of image count written to: ', hist_obj_cnt_file, '\n') plt.show () if filetype == 'chips' : chip_sizes = [math.sqrt (int (res.text)) for key, chips in all_objs \ for chip in chips for res in chip.findall ('resolution')] print('\naverage face size (NxN): ', int (sum (chip_sizes)/len (chip_sizes))) print('median face size (NxN): ', int (np.median (chip_sizes))) plt.title ('histogram of of face sizes') plt.xlabel ('N (image size=NxN)') plt.ylabel ('# chips (total=' + str (obj_count) + ')' ) hist_info = plt.hist (chip_sizes, 20, facecolor='green', alpha=0.5) hist_chip_sizes_file = 'hist_chip_sizes.png' plt.savefig (hist_chip_sizes_file) print('\n--- histogram of chip sizes written to: ', hist_chip_sizes_file, '\n') plt.show () tiny_chips = [chip for key, chips in all_objs \ for chip in chips for res in chip.findall ('resolution') if int (res.text) < 22500] chip.attrib.get ('file') tiny_chips_names = [chip.attrib.get ('file') for chip in tiny_chips] # pdb.set_trace () else : print('\n *** unable to show histogram: no access to display. *** \n') if filetype == 'faces': print_faces_stats (write_stats) if print_files : objfiles.sort () for objfile in objfiles: print('\t', objfile) ##------------------------------------------------------------ ##------------------------------------------------------------ ##------------------------------------------------------------ def is_png (image_file) : imgfile_base, imgfile_ext = os.path.splitext (image_file) if imgfile_ext.lower() == '.png' : return True else : return False ##------------------------------------------------------------ # get_YMDT_from_date - returns year, month, day and time from string # like: "2014:10:13 13:57:50" ##------------------------------------------------------------ def get_YMDT_from_date (image_datetime) : # pdb.set_trace () if image_datetime is None: return 0, 0, 0, 0 image_year = image_datetime[:4] image_month = image_datetime[5:7] image_day = image_datetime[8:10] image_time = image_datetime[11:13] + image_datetime[14:16] + image_datetime[17:19] return image_year, image_month, image_day, image_time ##------------------------------------------------------------ ##------------------------------------------------------------ def get_image_creation_datetime (image_file): # pdb.set_trace () if is_png (image_file) : return '' print ('image: ', image_file) img = Image.open (image_file) exif_data = img._getexif () if exif_data != None : date = exif_data.get (36867) return date else : return '' ##------------------------------------------------------------ ##------------------------------------------------------------ def get_photo_source (image_file): label_path = os.path.dirname (image_file) source_path = os.path.dirname (label_path) source_split = os.path.split (source_path) return source_split [1] ##------------------------------------------------------------ ##------------------------------------------------------------ def get_image_size (image_file): img = Image.open (image_file) w,h = img.size return w * h ##------------------------------------------------------------ ##------------------------------------------------------------ def get_orig_img_by_name (image_file, cur_str, orig_str): str_index = image_file.find (cur_str) if str_index > 0 : orig_image_file = image_file.replace (cur_str, orig_str) if not os.path.exists (orig_image_file) : print (' Warning: orig image ', orig_image_file, 'does not exist') return orig_image_file return '' ##------------------------------------------------------------ ## trim path n directories from top level ## e.g. /a/b/c/d/e/f/g.ext, 4 -> e/f/g.ext ##------------------------------------------------------------ def trim_path_start (pathname, dir_depth) : path = pathname for i in range (dir_depth) : path = os.path.dirname (path) # pdb.set_trace () path += '/' rel_pathname = pathname.replace (path, '') return rel_pathname ##------------------------------------------------------------ ## leave path with n directories from basename ## e.g. /a/b/c/d/e/f/g.ext, 1 -> f/g.ext ##------------------------------------------------------------ def trim_path_end (pathname, dir_depth) : path = pathname newpath = os.path.basename (path) for i in range (dir_depth) : path = os.path.dirname (path) cur_dir = os.path.basename (path) newpath = cur_dir + '/' + newpath # pdb.set_trace () return newpath ##------------------------------------------------------------ ##------------------------------------------------------------ def get_nose_xy (chip_tag): for part in chip_tag.findall ('part'): name = part.attrib.get ('name') if name == "nose" : nose_x = int (part.attrib.get ('x')) nose_y = int (part.attrib.get ('y')) return nose_x, nose_y ##------------------------------------------------------------ ##------------------------------------------------------------ def get_face_size (image_tag): # pdb.set_trace () box = image_tag.find ('box') if box is None: return 0 height = box.attrib.get ('height') width = box.attrib.get ('width') if height and width : face_size = int (height) * int (width) else: face_size = 0 return face_size ##------------------------------------------------------------ ## return string with content: ## file, label, date, size, photo_source, ## nose_xy, nose_source_file, orig_image, permission?, age ##------------------------------------------------------------ def gen_image_csv_str (image_tag): # pdb.set_trace () image_label = get_obj_label_text (image_tag) image_file = image_tag.attrib.get ('file') image_datetime = get_image_creation_datetime (image_file) image_year, image_month, image_day, image_time = get_YMDT_from_date (image_datetime) photo_source = get_photo_source (image_file) image_size = get_image_size (image_file) face_size = get_face_size (image_tag) image_date = image_year + image_month + image_day if get_verbosity () > 1 : print ('file : ', image_file) print ('label : ', image_label) print ('date : ', image_datetime) print ('source : ', photo_source) print ('size : ', image_size) print('-----------------------------') csv_str = trim_path_start (image_file, 5) csv_str += ';' + image_label csv_str += ';' + str (image_date) csv_str += ';' + str (image_year) csv_str += ';' + str (image_month) csv_str += ';' + str (image_day) csv_str += ';' + str (image_time) csv_str += ';' + str (image_size) csv_str += ';' + trim_path_start (photo_source, 5) csv_str += ';' + str (face_size) csv_header = 'IMAGE;LABEL;DATE;YEAR;MONTH;DAY;TIME;SIZE;PHOTO_SOURCE;FACE_SIZE' return csv_str, csv_header ##------------------------------------------------------------ ## return string with content: ## file, label ##------------------------------------------------------------ def gen_svm_csv_str (image_tag): # pdb.set_trace () image_label = get_obj_label_text (image_tag) image_file = image_tag.attrib.get ('file') truth_label = get_truth_label (image_file) if truth_label == image_label : match = '1' else : match = '0' if get_verbosity () > 1 : print ('file : ', image_file) print ('label : ', image_label) print('-----------------------------') csv_str = trim_path_start (image_file, 5) csv_str += ';' + image_label csv_str += ';' + truth_label csv_str += ';' + match csv_header = 'IMAGE;PREDICT;TRUTH_LABEL;MATCH' return csv_str, csv_header ##------------------------------------------------------------ ## return string with content: ## file, label, size, ## nose_xy, orig_image ##------------------------------------------------------------ def gen_chip_csv_str (chip_tag): image_file = chip_tag.attrib.get ('file') image_label = get_obj_label_text (chip_tag) image_size = get_image_size (image_file) orig_file = get_chip_source_file (chip_tag) nose_x, nose_y = get_nose_xy (chip_tag) if get_verbosity () > 1 : print ('file : ', image_file) print ('label : ', image_label) print ('size : ', image_size) print ('orig_file : ', orig_file) print ('nose_xy : ', nose_x, nose_y) print('-----------------------------') csv_str = trim_path_start (image_file, 5) csv_str += ';' + image_label csv_str += ';' + str (image_size) csv_str += ';' + trim_path_start (orig_file, 5) csv_str += ';' + str (nose_x) + ' ' + str (nose_y) csv_str += ';' + str (nose_x) csv_str += ';' + str (nose_y) csv_header = 'IMAGE;LABEL;SIZE;ORIG_IMAGE;NOSE_XY;NOSE_X;NOSE_Y' return csv_str, csv_header ##------------------------------------------------------------ ## return string with content: ## file, label, date, size ## nose_xy, nose_source_file, orig_image, permission?, age ##------------------------------------------------------------ def gen_derived_image_csv_str (image_tag): image_label = get_obj_label_text (image_tag) image_file = image_tag.attrib.get ('file') image_size = get_image_size (image_file) orig_image = get_orig_img_by_name (image_file, 'imageSourceSmall', 'imageSource') permission = '' face_size = get_face_size (image_tag) age = '' if get_verbosity () > 1 : print ('file : ', image_file) print ('label : ', image_label) print ('size : ', image_size) print ('orig : ', orig_image) print('-----------------------------') csv_str = trim_path_start (image_file, 5) csv_str += ';' + image_label csv_str += ';' + str (image_size) csv_str += ';' + trim_path_start (orig_image, 5) csv_str += ';' + str (face_size) csv_header = 'IMAGE;LABEL;SIZE_RESIZED;ORIG_IMAGE;FACE_SIZE_RESIZED' return csv_str, csv_header ##------------------------------------------------------------ ## write csv file of image info containing: ## filename, label, date, location??, source (level above label) ##------------------------------------------------------------ def write_image_info_csv (filenames, outfile, filetype): objs_d = defaultdict(list) objtype = filetype if objtype == 'derived_faces' or objtype == 'svm': objtype = 'faces' objfiles = load_objs_from_files (filenames, objs_d, objtype) csv_fp = open (outfile, "w") # images, derived_image: images/image # chips: chips/chip # pdb.set_trace () header = '' first = True for label, tags in list(objs_d.items ()) : for tag in tags: # pdb.set_trace () if filetype == 'faces' : image_csv, csv_header = gen_image_csv_str (tag) elif filetype == 'derived_faces' : image_csv, csv_header = gen_derived_image_csv_str (tag) elif filetype == 'chips' : image_csv, csv_header = gen_chip_csv_str (tag) elif filetype == 'svm' : image_csv, csv_header = gen_svm_csv_str (tag) if first : csv_fp.write (csv_header + '\n') first = False csv_fp.write (image_csv + '\n') csv_fp.close () print("... generated file:", outfile) if len (csv_header) : print("... header: ", csv_header) ##------------------------------------------------------------ ## write html of bear info: image, label/name, date, and dataset ## color coded for train (green) vs test (red) ## expects 4 columns: image, label, date, dataset ## # <hr style="width:50%">beatrice 2020<br> # resulting string for each image: # <img src="/home/data/bears/imageSource/britishColumbia/melanie_20170828/bc_beatrice/IMG_5056.JPG" # width"200" height="300" style="border:5px solid green;" alt="beatrice" > ##------------------------------------------------------------ def html_image_info_from_csv (csv_file, html_outfile, delim=';') : with open (csv_file) as csv_file: csv_reader = csv.reader (csv_file, delimiter=delim) ## expects 4 columns: image, label, date, dataset # TODO: open file for writing html_fp = open (html_outfile, "w") label = '' date = '' for row in csv_reader: # pdb.set_trace () new_label = row[1] new_date = row[2] border_color = 'green' if row[3] == 'train' else 'red' if new_label != label or new_date != date : label = new_label date = new_date html_fp.write ('<hr style="width:50%">' + new_label + ' ' + new_date + ' <br>\n') img_tag = '<img src="/home/data/bears/' + row[0] + '" ' img_tag += 'style="border:5px solid ' + border_color + '; max-width:250px; max-height:250px;" alt="' + label + '" >\n' html_fp.write (img_tag) html_fp.close () print ("... wrote html to file: ", html_outfile) ##------------------------------------------------------------ ## write html of embedding and its correct matched ## color coded for train vs test ## format: label;distance; ## date1;time1; date2;time2; ## image1;image2; chip1;chip2; ## match ## # breaks between matches: # <hr style="width:50%">beatrice 2020<br> # resulting string for each image: # <img src="/home/data/bears/imageSource/britishColumbia/melanie_20170828/bc_beatrice/IMG_5056.JPG" # width"200" height="300" style="border:5px solid green;" alt="beatrice" > ##------------------------------------------------------------ def html_matched_image_info_from_csv (csv_file, html_outfile, delim=';') : with open (csv_file) as csv_file: csv_reader = csv.reader (csv_file, delimiter=delim) ## format: label;distance; ## date1;time1; date2;time2; ## image1;image2; chip1;chip2 html_fp = open (html_outfile, "w") for row in csv_reader: # pdb.set_trace () label = row[0] distance = row[1] date1 = row[2] time1 = row[3] date2 = row[4] time2 = row[5] image1 = row[6] image2 = row[7] chip1 = row[8] chip2 = row[9] datematch = row[10] border_color = 'green' if int (datematch) == 1 : border_color = 'red' img_close = 'style="border:5px solid ' + border_color + '; max-width:250px; max-height:250px;" alt="' + label + '" >\n' html_fp.write ('<hr style="width:50%">' + label + '&emsp; &emsp;' + distance + ' <br>\n') html_fp.write ('<hr style="width:50%">' + date1 + ':' + time1 + '&emsp; &emsp;' + date2 + ':' + time2 + ' <br>\n') img_tag = '<img src="' + image1 + '" ' + img_close img_tag += '<img src="' + image2 + '" ' + img_close img_tag += '<img src="' + chip1 + '" ' + img_close img_tag += '<img src="' + chip2 + '" ' + img_close html_fp.write (img_tag) html_fp.close () print ("... wrote html to file: ", html_outfile) ##------------------------------------------------------------ ## write html of images in file ## # resulting string for each image: # <img src="/home/data/bears/imageSource/britishColumbia/melanie_20170828/bc_beatrice/IMG_5056.JPG" # width"200" height="300" style="border:5px solid green;" alt="beatrice" > ##------------------------------------------------------------ def html_images (text_file, html_outfile) : html_fp = open (html_outfile, "w") with open (text_file) as fp: img_files = fp.readlines () border_color = 'green' for img_file in img_files: if not img_file.strip() : continue img_tag = '<img src="' + img_file.strip () + '" ' img_tag += 'style="border:5px solid ' + border_color + '; max-width:250px; max-height:250px;" >\n' html_fp.write (img_tag) html_fp.close () print ("... wrote html to file: ", html_outfile) ##------------------------------------------------------------ ## cur_datetime - returns YYYYMMDDHHMM ##------------------------------------------------------------ def current_datetime () : return datetime.datetime.now().strftime("%Y%m%d%H%M") ##------------------------------------------------------------ ## ##------------------------------------------------------------ def print_faces_stats (write_unused_images) : print("-----------------------------") print("....# files with no faces : ", len (g_stats_zero)) print("....# files with multiple faces: ", len (g_stats_many)) # pdb.set_trace () if write_unused_images: if len (g_stats_zero) : stats_name = datetime.datetime.now().strftime("stats_zero_%Y%m%d_%H%M") stats_fp = open (stats_name, "w") for face in g_stats_zero: stats_fp.write (face + '\n') stats_fp.close () print("... generated file:", stats_name) if len (g_stats_many) : stats_name = datetime.datetime.now().strftime("stats_many_%Y%m%d_%H%M") stats_fp = open (stats_name, "w") for face in g_stats_many: stats_fp.write (face + '\n') stats_fp.close () print("... generated file:", stats_name) print('') ##------------------------------------------------------------ ## return xml files in directory ##------------------------------------------------------------ def get_xml_files (dir) : xml_files = [] for dirname, dirs, files in os.walk (dir): # print "files: ", files for file in files: if (file.endswith ('.xml')): xml_files.append (os.path.join(dirname, file)) # print "file: ", file # pdb.set_trace () return xml_files ##------------------------------------------------------------ ## write list of images into output_file xml ##------------------------------------------------------------ def create_imgs_xml (img_list, output_file) : img_files = get_img_files (img_list) root, images_tag = create_new_tree_w_element ('images') # pdb.set_trace () for img_file in img_files : image_tag = ET.SubElement (images_tag, 'image') image_tag.set ('file', str (img_file)) indent (root) tree = ET.ElementTree (root) tree.write (output_file) print('\n\tGenerated images file: ', output_file) ##------------------------------------------------------------ ## return images files in (sub)directories ##------------------------------------------------------------ def get_img_files (filenames, abs_path=True) : # pdb.set_trace () # print ('getting images for', filenames) img_files = [] pathed_dirs = [] for filename in filenames : if abs_path : filename = os.path.abspath (filename) for root, dirs, files in os.walk (filename) : pathed_dirs = [os.path.join (root, dir) for dir in dirs] get_img_files (pathed_dirs) matched_imgs = get_dirs_images (files) pathed_imgs = [os.path.join (root, img) for img in matched_imgs] # pdb.set_trace () img_files.extend (pathed_imgs) return img_files ##------------------------------------------------------------ ## get box ##------------------------------------------------------------ def get_box (image_tag) : box_d = defaultdict () for box in image_tag.findall ('box') : # TODO : multiple?? for part in g_box_attrs : box_d[part] = box.attrib.get (part) return box_d ##------------------------------------------------------------ ## get shape parts ##------------------------------------------------------------ def get_shape_parts (image_tag) : parts_d = defaultdict () for box in image_tag.findall ('box') : # TODO : multiple?? parts = box.findall ('part') # pdb.set_trace () for part in parts : name = part.attrib.get ('name') if name in g_shape_parts_find : if name == 'head_top' or name == 'htop' : ## tmp fix for erroneous 'head_top' name = 'head_top' x = part.attrib.get ('x') y = part.attrib.get ('y') parts_d[name] = {x, y} return parts_d ##------------------------------------------------------------ ## diff objs ##------------------------------------------------------------ def obj_equal (obj1, obj2, parts) : for part in parts : if obj1[part] != obj2[part] : return False return True ##------------------------------------------------------------ ## returns true if box and parts of the two tags match ##------------------------------------------------------------ def diff_image_tags (image1, image2) : box_1 = get_box (image1) parts_1 = get_shape_parts (image1) box_2 = get_box (image2) parts_2 = get_shape_parts (image2) filename1 = obj_get_filename (image1) filename2 = obj_get_filename (image2) # print ('\ncomparing content for : ') # print ('\t', filename1) # print ('\t', filename2) if not obj_equal (box_1, box_2, g_box_attrs) : return False if not obj_equal (parts_1, parts_2, g_shape_parts) : return False return True ##------------------------------------------------------------ ## returns name of label. assumes 1 box, 1 label. does no err checks ##------------------------------------------------------------ def get_obj_label_text (obj_tag) : if obj_tag.tag == 'image' : label_tag = obj_tag.find ('box/label') # box_tag = obj_tag.find ('box') # label_tag = box_tag.find ('label') elif obj_tag.tag == 'chip' : label_tag = obj_tag.find ('label') return label_tag.text ##------------------------------------------------------------ ## returns golden label, parsed from directory path ##------------------------------------------------------------ def get_truth_label (filename) : path = os.path.dirname (filename) label = os.path.basename (path) return label ##------------------------------------------------------------ ## given chip tag, return name of source file. ##------------------------------------------------------------ def get_chip_source_file (chip_tag) : # pdb.set_trace () source_tag = chip_tag.find ('source') if source_tag is None: return '' source_file = source_tag.attrib.get ('file') return source_file ##------------------------------------------------------------ ## get_new_face (face,faces_orig_d). find matching file name ##------------------------------------------------------------ def get_new_face (face, faces_new_d) : imagefile_old = face.attrib.get ('file') label_old = get_obj_label_text (face) pdb.set_trace () for label_new, faces in list(faces_new_d.items ()) : if label_old != label_new : continue; # look for file name for face in faces : imagefile_new = face.attrib.get ('file') if imagefile_new == imagefile_old : return face return None ##------------------------------------------------------------ ## validate_file - create new file with only valid chip files ##------------------------------------------------------------ def validate_file (xml_file, output_file) : chips_d = defaultdict (list) filetype = 'chips' objfiles = load_objs_from_files ([xml_file], chips_d, filetype) valid_chips = [] print('') for key, chips in list(chips_d.items ()) : ## iterate through all chips for chip in chips : # pdb.set_trace () chipfile = chip.attrib.get ('file') if os.path.exists (chipfile) : valid_chips.append (chip) else : print('\t...unable to find file: ', chipfile) print('\n\tGenerated valid chip file: ', output_file) print('') root, tree = create_new_tree_w_element (filetype) for chip in valid_chips : tree.append (chip) indent (root) tree = ET.ElementTree (root) tree.write (output_file) ##------------------------------------------------------------ ## find matching image (face,faces_orig_d). ## returns matched image_tag ##------------------------------------------------------------ def get_matching_image (image_file, images_d) : for l , image_tags in list(images_d.items ()) : # ignores label, which is only accurate during testing # look for file name for image_tag in image_tags : image_file_2 = image_tag.attrib.get ('file') if image_file == image_file_2 : return image_tag return None ##------------------------------------------------------------ ## return file for xml tag ##------------------------------------------------------------ def obj_get_filename (xml_tag) : filename = xml_tag.attrib.get ('file') return filename ##------------------------------------------------------------ ## remove image_tag from dict ##------------------------------------------------------------ def remove_image_tag (image_file, images_d) : for l , image_tags in list(images_d.items ()) : # ignores label, which is only accurate during testing # look for file name for i in range (len (image_tags)) : image_file_2 = obj_get_filename (image_tags[i]) if image_file == image_file_2 : del image_tags[i] return True return False ##------------------------------------------------------------ ## diff_face_files . check for matching images, box, parts ##------------------------------------------------------------ def diff_face_files (xml1, xml2) : images1_d = defaultdict(list) images2_d = defaultdict(list) filetype = "faces" print ('\ncomparing files: ', xml1, ' ', xml2) objfiles1 = load_objs_from_files ({xml1}, images1_d, filetype) objfiles2 = load_objs_from_files ({xml2}, images2_d, filetype) newfaces = [] images_one_only = [] images_mismatch = [] images_two_only = [] for label, images1 in list(images1_d.items ()) : ## iterate through all images for image1 in images1 : # pdb.set_trace () image_filename = obj_get_filename (image1) image2 = get_matching_image (image_filename, images2_d) if image2 is None : print ("no image match for ", image_filename) images_one_only.append (image1) continue match = diff_image_tags (image1, image2) if not match : print ("content mismatch for ", image_filename) images_mismatch.append (image1) remove_image_tag (image_filename, images2_d) continue # here only if found mathcing box and parts, remove match image2 from list remove_image_tag (image_filename, images2_d) for label, images2 in list(images2_d.items ()) : ## go through dict and make a list for image2 in images2 : images_two_only.append (image2) one_only_filename = 'images_one_only.xml' two_only_filename = 'images_two_only.xml' mismatch_filename = 'images_mismatch.xml' write_xml_file (one_only_filename, images_one_only, filetype) write_xml_file (two_only_filename, images_two_only, filetype) write_xml_file (mismatch_filename, images_mismatch, filetype) print ("writing files:") print ("\t", one_only_filename) print ("\t", two_only_filename) print ("\t", mismatch_filename) ##------------------------------------------------------------ ## xml_to_list - return list of files from xml ##------------------------------------------------------------ def xml_to_list (xml_file, filetype='faces') : xml_obj_d = default_dict (list) img_files = load_objs_from_files (xml_file, xml_obj_d, filetype) return img_files ##------------------------------------------------------------ ## find_files_from_patterns - return list of all matched files (not obj) ## using pattern from str_list. ## NOTE: pattern will match substring of filename, not only full strings ## e.g. pattern bc_n will match bc_neana and bc_no-tail ## TODO: can expand to use regex. ##------------------------------------------------------------ def find_files_from_patterns (filenames, patterns, filetype='faces') : matched = [] for filename in filenames : for string in patterns: # import re # match = re.search (string, filename) # if match : if string.lower () in filename.lower () : matched.append (string) return matched ##------------------------------------------------------------ # given xmls, write out filenames for all objects ##------------------------------------------------------------ def xml_to_files (xml_files, outfile, filetype, filename_type='file') : objs_d = defaultdict(list) # pdb.set_trace () source_filenames = load_objs_from_files (xml_files, objs_d, filetype, filename_type) outfile_fp = open (outfile, "w") for filename in source_filenames : outfile_fp.write (filename + '\n') outfile_fp.close () ##------------------------------------------------------------ ## xml_split_by_files - write matched and unmatched ## xml files given file of strings for matching ##------------------------------------------------------------ def xml_split_by_files (xml_files, split_file, outfile, filetype='faces', type_split='files', multi_ok=True) : objs_d = defaultdict(list) set_multi_ok (multi_ok) source_filenames = load_objs_from_files (xml_files, objs_d, filetype) # pdb.set_trace () with open (split_file, 'r') as fp: filenames_raw = fp.readlines () filenames = [filename.strip() for filename in filenames_raw] filename_type = 'file' # if filetype == 'chips' : # filename_type = 'source' matched_objs, unmatched_objs = obj_split (objs_d, filenames, filename_type, type_split) matched_filename = outfile + '_matched' + '.xml' unmatched_filename = outfile + '_unmatched' + '.xml' many_filename = outfile + '_multi' + '.xml' zero_filename = outfile + '_zero' + '.xml' write_xml_file (matched_filename, matched_objs, filetype) write_xml_file (unmatched_filename, unmatched_objs, filetype) write_xml_file (many_filename, g_objs_many , filetype) write_xml_file (zero_filename, g_objs_zero, filetype) print('unmatched', filetype, 'written to :', unmatched_filename) print(' matched', filetype, 'written to :', matched_filename) print(' many', filetype, 'written to :', many_filename) print(' zero', filetype, 'written to :', zero_filename) ##------------------------------------------------------------ ## xml_split_by_xml - write matched and unmatched ## xml given xml file for matching. filetype of two ## input xml must be the same. ##------------------------------------------------------------ def xml_split_by_xml (xml_file, split_xml_file, outfile, filetype='faces', type_split='files') : objs_d = defaultdict(list) split_filenames = load_objs_from_files (split_xml_file, objs_d, filetype) xml_split_by_files (xml_file, split_filenames, outfile, filetype, type_split) ##------------------------------------------------------------ ## obj_split - return list of matched and unmatched ## objs given type_split. ## if filename_type == 'source', get the source filename ## obj to compare against list ## only matches full strings when spliting by files ## matches substring when split by pattern. e.g. pattern '_chip_0' ## will matching all filenames that contains '_chip_0' like ## '/data/images/chips/IMG_0001_chip_0' ##------------------------------------------------------------ def obj_split (objs_d, filenames, filename_type='file', type_split='files') : matched_objs = [] unmatched_objs = [] # pdb.set_trace () if type_split == 'files' : for label, objs in list(objs_d.items ()) : ## iterate through objs for obj in objs : # pdb.set_trace () if filename_type == 'source' : obj_filename = get_chip_source_file (obj) else : obj_filename = obj_get_filename (obj) if obj_filename in filenames : matched_objs.append (obj) else : unmatched_objs.append (obj) ## --------------- need to test ------------ ## TODO: implement pattern match elif type_split == 'patterns' : split_patterns = filenames for label, objs in list(objs_d.items ()) : ## iterate through objs for obj in objs : # pdb.set_trace () if filename_type == 'source' : obj_filename = get_chip_source_file (obj) else : obj_filename = obj_get_filename (obj) for pattern in split_patterns : if pattern in obj_filename : matched_objs.append (obj) else : unmatched_objs.append (obj) else: print ('Error: Unimplemented split option:', type_split) return matched_objs, unmatched_objs ##------------------------------------------------------------ ## ## ## ##------------------------------------------------------------ ##------------------------------------------------------------ ## xml_split_by_list update_path - create file of same list of images with new data ##------------------------------------------------------------ def xml_split_by_list (orig_file, new_files, output_file, filetype='faces') : a = 5 ##------------------------------------------------------------ ## update_path - create file of same list of images with new data ##------------------------------------------------------------ def update_path (orig_file, new_files, output_file, filetype='faces') : faces_orig_d = defaultdict(list) faces_new_d = defaultdict(list) objfiles1 = load_objs_from_files (orig_file, faces_orig_d, filetype) objfiles2 = load_objs_from_files (new_files, faces_new_d, filetype) newfaces = [] for key, faces in list(faces_orig_d.items ()) : ## iterate through old list of tests for face in faces : # pdb.set_trace () newface = get_new_face (face, faces_new_d) ## get new data for same file if newface : newfaces.append (newface) else : print('unable to match file: ', face.attrib.get ('file')) root, tree = create_new_tree_w_element (filetype) for face in newfaces : tree.append (face) indent (root) tree = ET.ElementTree (root) tree.write (output_file) ##------------------------------------------------------------ ## convert a string to floats for each label ##------------------------------------------------------------ def str_to_float (floats_str) : float_list = [] float_strs = floats_str.split () for float_str in float_strs: f = float (float_str) float_list.append (f) return float_list ##------------------------------------------------------------ ## plot embeddings ##------------------------------------------------------------ def write_embed_tsv (input_files) : embeds_d = defaultdict(list) load_objs_from_files (input_files, embeds_d, 'embeddings') label_list = [] embeds_list = [] for label, embeds in sorted(embeds_d.items()): ## list of embeds for embed in embeds : embeds_list.append (embed) label_list.append (label) embeds_tsv_file = open ("embeds.tsv", "w") labels_tsv_file = open ("labels.tsv", "w") for i in range(len (embeds_list)): embeds_tsv_file.write ('\t'.join (str(x) for x in embeds_list[i])) embeds_tsv_file.write ('\n') labels_tsv_file.write (label_list[i]) labels_tsv_file.write ('\n') embeds_tsv_file.close () labels_tsv_file.close () print ("generated tsv files: ") print ("\tembeds.tsv") print ("\tlabels.tsv") # print ('\t'.join (str(x) for x in embeds_list[0])) ##------------------------------------------------------------ ## plot embeddings ##------------------------------------------------------------ def plot_embeddings (input_files) : embeds_d = defaultdict(list) load_objs_from_files (input_files, embeds_d, 'embeddings') label_list = [] embeds_list = [] for label, embeds in sorted(embeds_d.items()): ## list of embeds for embed in embeds : embeds_list.append (embed) label_list.append (label) tsne = TSNE(n_components=2, random_state=0, perplexity=5, learning_rate=10, method='exact', n_iter=2000) features = np.array(embeds_list) X_2d = tsne.fit_transform(features) label_list_set = set (label_list) target_names = list (label_list_set) target_names.sort () target_ids = range(len(target_names)) y = np.array (label_list) pdb.set_trace () have_display = "DISPLAY" in os.environ if have_display: plt.figure() ax = plt.subplot (111) markers = 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', '^', '^', '^', '^', '^', '^', '^', '^' colors = 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w' for i, c, label, m in zip(target_ids, colors, target_names, markers): # print (i, ' ', c, ' ', label) ax.scatter(X_2d[y == label, 0], X_2d[y == label, 1], c=c, label=label, marker=m, s=100) # pdb.set_trace () chartBox = ax.get_position () plt.tight_layout() ax.set_position ([chartBox.x0, chartBox.y0, chartBox.width*0.90, chartBox.height]) ax.legend(bbox_to_anchor=(0.87,1.0),loc='upper left', ncol=1, scatterpoints=1) plt.xticks([]) plt.yticks([]) plt.savefig('emb.png') plt.show() else: print ('\n\tUnable to plot, no display detected.\n') # print ('\t'.join (str(x) for x in embeds_list[0])) ##------------------------------------------------------------------------------ ##------------------------------------------------------------------------------ #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def get_bear_count (res, image_np, min_score, do_display=False) : have_display = "DISPLAY" in os.environ display = have_display and do_display dim = image_np.shape width = dim[1] height = dim[0] bear_cnt = 0 if display : fig,ax = plt.subplots(1) # Display the image ax.imshow(image_np) boxes = res.json()['predictions'][0]['detection_boxes'] scores = res.json()['predictions'][0]['detection_scores'] classes = res.json()['predictions'][0]['detection_classes'] detections = int(res.json()['predictions'][0]['num_detections']) for i in range(detections): label = coco_classes_d [int (classes[i])] if (scores[i] < float (min_score)): # print('Scores too low below ', i) break if label == 'bear' : bear_cnt += 1 else : continue # print(' Class', label, 'Score', scores[i]) ymin = int(boxes[i][0] * height) xmin = int(boxes[i][1] * width) ymax = int(boxes[i][2] * height) xmax = int(boxes[i][3] * width) b_width = xmax-xmin b_height = ymax-ymin # print('\t', boxes[i], end='') # print(xmin, ymin, b_width, b_height) # Create a Rectangle patch rect = patches.Rectangle((xmin,ymin),b_width,b_height,linewidth=1,edgecolor='r',facecolor='none') # Add the patch to the Axes if (display) : ax.add_patch(rect) if (display) : plt.show() return bear_cnt #------------------------------------------------------------------------------- def do_obj_count (result, image_np, min_score, objs, objs_d) : obj_cnt = 0 boxes = result.json()['predictions'][0]['detection_boxes'] scores = result.json()['predictions'][0]['detection_scores'] classes = result.json()['predictions'][0]['detection_classes'] detections = int(result.json()['predictions'][0]['num_detections']) for i in range(detections): label = objs_d [int (classes[i])] if (scores[i] < float (min_score)): # scored are ordered print('Scores too low below ', i) break if label in objs : obj_cnt += 1 return obj_cnt #------------------------------------------------------------------------------- def get_rect (dim, box, color='r') : width = dim[1] height = dim[0] ymin = int(box[0] * height) xmin = int(box[1] * width) ymax = int(box[2] * height) xmax = int(box[3] * width) b_width = xmax-xmin b_height = ymax-ymin # Create a Rectangle patch rect = patches.Rectangle((xmin,ymin),b_width,b_height,linewidth=1,edgecolor=color,facecolor='none') return rect #------------------------------------------------------------------------------- # given list of tf detections in result, extract count of labels for each detection # return list of detection count #------------------------------------------------------------------------------- def get_obj_count (result, image_np, min_score, labels, do_display=False) : have_display = "DISPLAY" in os.environ display = have_display and do_display dim = image_np.shape if display : fig,ax = plt.subplots(1) ax.imshow(image_np) result_cnt = len (result.json()['predictions']) matched_detects = [] for j in range (result_cnt) : boxes = result.json()['predictions'][j]['detection_boxes'] scores = result.json()['predictions'][j]['detection_scores'] classes = result.json()['predictions'][j]['detection_classes'] detections = int(result.json()['predictions'][j]['num_detections']) obj_cnt = 0 # pdb.set_trace () for i in range(detections): label = object_classes_d [int (classes[i])] if (scores[i] < float (min_score)): # print('Scores too low below ', i) break if label in labels : obj_cnt += 1 print(' Class', label, 'Score', scores[i]) # pdb.set_trace () rect = get_rect (dim, boxes[i], 'r') # Add the patch to the Axes if (display) : ax.add_patch(rect) matched_detects.append (obj_cnt) if (display) : plt.show() return matched_detects #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def img_find_bears (img_file, min_score, labels) : image = Image.open(img_file) image_np = np.array(image) payload = {"instances": [image_np.tolist()]} result = requests.post("http://localhost:8080/v1/models/default:predict", json=payload) bear_cnts = get_obj_count (result, image_np, min_score, labels, True) return bear_cnts #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def imgs_find_bears (img_files, min_score, labels) : img_list = [] for img_file in img_files : image = Image.open(img_file) image_np = np.array(image) img_list.append (image_np.tolist ()) payload = {"instances": img_list} result = requests.post("http://localhost:8080/v1/models/default:predict", json=payload) # pdb.set_trace () bear_cnts = get_obj_count (result, image_np, min_score, labels, True) return bear_cnts #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def do_find_bears (filename, out_file, min_score, model) : if model == 'tf-frcnn' : ids = coco_ids classes = coco_classes labels = ['bear'] else : # megadetector ids = md_ids classes = md_classes labels = ['animal'] for i in range (len (ids)) : object_classes_d[ids[i]] = classes[i] out_fp0 = open (out_file+'_0', "w") out_fp1 = open (out_file+'_1', "w") out_fpmulti = open (out_file+'_multi', "w") expected_cnt = 1 with open (filename, 'r') as fp: img_files = fp.readlines () for img_file in img_files : print ('counting bears for ', img_file) bear_cnts = img_find_bears (img_file.strip(), min_score, labels) bear_cnt = bear_cnts[0] # pdb.set_trace () # if bear_cnt > expected_cnt : if bear_cnt == 0 : out_fp0.write (str (img_file)) out_fp0.write ("\n") elif bear_cnt == 1 : out_fp1.write (str (img_file)) out_fp1.write ("\n") else : out_fpmulti.write (str (img_file)) out_fpmulti.write ("\n") print (bear_cnt, 'bears:', img_file) print ('\n\tGenerated files: ', out_file, '_{0,1,multi}') print ('\n') out_fp0.close () out_fp1.close () out_fpmulti.close () #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def do_find_bears_batch (filename, out_file, min_score, model) : if model == 'tf-frcnn' : ids = coco_ids classes = coco_classes labels = ['bear'] else : # megadetector ids = md_ids classes = md_classes labels = ['animal'] for i in range (len (ids)) : object_classes_d[ids[i]] = classes[i] out_fp0 = open (out_file+'_b_0', "w") out_fp1 = open (out_file+'_b_1', "w") out_fpmulti = open (out_file+'_b_multi', "w") expected_cnt = 1 with open (filename, 'r') as fp: img_files_raw = fp.readlines () img_files = [filename.strip() for filename in img_files_raw] bear_cnts = imgs_find_bears (img_files, min_score, labels) i = 0 for img_file in img_files : # bear_cnt = img_find_bears (img_file.strip(), min_score, labels) # pdb.set_trace () print ('counting bears for ', img_file) bear_cnt = bear_cnts[i] if bear_cnt == 0 : out_fp0.write (str (img_file)) out_fp0.write ("\n") elif bear_cnt == 1 : out_fp1.write (str (img_file)) out_fp1.write ("\n") else : out_fpmulti.write (str (img_file)) out_fpmulti.write ("\n") print (bear_cnt, 'bears:', img_file) i += 1 print ('\n\tGenerated files: ', out_file, '_{0,1,multi}') print ('\n') out_fp0.close () out_fp1.close () out_fpmulti.close () ##------------------------------------------------------------------------------ #------------------------------------------------------------------------------- ##------------------------------------------------------------ ## extract embeddings ##------------------------------------------------------------ def extract_bc_embeddings (input_files) : embeds_d = defaultdict(list) bc_embeds = [] bc1_embeds = [] bf_embeds = [] xml_files = generate_xml_file_list (input_files) print ('\nextracting embeddings from file: ') for x_file in xml_files: print("\t", x_file) # pdb.set_trace() root, tree = load_file (x_file) # separate out bc & bf bears for embedding in root.findall ('./embeddings/embedding'): label = embedding.find ('./label') # pdb.set_trace () # if label.text == 'bc_also' or label.text == 'bc_amber' or label.text == 'bc_beatrice' or label.text == 'bc_bella' or label.text == 'bc_flora' or label.text == 'bc_frank' or label.text == 'bc_gc' or label.text == 'bc_hoeya' or label.text == 'bc_kwatse' or label.text == 'bc_lenore' or label.text == 'bc_lillian' or label.text == 'bc_lucky' or label.text == 'bc_river' or label.text == 'bc_steve' or label.text == 'bc_toffee' or label.text == 'bc_topaz' : # bc1_embeds.append (embedding) # else : # bc_embeds.append (embedding) if label in bc_labels : bc_embeds.append (embedding) else : # brooks bear bf_embeds.append (embedding) # write out bc bears print ('\t... # bc bears: ', len (bc_embeds)) print ('\t... # bc1 bears: ', len (bc1_embeds)) print ('\t... # bf bears: ', len (bf_embeds)) # pdb.set_trace () t_root, t_embeds = create_new_tree_w_element ("embeddings") for i in range (len (bc1_embeds)) : embed = bc1_embeds[i] t_embeds.append (embed) tree = ET.ElementTree (t_root) t_name = "bc1_embeds.xml" indent (t_root) tree.write (t_name) print ('wrote bc embeddings to ', t_name) ##------------------------------------------------------------ ## split bc bf objects ##------------------------------------------------------------ def split_objects_by_locales (input_files, obj_path='images/image', label_path='box/label') : bc_objs = [] bf_objs = [] unknown_objs = [] xml_files = generate_xml_file_list (input_files) print ('\nextracting faces from file: ') for x_file in xml_files: print("\t", x_file) # pdb.set_trace() root, tree = load_file (x_file) # separate out bc & bf bears for obj in root.findall (obj_path): label = obj.find (label_path) # pdb.set_trace () if label.text[:2] == 'bc' : # bc bear bc_objs.append (obj) elif label.text[:2] == 'bf' : # brooks bear bf_objs.append (obj) else : unknown_objs.append (obj) # write out bc bears print ('\t... # bc bears: ', len (bc_objs)) print ('\t... # bf bears: ', len (bf_objs)) print ('\t... # unknown bears: ', len (unknown_objs)) # pdb.set_trace () # for locale in [] : t_root, t_embeds = create_new_tree_w_element ("images") for i in range (len (bc_objs)) : embed = bc_objs[i] t_embeds.append (embed) tree = ET.ElementTree (t_root) t_name = "bc1_faces.xml" indent (t_root) tree.write (t_name) print ('wrote faces to ', t_name) t_root, t_embeds = create_new_tree_w_element ("images") for i in range (len (bc_objs)) : embed = bc_objs[i] t_embeds.append (embed) tree = ET.ElementTree (t_root) t_name = "bc_faces.xml" indent (t_root) tree.write (t_name) print ('wrote faces to ', t_name) t_root, t_embeds = create_new_tree_w_element ("images") for i in range (len (bf_embeds)) : embed = bf_embeds[i] t_embeds.append (embed) tree = ET.ElementTree (t_root) t_name = "bf_faces.xml" indent (t_root) tree.write (t_name) print ('wrote faces to ', t_name) ##------------------------------------------------------------ ## split faces by count (0, 1, multi) ##------------------------------------------------------------ def split_faces_by_count (input_files, output_root) : zeros = [] ones = [] multis = [] xml_files = generate_xml_file_list (input_files) print ('\nextracting faces from file: ') for x_file in xml_files: print("\t", x_file) # pdb.set_trace() root, tree = load_file (x_file) # separate out face(box) counts for image in root.findall ('images/image'): boxes = image.findall ('box') # pdb.set_trace () if len (boxes) == 0 : zeros.append (image) elif len (boxes) == 1 : ones.append (image) else : multis.append (image) # write out bc bears print ('\t... # zero faces : ', len (zeros)) print ('\t... # single face : ', len (ones)) print ('\t... # multiple faces: ', len (multis)) # pdb.set_trace () t_root, t_images = create_new_tree_w_element ("images") for i in range (len (zeros)) : image = zeros[i] t_images.append (image) tree = ET.ElementTree (t_root) t_name = output_root + '_0.xml' indent (t_root) tree.write (t_name) print ('------- wrote zero detects to :', t_name) t_root, t_images = create_new_tree_w_element ("images") for i in range (len (ones)) : image = ones[i] t_images.append (image) tree = ET.ElementTree (t_root) t_name = output_root + '_1.xml' indent (t_root) tree.write (t_name) print ('------- wrote single detects to :', t_name) t_root, t_images = create_new_tree_w_element ("images") for i in range (len (multis)) : image = multis[i] t_images.append (image) tree = ET.ElementTree (t_root) t_name = output_root + '_multi.xml' indent (t_root) tree.write (t_name) print ('------- wrote multi detects to :', t_name) ##------------------------------------------------------------ ## main code ##------------------------------------------------------------ def do_generate_folds (input_files, n_folds, output_file, shuffle=True) : chips_d = defaultdict(list) load_objs_from_files (input_files, chips_d) ## print "printing chips dictionary ... " ## print_dict (chips_d) train_list, validate_list = generate_folds_content (chips_d, n_folds, shuffle) generate_folds_files (train_list, validate_list, output_file) ##------------------------------------------------------------ ## can be called with: ## partition_files 80 20 -out xxx *.xml dirs ## generate_folds 5 -out yyy *.xml dirs ##------------------------------------------------------------ def main (argv) : parser = argparse.ArgumentParser(description='Generate data for training.', formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=50)) # parser.formatter.max_help_position = 50 parser.add_argument ('--partition', default=80, help='Parition data in two. Defaults to 80.') parser.add_argument ('--folds', default=5, help='Generate n sets of train/validate files. Defaults to 5.') parser.add_argument ('--output', default="", help='Output file basename.') parser.add_argument ('--verbosity', type=int, default=1, choices=[0, 1, 2], help="increase output verbosity") if __name__ == "__main__": main (sys.argv) ## test split/partition. use count with remainders ## import datetime ## datetime.datetime.now().strftime("%Y%m%d_%H%M") ## split x y (x+y=100) ## split n ## generate_partition_files 80 20 [xml_file_or_dir]+ ## generate_folds_files 5 [xml_file_or_dir]+
[ "matplotlib.pyplot.title", "csv.reader", "pandas.read_csv", "random.shuffle", "matplotlib.pyplot.bar", "os.walk", "collections.defaultdict", "matplotlib.pyplot.figure", "numpy.rot90", "numpy.mean", "xml.etree.cElementTree.Element", "requests.post", "matplotlib.pyplot.tight_layout", "os.path.join", "matplotlib.pyplot.xlabel", "pandas.DataFrame", "xml.etree.cElementTree.parse", "numpy.meshgrid", "numpy.zeros_like", "scipy.spatial.distance.euclidean", "random.randint", "xml.etree.cElementTree.ElementTree", "matplotlib.patches.Rectangle", "numpy.histogram2d", "pandas.merge", "os.path.dirname", "matplotlib.pyplot.yticks", "os.path.exists", "argparse.HelpFormatter", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.xticks", "matplotlib.pyplot.subplots", "datetime.datetime.now", "matplotlib.pyplot.show", "numpy.ones_like", "math.sqrt", "numpy.ma.masked_where", "os.path.basename", "numpy.median", "numpy.flipud", "matplotlib.pyplot.pcolormesh", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.subplot", "os.makedirs", "matplotlib.pyplot.plot", "sklearn.manifold.TSNE", "os.getcwd", "os.path.isdir", "matplotlib.pyplot.scatter", "matplotlib.pyplot.hist", "os.path.abspath", "xml.etree.cElementTree.tostring", "matplotlib.pyplot.axis", "PIL.Image.open", "random.choice", "numpy.array", "os.path.splitext", "pdb.set_trace", "collections.OrderedDict", "xml.etree.cElementTree.SubElement", "os.path.split", "matplotlib.pyplot.savefig" ]
[((4177, 4190), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (4188, 4190), False, 'from collections import defaultdict\n'), ((4434, 4460), 'xml.etree.cElementTree.tostring', 'ET.tostring', (['elem', '"""utf-8"""'], {}), "(elem, 'utf-8')\n", (4445, 4460), True, 'import xml.etree.cElementTree as ET\n'), ((9212, 9231), 'xml.etree.cElementTree.parse', 'ET.parse', (['faces_xml'], {}), '(faces_xml)\n', (9220, 9231), True, 'import xml.etree.cElementTree as ET\n'), ((10288, 10307), 'PIL.Image.open', 'Image.open', (['imgfile'], {}), '(imgfile)\n', (10298, 10307), False, 'from PIL import Image\n'), ((10612, 10628), 'math.sqrt', 'math.sqrt', (['ratio'], {}), '(ratio)\n', (10621, 10628), False, 'import math\n'), ((10888, 10907), 'PIL.Image.open', 'Image.open', (['imgfile'], {}), '(imgfile)\n', (10898, 10907), False, 'from PIL import Image\n'), ((11063, 11079), 'math.sqrt', 'math.sqrt', (['ratio'], {}), '(ratio)\n', (11072, 11079), False, 'import math\n'), ((13480, 13499), 'PIL.Image.open', 'Image.open', (['imgfile'], {}), '(imgfile)\n', (13490, 13499), False, 'from PIL import Image\n'), ((18737, 18764), 'os.path.splitext', 'os.path.splitext', (['orig_file'], {}), '(orig_file)\n', (18753, 18764), False, 'import os\n'), ((20136, 20163), 'os.path.splitext', 'os.path.splitext', (['orig_file'], {}), '(orig_file)\n', (20152, 20163), False, 'import os\n'), ((20544, 20558), 'xml.etree.cElementTree.parse', 'ET.parse', (['file'], {}), '(file)\n', (20552, 20558), True, 'import xml.etree.cElementTree as ET\n'), ((25360, 25375), 'numpy.array', 'np.array', (['embed'], {}), '(embed)\n', (25368, 25375), True, 'import numpy as np\n'), ((26464, 26477), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (26475, 26477), False, 'from collections import OrderedDict\n'), ((26494, 26513), 'numpy.array', 'np.array', (['new_embed'], {}), '(new_embed)\n', (26502, 26513), True, 'import numpy as np\n'), ((26653, 26668), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (26666, 26668), False, 'import pdb\n'), ((26921, 26934), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (26932, 26934), False, 'from collections import defaultdict\n'), ((27129, 27144), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (27142, 27144), False, 'import pdb\n'), ((30203, 30226), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (30216, 30226), False, 'import os\n'), ((36854, 36871), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (36865, 36871), False, 'from collections import defaultdict\n'), ((36886, 36903), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (36897, 36903), False, 'from collections import defaultdict\n'), ((39108, 39125), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (39119, 39125), False, 'from collections import defaultdict\n'), ((40871, 40888), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (40882, 40888), False, 'from collections import defaultdict\n'), ((44274, 44289), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (44287, 44289), False, 'import pdb\n'), ((52341, 52356), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (52354, 52356), False, 'import pdb\n'), ((53107, 53122), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (53120, 53122), False, 'import pdb\n'), ((54438, 54453), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (54451, 54453), False, 'import pdb\n'), ((55154, 55200), 'pandas.DataFrame', 'pandas.DataFrame', (['filenames'], {'columns': "['IMAGE']"}), "(filenames, columns=['IMAGE'])\n", (55170, 55200), False, 'import pandas\n'), ((55253, 55311), 'pandas.merge', 'pandas.merge', (['df_all', 'df_images'], {'on': "['IMAGE']", 'how': '"""inner"""'}), "(df_all, df_images, on=['IMAGE'], how='inner')\n", (55265, 55311), False, 'import pandas\n'), ((55997, 56038), 'pandas.read_csv', 'pandas.read_csv', (['db_csv_filename'], {'sep': '""";"""'}), "(db_csv_filename, sep=';')\n", (56012, 56038), False, 'import pandas\n'), ((56053, 56099), 'pandas.DataFrame', 'pandas.DataFrame', (['filenames'], {'columns': "['IMAGE']"}), "(filenames, columns=['IMAGE'])\n", (56069, 56099), False, 'import pandas\n'), ((56185, 56243), 'pandas.merge', 'pandas.merge', (['df_all', 'df_images'], {'on': "['IMAGE']", 'how': '"""inner"""'}), "(df_all, df_images, on=['IMAGE'], how='inner')\n", (56197, 56243), False, 'import pandas\n'), ((57804, 57864), 'pandas.DataFrame', 'pandas.DataFrame', (['label_date_list'], {'columns': "['LABEL', 'DATE']"}), "(label_date_list, columns=['LABEL', 'DATE'])\n", (57820, 57864), False, 'import pandas\n'), ((57946, 58022), 'pandas.merge', 'pandas.merge', (['df_images_db', 'df_label_date'], {'on': "['LABEL', 'DATE']", 'how': '"""inner"""'}), "(df_images_db, df_label_date, on=['LABEL', 'DATE'], how='inner')\n", (57958, 58022), False, 'import pandas\n'), ((58572, 58594), 'random.shuffle', 'random.shuffle', (['labels'], {}), '(labels)\n', (58586, 58594), False, 'import random\n'), ((59428, 59445), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (59439, 59445), False, 'from collections import defaultdict\n'), ((61575, 61590), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (61588, 61590), False, 'import pdb\n'), ((64677, 64694), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (64688, 64694), False, 'from collections import defaultdict\n'), ((72668, 72688), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (72682, 72688), True, 'import xml.etree.cElementTree as ET\n'), ((73847, 73868), 'xml.etree.cElementTree.Element', 'ET.Element', (['"""dataset"""'], {}), "('dataset')\n", (73857, 73868), True, 'import xml.etree.cElementTree as ET\n'), ((74112, 74123), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (74121, 74123), False, 'import os\n'), ((74330, 74357), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['r', 'elem_name'], {}), '(r, elem_name)\n', (74343, 74357), True, 'import xml.etree.cElementTree as ET\n'), ((74579, 74597), 'xml.etree.cElementTree.parse', 'ET.parse', (['xml_file'], {}), '(xml_file)\n', (74587, 74597), True, 'import xml.etree.cElementTree as ET\n'), ((78008, 78025), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (78019, 78025), False, 'from collections import defaultdict\n'), ((81053, 81073), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (81067, 81073), True, 'import xml.etree.cElementTree as ET\n'), ((81427, 81447), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (81441, 81447), True, 'import xml.etree.cElementTree as ET\n'), ((81825, 81842), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (81836, 81842), False, 'from collections import defaultdict\n'), ((82215, 82225), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (82223, 82225), True, 'import matplotlib.pyplot as plt\n'), ((82642, 82654), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (82652, 82654), True, 'import matplotlib.pyplot as plt\n'), ((82739, 82753), 'matplotlib.pyplot.axis', 'plt.axis', (['"""on"""'], {}), "('on')\n", (82747, 82753), True, 'import matplotlib.pyplot as plt\n'), ((82843, 82887), 'matplotlib.pyplot.bar', 'plt.bar', (['band_label', 'bands', '(7)'], {'color': '"""green"""'}), "(band_label, bands, 7, color='green')\n", (82850, 82887), True, 'import matplotlib.pyplot as plt\n'), ((83279, 83291), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (83289, 83291), True, 'import matplotlib.pyplot as plt\n'), ((83293, 83321), 'matplotlib.pyplot.title', 'plt.title', (['"""nose histogram."""'], {}), "('nose histogram.')\n", (83302, 83321), True, 'import matplotlib.pyplot as plt\n'), ((83324, 83344), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '""".r"""'], {}), "(x, y, '.r')\n", (83332, 83344), True, 'import matplotlib.pyplot as plt\n'), ((83344, 83359), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (83354, 83359), True, 'import matplotlib.pyplot as plt\n'), ((83361, 83376), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y"""'], {}), "('y')\n", (83371, 83376), True, 'import matplotlib.pyplot as plt\n'), ((83440, 83472), 'numpy.histogram2d', 'np.histogram2d', (['x', 'y'], {'bins': 'nbins'}), '(x, y, bins=nbins)\n', (83454, 83472), True, 'import numpy as np\n'), ((83514, 83525), 'numpy.rot90', 'np.rot90', (['H'], {}), '(H)\n', (83522, 83525), True, 'import numpy as np\n'), ((83531, 83543), 'numpy.flipud', 'np.flipud', (['H'], {}), '(H)\n', (83540, 83543), True, 'import numpy as np\n'), ((83570, 83599), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(H == 0)', 'H'], {}), '(H == 0, H)\n', (83588, 83599), True, 'import numpy as np\n'), ((83675, 83687), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (83685, 83687), True, 'import matplotlib.pyplot as plt\n'), ((83755, 83794), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['xedges', 'yedges', 'Hmasked'], {}), '(xedges, yedges, Hmasked)\n', (83769, 83794), True, 'import matplotlib.pyplot as plt\n'), ((83794, 83809), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (83804, 83809), True, 'import matplotlib.pyplot as plt\n'), ((83811, 83826), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y"""'], {}), "('y')\n", (83821, 83826), True, 'import matplotlib.pyplot as plt\n'), ((83835, 83849), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (83847, 83849), True, 'import matplotlib.pyplot as plt\n'), ((86839, 86856), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (86850, 86856), False, 'from collections import defaultdict\n'), ((88167, 88187), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (88181, 88187), True, 'import xml.etree.cElementTree as ET\n'), ((92705, 92717), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (92715, 92717), True, 'import matplotlib.pyplot as plt\n'), ((92863, 92895), 'numpy.histogram2d', 'np.histogram2d', (['x', 'y'], {'bins': 'nbins'}), '(x, y, bins=nbins)\n', (92877, 92895), True, 'import numpy as np\n'), ((93217, 93266), 'numpy.meshgrid', 'np.meshgrid', (['(xedges[:-1] + 1.0)', '(yedges[:-1] + 1.0)'], {}), '(xedges[:-1] + 1.0, yedges[:-1] + 1.0)\n', (93228, 93266), True, 'import numpy as np\n'), ((93327, 93346), 'numpy.zeros_like', 'np.zeros_like', (['xpos'], {}), '(xpos)\n', (93340, 93346), True, 'import numpy as np\n'), ((97642, 97658), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (97653, 97658), False, 'from collections import defaultdict\n'), ((98939, 98956), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (98950, 98956), False, 'from collections import defaultdict\n'), ((102518, 102546), 'os.path.splitext', 'os.path.splitext', (['image_file'], {}), '(image_file)\n', (102534, 102546), False, 'import os\n'), ((103472, 103494), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (103482, 103494), False, 'from PIL import Image\n'), ((103790, 103817), 'os.path.dirname', 'os.path.dirname', (['image_file'], {}), '(image_file)\n', (103805, 103817), False, 'import os\n'), ((103834, 103861), 'os.path.dirname', 'os.path.dirname', (['label_path'], {}), '(label_path)\n', (103849, 103861), False, 'import os\n'), ((103879, 103905), 'os.path.split', 'os.path.split', (['source_path'], {}), '(source_path)\n', (103892, 103905), False, 'import os\n'), ((104099, 104121), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (104109, 104121), False, 'from PIL import Image\n'), ((105334, 105356), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (105350, 105356), False, 'import os\n'), ((110983, 111000), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (110994, 111000), False, 'from collections import defaultdict\n'), ((117567, 117579), 'os.walk', 'os.walk', (['dir'], {}), '(dir)\n', (117574, 117579), False, 'import os\n'), ((118257, 118277), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (118271, 118277), True, 'import xml.etree.cElementTree as ET\n'), ((119255, 119268), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (119266, 119268), False, 'from collections import defaultdict\n'), ((119604, 119617), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (119615, 119617), False, 'from collections import defaultdict\n'), ((121635, 121660), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (121650, 121660), False, 'import os\n'), ((121671, 121693), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (121687, 121693), False, 'import os\n'), ((122395, 122410), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (122408, 122410), False, 'import pdb\n'), ((122911, 122928), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (122922, 122928), False, 'from collections import defaultdict\n'), ((123513, 123533), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (123527, 123533), True, 'import xml.etree.cElementTree as ET\n'), ((125081, 125098), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (125092, 125098), False, 'from collections import defaultdict\n'), ((125112, 125129), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (125123, 125129), False, 'from collections import defaultdict\n'), ((128002, 128019), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (128013, 128019), False, 'from collections import defaultdict\n'), ((128608, 128625), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (128619, 128625), False, 'from collections import defaultdict\n'), ((130098, 130115), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (130109, 130115), False, 'from collections import defaultdict\n'), ((132693, 132710), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (132704, 132710), False, 'from collections import defaultdict\n'), ((132726, 132743), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (132737, 132743), False, 'from collections import defaultdict\n'), ((133343, 133363), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['root'], {}), '(root)\n', (133357, 133363), True, 'import xml.etree.cElementTree as ET\n'), ((133939, 133956), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (133950, 133956), False, 'from collections import defaultdict\n'), ((134880, 134897), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (134891, 134897), False, 'from collections import defaultdict\n'), ((135150, 135252), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'random_state': '(0)', 'perplexity': '(5)', 'learning_rate': '(10)', 'method': '"""exact"""', 'n_iter': '(2000)'}), "(n_components=2, random_state=0, perplexity=5, learning_rate=10, method\n ='exact', n_iter=2000)\n", (135154, 135252), False, 'from sklearn.manifold import TSNE\n'), ((135260, 135281), 'numpy.array', 'np.array', (['embeds_list'], {}), '(embeds_list)\n', (135268, 135281), True, 'import numpy as np\n'), ((135458, 135478), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (135466, 135478), True, 'import numpy as np\n'), ((135481, 135496), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (135494, 135496), False, 'import pdb\n'), ((139031, 139134), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(xmin, ymin)', 'b_width', 'b_height'], {'linewidth': '(1)', 'edgecolor': 'color', 'facecolor': '"""none"""'}), "((xmin, ymin), b_width, b_height, linewidth=1, edgecolor=\n color, facecolor='none')\n", (139048, 139134), True, 'import matplotlib.patches as patches\n'), ((140755, 140775), 'PIL.Image.open', 'Image.open', (['img_file'], {}), '(img_file)\n', (140765, 140775), False, 'from PIL import Image\n'), ((140788, 140803), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (140796, 140803), True, 'import numpy as np\n'), ((140860, 140938), 'requests.post', 'requests.post', (['"""http://localhost:8080/v1/models/default:predict"""'], {'json': 'payload'}), "('http://localhost:8080/v1/models/default:predict', json=payload)\n", (140873, 140938), False, 'import requests\n'), ((141432, 141510), 'requests.post', 'requests.post', (['"""http://localhost:8080/v1/models/default:predict"""'], {'json': 'payload'}), "('http://localhost:8080/v1/models/default:predict', json=payload)\n", (141445, 141510), False, 'import requests\n'), ((144722, 144739), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (144733, 144739), False, 'from collections import defaultdict\n'), ((146145, 146167), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (146159, 146167), True, 'import xml.etree.cElementTree as ET\n'), ((147420, 147442), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (147434, 147442), True, 'import xml.etree.cElementTree as ET\n'), ((147690, 147712), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (147704, 147712), True, 'import xml.etree.cElementTree as ET\n'), ((147963, 147985), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (147977, 147985), True, 'import xml.etree.cElementTree as ET\n'), ((149139, 149161), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (149153, 149161), True, 'import xml.etree.cElementTree as ET\n'), ((149428, 149450), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (149442, 149450), True, 'import xml.etree.cElementTree as ET\n'), ((149721, 149743), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (149735, 149743), True, 'import xml.etree.cElementTree as ET\n'), ((150100, 150117), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (150111, 150117), False, 'from collections import defaultdict\n'), ((18296, 18324), 'os.path.dirname', 'os.path.dirname', (['new_imgfile'], {}), '(new_imgfile)\n', (18311, 18324), False, 'import os\n'), ((19331, 19361), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['root', '"""command"""'], {}), "(root, 'command')\n", (19344, 19361), True, 'import xml.etree.cElementTree as ET\n'), ((19852, 19880), 'os.path.dirname', 'os.path.dirname', (['new_imgfile'], {}), '(new_imgfile)\n', (19867, 19880), False, 'import os\n'), ((25446, 25457), 'numpy.array', 'np.array', (['e'], {}), '(e)\n', (25454, 25457), True, 'import numpy as np\n'), ((25468, 25505), 'scipy.spatial.distance.euclidean', 'distance.euclidean', (['e_array', 'e1_array'], {}), '(e_array, e1_array)\n', (25486, 25505), False, 'from scipy.spatial import distance\n'), ((26572, 26587), 'numpy.array', 'np.array', (['embed'], {}), '(embed)\n', (26580, 26587), True, 'import numpy as np\n'), ((26610, 26650), 'scipy.spatial.distance.euclidean', 'distance.euclidean', (['e_array', 'new_e_array'], {}), '(e_array, new_e_array)\n', (26628, 26650), False, 'from scipy.spatial import distance\n'), ((26994, 27010), 'numpy.array', 'np.array', (['embeds'], {}), '(embeds)\n', (27002, 27010), True, 'import numpy as np\n'), ((27023, 27065), 'numpy.mean', 'np.mean', (['e_array'], {'axis': '(0)', 'dtype': 'np.float64'}), '(e_array, axis=0, dtype=np.float64)\n', (27030, 27065), True, 'import numpy as np\n'), ((27111, 27126), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (27124, 27126), False, 'import pdb\n'), ((30334, 30353), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (30347, 30353), False, 'import os\n'), ((34984, 35012), 'pandas.read_csv', 'pandas.read_csv', (['db'], {'sep': '""";"""'}), "(db, sep=';')\n", (34999, 35012), False, 'import pandas\n'), ((60414, 60435), 'random.choice', 'random.choice', (['images'], {}), '(images)\n', (60427, 60435), False, 'import random\n'), ((66508, 66533), 'random.shuffle', 'random.shuffle', (['all_chips'], {}), '(all_chips)\n', (66522, 66533), False, 'import random\n'), ((69066, 69091), 'random.shuffle', 'random.shuffle', (['all_chips'], {}), '(all_chips)\n', (69080, 69091), False, 'import random\n'), ((71968, 71990), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['t_root'], {}), '(t_root)\n', (71982, 71990), True, 'import xml.etree.cElementTree as ET\n'), ((72010, 72032), 'xml.etree.cElementTree.ElementTree', 'ET.ElementTree', (['v_root'], {}), '(v_root)\n', (72024, 72032), True, 'import xml.etree.cElementTree as ET\n'), ((73877, 73904), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['r', '"""comment"""'], {}), "(r, 'comment')\n", (73890, 73904), True, 'import xml.etree.cElementTree as ET\n'), ((74003, 74027), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['r', '"""date"""'], {}), "(r, 'date')\n", (74016, 74027), True, 'import xml.etree.cElementTree as ET\n'), ((74080, 74103), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['r', '"""cwd"""'], {}), "(r, 'cwd')\n", (74093, 74103), True, 'import xml.etree.cElementTree as ET\n'), ((74126, 74153), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['r', '"""command"""'], {}), "(r, 'command')\n", (74139, 74153), True, 'import xml.etree.cElementTree as ET\n'), ((74175, 74203), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['r', '"""filetype"""'], {}), "(r, 'filetype')\n", (74188, 74203), True, 'import xml.etree.cElementTree as ET\n'), ((75503, 75529), 'os.path.splitext', 'os.path.splitext', (['xml_file'], {}), '(xml_file)\n', (75519, 75529), False, 'import os\n'), ((76067, 76083), 'os.path.isdir', 'os.path.isdir', (['i'], {}), '(i)\n', (76080, 76083), False, 'import os\n'), ((78651, 78668), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (78659, 78668), True, 'import matplotlib.pyplot as plt\n'), ((78671, 78686), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (78679, 78686), True, 'import matplotlib.pyplot as plt\n'), ((78689, 78740), 'matplotlib.pyplot.scatter', 'plt.scatter', (['l_eye[0]', '(0 - l_eye[1])'], {'c': '"""blue"""', 's': '(64)'}), "(l_eye[0], 0 - l_eye[1], c='blue', s=64)\n", (78700, 78740), True, 'import matplotlib.pyplot as plt\n'), ((78742, 78793), 'matplotlib.pyplot.scatter', 'plt.scatter', (['r_eye[0]', '(0 - r_eye[1])'], {'c': '"""blue"""', 's': '(64)'}), "(r_eye[0], 0 - r_eye[1], c='blue', s=64)\n", (78753, 78793), True, 'import matplotlib.pyplot as plt\n'), ((78795, 78844), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_list', 'y_list_flip'], {'c': '"""green"""', 's': '(16)'}), "(x_list, y_list_flip, c='green', s=16)\n", (78806, 78844), True, 'import matplotlib.pyplot as plt\n'), ((78848, 78895), 'matplotlib.pyplot.scatter', 'plt.scatter', (['nose_x', '(0 - nose_y)'], {'c': '"""red"""', 's': '(128)'}), "(nose_x, 0 - nose_y, c='red', s=128)\n", (78859, 78895), True, 'import matplotlib.pyplot as plt\n'), ((78939, 78966), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""nose_fig.png"""'], {}), "('nose_fig.png')\n", (78950, 78966), True, 'import matplotlib.pyplot as plt\n'), ((78970, 78980), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (78978, 78980), True, 'import matplotlib.pyplot as plt\n'), ((82774, 82798), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""face count"""'], {}), "('face count')\n", (82784, 82798), True, 'import matplotlib.pyplot as plt\n'), ((82819, 82841), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""distance"""'], {}), "('distance')\n", (82829, 82841), True, 'import matplotlib.pyplot as plt\n'), ((87457, 87488), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['chips', 'elem_name'], {}), '(chips, elem_name)\n', (87470, 87488), True, 'import xml.etree.cElementTree as ET\n'), ((87729, 87760), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['chips', 'elem_name'], {}), '(chips, elem_name)\n', (87742, 87760), True, 'import xml.etree.cElementTree as ET\n'), ((89897, 89929), 'random.randint', 'random.randint', (['(0)', '(label_cnt - 1)'], {}), '(0, label_cnt - 1)\n', (89911, 89929), False, 'import random\n'), ((90048, 90078), 'random.randint', 'random.randint', (['(0)', '(img_cnt - 1)'], {}), '(0, img_cnt - 1)\n', (90062, 90078), False, 'import random\n'), ((91366, 91398), 'random.randint', 'random.randint', (['(0)', '(label_cnt - 1)'], {}), '(0, label_cnt - 1)\n', (91380, 91398), False, 'import random\n'), ((91654, 91684), 'random.randint', 'random.randint', (['(0)', '(img_cnt - 1)'], {}), '(0, img_cnt - 1)\n', (91668, 91684), False, 'import random\n'), ((93449, 93467), 'numpy.ones_like', 'np.ones_like', (['zpos'], {}), '(zpos)\n', (93461, 93467), True, 'import numpy as np\n'), ((94089, 94125), 'math.sqrt', 'math.sqrt', (['(x_dist ** 2 + y_dist ** 2)'], {}), '(x_dist ** 2 + y_dist ** 2)\n', (94098, 94125), False, 'import math\n'), ((94289, 94343), 'math.sqrt', 'math.sqrt', (['((pt_x - nose_x) ** 2 + (pt_y - nose_y) ** 2)'], {}), '((pt_x - nose_x) ** 2 + (pt_y - nose_y) ** 2)\n', (94298, 94343), False, 'import math\n'), ((97761, 97785), 'PIL.Image.open', 'Image.open', (['img_files[i]'], {}), '(img_files[i])\n', (97771, 97785), False, 'from PIL import Image\n'), ((104924, 104945), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (104939, 104945), False, 'import os\n'), ((105397, 105418), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (105412, 105418), False, 'import os\n'), ((105432, 105454), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (105448, 105454), False, 'import os\n'), ((112605, 112642), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': 'delim'}), '(csv_file, delimiter=delim)\n', (112615, 112642), False, 'import csv\n'), ((114125, 114162), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': 'delim'}), '(csv_file, delimiter=delim)\n', (114135, 114162), False, 'import csv\n'), ((118157, 118191), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['images_tag', '"""image"""'], {}), "(images_tag, 'image')\n", (118170, 118191), True, 'import xml.etree.cElementTree as ET\n'), ((118784, 118801), 'os.walk', 'os.walk', (['filename'], {}), '(filename)\n', (118791, 118801), False, 'import os\n'), ((135560, 135572), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (135570, 135572), True, 'import matplotlib.pyplot as plt\n'), ((135580, 135596), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (135591, 135596), True, 'import matplotlib.pyplot as plt\n'), ((136035, 136053), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (136051, 136053), True, 'import matplotlib.pyplot as plt\n'), ((136222, 136236), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (136232, 136236), True, 'import matplotlib.pyplot as plt\n'), ((136239, 136253), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (136249, 136253), True, 'import matplotlib.pyplot as plt\n'), ((136256, 136278), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""emb.png"""'], {}), "('emb.png')\n", (136267, 136278), True, 'import matplotlib.pyplot as plt\n'), ((136281, 136291), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (136289, 136291), True, 'import matplotlib.pyplot as plt\n'), ((136975, 136990), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (136987, 136990), True, 'import matplotlib.pyplot as plt\n'), ((137842, 137943), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(xmin, ymin)', 'b_width', 'b_height'], {'linewidth': '(1)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((xmin, ymin), b_width, b_height, linewidth=1, edgecolor=\n 'r', facecolor='none')\n", (137859, 137943), True, 'import matplotlib.patches as patches\n'), ((138021, 138031), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (138029, 138031), True, 'import matplotlib.pyplot as plt\n'), ((139620, 139635), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (139632, 139635), True, 'import matplotlib.pyplot as plt\n'), ((141298, 141318), 'PIL.Image.open', 'Image.open', (['img_file'], {}), '(img_file)\n', (141308, 141318), False, 'from PIL import Image\n'), ((141332, 141347), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (141340, 141347), True, 'import numpy as np\n'), ((17745, 17764), 'PIL.Image.open', 'Image.open', (['imgfile'], {}), '(imgfile)\n', (17755, 17764), False, 'from PIL import Image\n'), ((18335, 18365), 'os.path.isdir', 'os.path.isdir', (['new_imgfile_dir'], {}), '(new_imgfile_dir)\n', (18348, 18365), False, 'import os\n'), ((18372, 18400), 'os.makedirs', 'os.makedirs', (['new_imgfile_dir'], {}), '(new_imgfile_dir)\n', (18383, 18400), False, 'import os\n'), ((19891, 19921), 'os.path.isdir', 'os.path.isdir', (['new_imgfile_dir'], {}), '(new_imgfile_dir)\n', (19904, 19921), False, 'import os\n'), ((19928, 19956), 'os.makedirs', 'os.makedirs', (['new_imgfile_dir'], {}), '(new_imgfile_dir)\n', (19939, 19956), False, 'import os\n'), ((39675, 39695), 'random.shuffle', 'random.shuffle', (['objs'], {}), '(objs)\n', (39689, 39695), False, 'import random\n'), ((67388, 67409), 'random.shuffle', 'random.shuffle', (['chips'], {}), '(chips)\n', (67402, 67409), False, 'import random\n'), ((70276, 70305), 'random.shuffle', 'random.shuffle', (['chips_d_items'], {}), '(chips_d_items)\n', (70290, 70305), False, 'import random\n'), ((70369, 70386), 'random.shuffle', 'random.shuffle', (['j'], {}), '(j)\n', (70383, 70386), False, 'import random\n'), ((73954, 73977), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (73975, 73977), False, 'import datetime\n'), ((75313, 75346), 'os.path.basename', 'os.path.basename', (['pathed_chipfile'], {}), '(pathed_chipfile)\n', (75329, 75346), False, 'import os\n'), ((90153, 90173), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (90167, 90173), False, 'import random\n'), ((91420, 91452), 'random.randint', 'random.randint', (['(0)', '(label_cnt - 1)'], {}), '(0, label_cnt - 1)\n', (91434, 91452), False, 'import random\n'), ((95950, 95967), 'numpy.median', 'np.median', (['x_list'], {}), '(x_list)\n', (95959, 95967), True, 'import numpy as np\n'), ((95970, 95987), 'numpy.median', 'np.median', (['y_list'], {}), '(y_list)\n', (95979, 95987), True, 'import numpy as np\n'), ((100193, 100221), 'numpy.median', 'np.median', (['img_cnt_per_label'], {}), '(img_cnt_per_label)\n', (100202, 100221), True, 'import numpy as np\n'), ((100632, 100692), 'matplotlib.pyplot.hist', 'plt.hist', (['img_cnt_per_label', '(20)'], {'facecolor': '"""blue"""', 'alpha': '(0.5)'}), "(img_cnt_per_label, 20, facecolor='blue', alpha=0.5)\n", (100640, 100692), True, 'import matplotlib.pyplot as plt\n'), ((100696, 100753), 'matplotlib.pyplot.title', 'plt.title', (["('histogram of ' + filetype + ' count per bear')"], {}), "('histogram of ' + filetype + ' count per bear')\n", (100705, 100753), True, 'import matplotlib.pyplot as plt\n'), ((100925, 100955), 'matplotlib.pyplot.savefig', 'plt.savefig', (['hist_obj_cnt_file'], {}), '(hist_obj_cnt_file)\n', (100936, 100955), True, 'import matplotlib.pyplot as plt\n'), ((101041, 101051), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (101049, 101051), True, 'import matplotlib.pyplot as plt\n'), ((104465, 104496), 'os.path.exists', 'os.path.exists', (['orig_image_file'], {}), '(orig_image_file)\n', (104479, 104496), False, 'import os\n'), ((116358, 116381), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (116379, 116381), False, 'import datetime\n'), ((118730, 118755), 'os.path.abspath', 'os.path.abspath', (['filename'], {}), '(filename)\n', (118745, 118755), False, 'import os\n'), ((123207, 123231), 'os.path.exists', 'os.path.exists', (['chipfile'], {}), '(chipfile)\n', (123221, 123231), False, 'import os\n'), ((140497, 140507), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (140505, 140507), True, 'import matplotlib.pyplot as plt\n'), ((9870, 9897), 'xml.etree.cElementTree.SubElement', 'ET.SubElement', (['box', '"""label"""'], {}), "(box, 'label')\n", (9883, 9897), True, 'import xml.etree.cElementTree as ET\n'), ((22046, 22069), 'collections.defaultdict', 'defaultdict', (['(lambda : 0)'], {}), '(lambda : 0)\n', (22057, 22069), False, 'from collections import defaultdict\n'), ((69763, 69784), 'random.shuffle', 'random.shuffle', (['chips'], {}), '(chips)\n', (69777, 69784), False, 'import random\n'), ((69986, 70003), 'random.shuffle', 'random.shuffle', (['j'], {}), '(j)\n', (70000, 70003), False, 'import random\n'), ((90309, 90341), 'random.randint', 'random.randint', (['(0)', '(label_cnt - 1)'], {}), '(0, label_cnt - 1)\n', (90323, 90341), False, 'import random\n'), ((101373, 101412), 'matplotlib.pyplot.title', 'plt.title', (['"""histogram of of face sizes"""'], {}), "('histogram of of face sizes')\n", (101382, 101412), True, 'import matplotlib.pyplot as plt\n'), ((101418, 101450), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""N (image size=NxN)"""'], {}), "('N (image size=NxN)')\n", (101428, 101450), True, 'import matplotlib.pyplot as plt\n'), ((101528, 101582), 'matplotlib.pyplot.hist', 'plt.hist', (['chip_sizes', '(20)'], {'facecolor': '"""green"""', 'alpha': '(0.5)'}), "(chip_sizes, 20, facecolor='green', alpha=0.5)\n", (101536, 101582), True, 'import matplotlib.pyplot as plt\n'), ((101637, 101670), 'matplotlib.pyplot.savefig', 'plt.savefig', (['hist_chip_sizes_file'], {}), '(hist_chip_sizes_file)\n', (101648, 101670), True, 'import matplotlib.pyplot as plt\n'), ((101760, 101770), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (101768, 101770), True, 'import matplotlib.pyplot as plt\n'), ((118823, 118846), 'os.path.join', 'os.path.join', (['root', 'dir'], {}), '(root, dir)\n', (118835, 118846), False, 'import os\n'), ((118956, 118979), 'os.path.join', 'os.path.join', (['root', 'img'], {}), '(root, img)\n', (118968, 118979), False, 'import os\n'), ((150751, 150801), 'argparse.HelpFormatter', 'argparse.HelpFormatter', (['prog'], {'max_help_position': '(50)'}), '(prog, max_help_position=50)\n', (150773, 150801), False, 'import argparse\n'), ((116836, 116859), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (116857, 116859), False, 'import datetime\n'), ((117101, 117124), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (117122, 117124), False, 'import datetime\n'), ((117684, 117711), 'os.path.join', 'os.path.join', (['dirname', 'file'], {}), '(dirname, file)\n', (117696, 117711), False, 'import os\n'), ((22601, 22616), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (22614, 22616), False, 'import pdb\n'), ((101344, 101365), 'numpy.median', 'np.median', (['chip_sizes'], {}), '(chip_sizes)\n', (101353, 101365), True, 'import numpy as np\n')]
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Defines utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from jax.tree_util import register_pytree_node import jax.numpy as np import numpy as onp i16 = np.int16 i32 = np.int32 i64 = np.int64 f16 = np.float16 f32 = np.float32 f64 = np.float64 def static_cast(*xs): """Function to cast a value to the lowest dtype that can express it.""" # NOTE(schsam): static_cast is so named because it cannot be jit. return (np.array(x, dtype=onp.min_scalar_type(x)) for x in xs) def register_pytree_namedtuple(cls): register_pytree_node( cls, lambda xs: (tuple(xs), None), lambda _, xs: cls(*xs))
[ "numpy.min_scalar_type" ]
[((1104, 1126), 'numpy.min_scalar_type', 'onp.min_scalar_type', (['x'], {}), '(x)\n', (1123, 1126), True, 'import numpy as onp\n')]
import numpy as np import pyworld as pw import audio import os from pathlib import Path from scipy.interpolate import interp1d def extract_f0(wav, max_duration, data_cfg): # Compute fundamental frequency f0, t = pw.dio( wav.astype(np.float64), data_cfg.sampling_rate, frame_period=data_cfg.hop_length / data_cfg.sampling_rate * 1000, ) f0 = pw.stonemask(wav.astype(np.float64), f0, t, data_cfg.sampling_rate).astype(np.float32) f0 = f0[:max_duration] nonzero_ids = np.where(f0 != 0)[0] if len(nonzero_ids) > 2: interp_fn = interp1d( nonzero_ids, f0[nonzero_ids], fill_value=(f0[nonzero_ids[0]], f0[nonzero_ids[-1]]), bounds_error=False, ) f0 = interp_fn(np.linspace(0, len(f0) - 1, max_duration)) f0 = np.log(f0) if np.sum(f0 != 0) <= 1: return None return f0 def extract_mel_energy(wav, max_duration, data_cfg): # Compute mel-scale spectrogram and energy mel_spectrogram, energy = audio.tools.get_mel_from_wav(wav, data_cfg) mel_spectrogram = mel_spectrogram.numpy().astype(np.float32)[:, :max_duration] energy = np.log(energy + data_cfg.energy_log_offset) energy = energy[:max_duration] return mel_spectrogram.T, energy def build_feature_stat(base_path, train_filenames): f0_min = 1e9 f0_max = -1e9 energy_min = 1e9 energy_max = -1e9 for filename in train_filenames: f0 = np.load(base_path / "f0" / f"f0-{filename}.npy") f0_min = min(f0_min, f0.min()) f0_max = max(f0_max, f0.max()) energy = np.load(base_path / "energy" / f"energy-{filename}.npy") energy_min = min(energy_min, energy.min()) energy_max = max(energy_max, energy.max()) return { "f0_min": float(f0_min), "f0_max": float(f0_max), "energy_min": float(energy_min), "energy_max": float(energy_max), } def train_test_split(base_path): np.random.seed(42) train_out = [] dev_out = [] speakers = set() with open(base_path / "train.txt", "w", encoding="utf-8") as ftrain: with open(base_path / "dev.txt", "w", encoding="utf-8") as fdev: for filename in os.listdir(base_path / "f0"): basename = Path(filename).stem.split("-")[1] speaker = filename.split("-")[1].split("_")[0] speakers.add(speaker) if np.random.random() < 0.9: print(basename, speaker, file=ftrain) train_out.append(basename) else: print(basename, speaker, file=fdev) dev_out.append(basename) return train_out, dev_out, speakers
[ "numpy.load", "numpy.random.seed", "numpy.log", "numpy.sum", "pathlib.Path", "numpy.where", "numpy.random.random", "scipy.interpolate.interp1d", "audio.tools.get_mel_from_wav", "os.listdir" ]
[((1044, 1087), 'audio.tools.get_mel_from_wav', 'audio.tools.get_mel_from_wav', (['wav', 'data_cfg'], {}), '(wav, data_cfg)\n', (1072, 1087), False, 'import audio\n'), ((1184, 1227), 'numpy.log', 'np.log', (['(energy + data_cfg.energy_log_offset)'], {}), '(energy + data_cfg.energy_log_offset)\n', (1190, 1227), True, 'import numpy as np\n'), ((1993, 2011), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (2007, 2011), True, 'import numpy as np\n'), ((516, 533), 'numpy.where', 'np.where', (['(f0 != 0)'], {}), '(f0 != 0)\n', (524, 533), True, 'import numpy as np\n'), ((586, 703), 'scipy.interpolate.interp1d', 'interp1d', (['nonzero_ids', 'f0[nonzero_ids]'], {'fill_value': '(f0[nonzero_ids[0]], f0[nonzero_ids[-1]])', 'bounds_error': '(False)'}), '(nonzero_ids, f0[nonzero_ids], fill_value=(f0[nonzero_ids[0]], f0[\n nonzero_ids[-1]]), bounds_error=False)\n', (594, 703), False, 'from scipy.interpolate import interp1d\n'), ((837, 847), 'numpy.log', 'np.log', (['f0'], {}), '(f0)\n', (843, 847), True, 'import numpy as np\n'), ((856, 871), 'numpy.sum', 'np.sum', (['(f0 != 0)'], {}), '(f0 != 0)\n', (862, 871), True, 'import numpy as np\n'), ((1483, 1531), 'numpy.load', 'np.load', (["(base_path / 'f0' / f'f0-{filename}.npy')"], {}), "(base_path / 'f0' / f'f0-{filename}.npy')\n", (1490, 1531), True, 'import numpy as np\n'), ((1627, 1683), 'numpy.load', 'np.load', (["(base_path / 'energy' / f'energy-{filename}.npy')"], {}), "(base_path / 'energy' / f'energy-{filename}.npy')\n", (1634, 1683), True, 'import numpy as np\n'), ((2244, 2272), 'os.listdir', 'os.listdir', (["(base_path / 'f0')"], {}), "(base_path / 'f0')\n", (2254, 2272), False, 'import os\n'), ((2455, 2473), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2471, 2473), True, 'import numpy as np\n'), ((2301, 2315), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (2305, 2315), False, 'from pathlib import Path\n')]
from os.path import abspath, dirname import numpy as np import tensorflow as tf TRAIN = 'train' VAL = 'val' TEST = 'test' """ Available DataSets """ GTSR = 'GTSR' GTSD = 'GTSD' BDD100K = 'BDD100K' MAPILLARY_TS = 'MAPILLARY_TS' COCO = 'COCO' ALL_DETECTION_DATA_SETS = [GTSD, BDD100K, MAPILLARY_TS, COCO] """ PATH """ # Inside the project PROJECT_PATH = abspath(dirname(__file__)).split('/src')[0] + '/' """ DATA paths """ # External path # Here we have to copy the labels files we get from the dataset that we then convert to a json into the # the raw folder with the same format in every dataset. Meaning: # - A json label map, key the id (integer) of the label and value the label value (string) # - A csv file with: filename, xmin, ymin, xmax, ymax, label # TRAIN and VALIDATION labels have to be grouped since we will use k-fold cross validation EXTERNAL_PATH = PROJECT_PATH + 'data/external/' DATASET_PATH = EXTERNAL_PATH + 'datasets/{}/' EXTERNAL_ANNOTATIONS_PATH = EXTERNAL_PATH + '{}_labels.{}' EXTERNAL_ANNOTATIONS_TRAIN_PATH = EXTERNAL_PATH + '{}_labels_train.{}' EXTERNAL_ANNOTATIONS_TEST_PATH = EXTERNAL_PATH + '{}_labels_test.{}' EXTERNAL_ANNOTATIONS_VAL_PATH = EXTERNAL_PATH + '{}_labels_val.{}' # Raw paths RAW_PATH = PROJECT_PATH + 'data/raw/' # key (integer): the id of the label # value (string): the label value LABEL_MAP_JSON_PATH = RAW_PATH + '{}_label_map.json' LABEL_MAP_PBTXT_PATH = RAW_PATH + '{}_label_map.pbtxt' # filename, xmin, ymin, xmax, ymax, label ANNOTATIONS_CSV_PATH = RAW_PATH + '{}_annotations_{}.csv' # DATASET_annotations_TRAIN/VAL/TEST.csv # Interim paths INTERIM_FOLDER_PATH = PROJECT_PATH + 'data/interim/' # key (string): filename # value (list): list of bounding boxes that correspond to the filename each with format: # [x_min, y_min, x_max, y_max, label] ANNOTATIONS_DICT_PATH = INTERIM_FOLDER_PATH + 'annotations_{}_{}_dict.json' # annotations_DATASET_TRAIN/VAL/TEST_dict.p # Processed paths PROCESSED_PROJECT_FOLDER_PATH = PROJECT_PATH + 'data/processed/' TFRECORDS_PATH = '{}_{}_{}.records' # DATASET_TRAIN/VAL/TEST_SHARD-NSHARDS.records """ Models """ MODELS_PROJECT_PATH = PROJECT_PATH + 'models/{}/{}/' CHECKPOINTS = 'checkpoints/' LOGS = 'logs/' FIGURES = 'figures/' MODELS_DIRS = [CHECKPOINTS, LOGS, FIGURES] YOLOv3 = 'YOLOv3' Tiny_YOLOv3 = 'Tiny_YOLOv3' """ Model """ IMAGE_FEATURE_MAP = { 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/filename': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/object/bbox/xmin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), 'image/object/class/label': tf.io.VarLenFeature(tf.float32), } TRAINABLE_ALL = "all" TRAINABLE_FEATURES = "features" TRAINABLE_LAST_BLOCK = "last_block" TRAINABLE_LAST_CONV = "last_conv" # YOLO YOLO_DEFAULT_IMAGE_RES = 416 YOLO_DEFAULT_ANCHORS = np.array([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45), (59, 119), (116, 90), (156, 198), (373, 326)], np.float32) / YOLO_DEFAULT_IMAGE_RES YOLO_DEFAULT_ANCHOR_MASKS = np.array([[6, 7, 8], [3, 4, 5], [0, 1, 2]]) TINY_YOLO_DEFAULT_ANCHORS = np.array([(10, 14), (23, 27), (37, 58), (81, 82), (135, 169), (344, 319)], np.float32) / YOLO_DEFAULT_IMAGE_RES TINY_YOLO_DEFAULT_ANCHOR_MASKS = np.array([[3, 4, 5], [0, 1, 2]]) """ Visualization """ colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 128, 0), (128, 0, 255), (255, 0, 128), (255, 255, 0), (255, 0, 255), (0, 255, 255), (205, 128, 77), (128, 0, 128), (0, 128, 128), (255, 255, 255), (128, 128, 128), (0, 0, 0)] # Colors for printing in command line C_HEADER = '\033[95m' C_OKBLUE = '\033[94m' C_OKGREEN = '\033[92m' C_WARNING = '\033[33m' C_FAIL = '\033[91m' C_ENDC = '\033[0m' C_BOLD = '\033[1m' C_UNDERLINE = '\033[4m'
[ "os.path.dirname", "numpy.array", "tensorflow.io.VarLenFeature", "tensorflow.io.FixedLenFeature" ]
[((3649, 3692), 'numpy.array', 'np.array', (['[[6, 7, 8], [3, 4, 5], [0, 1, 2]]'], {}), '([[6, 7, 8], [3, 4, 5], [0, 1, 2]])\n', (3657, 3692), True, 'import numpy as np\n'), ((3942, 3974), 'numpy.array', 'np.array', (['[[3, 4, 5], [0, 1, 2]]'], {}), '([[3, 4, 5], [0, 1, 2]])\n', (3950, 3974), True, 'import numpy as np\n'), ((2627, 2679), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {'default_value': '(0)'}), '([], tf.int64, default_value=0)\n', (2648, 2679), True, 'import tensorflow as tf\n'), ((2700, 2752), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {'default_value': '(0)'}), '([], tf.int64, default_value=0)\n', (2721, 2752), True, 'import tensorflow as tf\n'), ((2775, 2829), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.string'], {'default_value': '""""""'}), "([], tf.string, default_value='')\n", (2796, 2829), True, 'import tensorflow as tf\n'), ((2853, 2907), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.string'], {'default_value': '""""""'}), "([], tf.string, default_value='')\n", (2874, 2907), True, 'import tensorflow as tf\n'), ((2939, 2970), 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), '(tf.float32)\n', (2958, 2970), True, 'import tensorflow as tf\n'), ((3002, 3033), 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), '(tf.float32)\n', (3021, 3033), True, 'import tensorflow as tf\n'), ((3065, 3096), 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), '(tf.float32)\n', (3084, 3096), True, 'import tensorflow as tf\n'), ((3128, 3159), 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), '(tf.float32)\n', (3147, 3159), True, 'import tensorflow as tf\n'), ((3193, 3224), 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), '(tf.float32)\n', (3212, 3224), True, 'import tensorflow as tf\n'), ((3412, 3534), 'numpy.array', 'np.array', (['[(10, 13), (16, 30), (33, 23), (30, 61), (62, 45), (59, 119), (116, 90), (\n 156, 198), (373, 326)]', 'np.float32'], {}), '([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45), (59, 119), (116,\n 90), (156, 198), (373, 326)], np.float32)\n', (3420, 3534), True, 'import numpy as np\n'), ((3722, 3812), 'numpy.array', 'np.array', (['[(10, 14), (23, 27), (37, 58), (81, 82), (135, 169), (344, 319)]', 'np.float32'], {}), '([(10, 14), (23, 27), (37, 58), (81, 82), (135, 169), (344, 319)],\n np.float32)\n', (3730, 3812), True, 'import numpy as np\n'), ((453, 470), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (460, 470), False, 'from os.path import abspath, dirname\n')]
import unittest import numpy as np from data_structure_collection.matrix import product class TestProduct(unittest.TestCase): def test_product(self): mat1 = [[2, 4], [3, 4]] mat2 = [[1, 2], [1, 3]] m1, m2, n1, n2 = 2, 2, 2, 2 res = product(m1, m2, mat1, n1, n2, mat2) self.assertTrue(np.array_equal(np.array(res), np.dot(mat1, mat2)))
[ "numpy.dot", "data_structure_collection.matrix.product", "numpy.array" ]
[((272, 307), 'data_structure_collection.matrix.product', 'product', (['m1', 'm2', 'mat1', 'n1', 'n2', 'mat2'], {}), '(m1, m2, mat1, n1, n2, mat2)\n', (279, 307), False, 'from data_structure_collection.matrix import product\n'), ((347, 360), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (355, 360), True, 'import numpy as np\n'), ((362, 380), 'numpy.dot', 'np.dot', (['mat1', 'mat2'], {}), '(mat1, mat2)\n', (368, 380), True, 'import numpy as np\n')]
import codecs import numpy as np import re from typing import Tuple, List, Dict import model import utils def load_sentences(path: str) -> List[List[List[str]]]: sentences = [] sentence = [] for line in codecs.open(path, 'r', 'utf-8'): line = re.sub(r'[0-9]', '0', line.rstrip()) if not line: if len(sentence) > 0: if 'DOCSTART' not in sentence[0][0]: sentences.append(sentence) sentence = [] else: word = line.split() # List[str] assert len(word) >= 2 sentence.append(word) # List[List[str]] if len(sentence) > 0: if 'DOCSTART' not in sentence[0][0]: sentences.append(sentence) # List[List[List[str]]] utils.update_tag_scheme(sentences, 'iobes') # iobes or iob return sentences def word_mapping(sentences: List[List[List[str]]]): words = [[x[0] for x in s] for s in sentences] dico = utils.create_dico(words) dico['<PAD>'] = 10000001 dico['<UNK>'] = 10000000 dico = {k: v for k, v in dico.items() if v >= 3} word_to_id, id_to_word = utils.create_desc_mapping(dico) print("Found {} unique words ({} in total).".format(len(dico), sum(len(x) for x in words))) return dico, word_to_id, id_to_word def char_mapping(sentences: List[List[List[str]]]): chars: List[List[str]] = ["".join([w[0] for w in s]) for s in sentences] # List[List[char]] dico = utils.create_dico(chars) dico['<PAD>'] = 10000000 char_to_id, id_to_char = utils.create_desc_mapping(dico) print("Found {} unique characters.".format(len(dico))) return dico, char_to_id, id_to_char def tag_mapping(sentences: List[List[List[str]]]): tags = [[word[-1] for word in s] for s in sentences] dico = utils.create_dico(tags) dico[model.SOS_TAG] = -1 dico[model.EOS_TAG] = -2 tag_to_id, id_to_tag = utils.create_desc_mapping(dico) print("Found {} unique named entity tags.".format(len(dico))) return dico, tag_to_id, id_to_tag def load_pretrained_embedding(dictionary: Dict[str, int], pretrained_path: str, word_dim: int): print('Loading pretrained embedding from {}...'.format(pretrained_path)) lines = list(codecs.open(pretrained_path, 'r', 'utf-8')) pretrained = set([line.strip().split()[0].strip() for line in lines]) for word in pretrained: if word not in dictionary: dictionary[word] = 0 word_to_id, id_to_word = utils.create_desc_mapping(dictionary) all_word_embedding = {} for line in lines: s = line.strip().split() if len(s) == word_dim + 1: all_word_embedding[s[0]] = np.array([float(i) for i in s[1:]]) word_embedding: np.ndarray = np.random.uniform(-np.sqrt(0.06), np.sqrt(0.06), (len(word_to_id), word_dim)) for w in word_to_id: if w in all_word_embedding: word_embedding[word_to_id[w]] = all_word_embedding[w] elif w.lower() in all_word_embedding: word_embedding[word_to_id[w]] = all_word_embedding[w.lower()] print('Loaded {} pretrained embedding.'.format(len(all_word_embedding))) return dictionary, word_to_id, id_to_word, word_embedding class Data: """ Single line of data in dataset. """ def __init__(self, str_words: List[str], words: List[int], chars: List[List[int]], chars_mask: List[List[int]], chars_length: List[int], chars_d: Dict[int, int], caps: List[int], tags: List[int]): self.str_words = str_words self.words = words self.chars = chars self.chars_mask = chars_mask self.chars_length = chars_length self.chars_d = chars_d self.caps = caps self.tags = tags self.words_prefix_ids: List[List[int]] = [] self.words_suffix_ids: List[List[int]] = [] def prepare_dataset(sentences: List[List[List[str]]], word_to_id: Dict[str, int], char_to_id: Dict[str, int], tag_to_id: Dict[str, int]) -> List[Data]: dataset: List[Data] = [] for sentence in sentences: str_words = [word[0] for word in sentence] words = [word_to_id[word if word in word_to_id else '<UNK>'] for word in str_words] chars = [[char_to_id[char] for char in word if char in char_to_id] for word in str_words] # Skip characters that are not in the training set chars_mask, chars_length, chars_d = utils.align_char_lists(chars) caps = [model.cap_feature(word) for word in str_words] tags = [tag_to_id[word[-1]] for word in sentence] data = Data(str_words=str_words, words=words, chars=chars, chars_mask=chars_mask, chars_length=chars_length, chars_d=chars_d, caps=caps, tags=tags) dataset.append(data) return dataset def add_affix_to_datasets(train_data: List[Data], val_data: List[Data], test_data: List[Data]): print('Generating affix list from training dataset...') prefix_dicts, suffix_dicts = utils.get_affix_dict_list([data.str_words for data in train_data], threshold=125) for dataset in [train_data, val_data, test_data]: for data in dataset: words_prefix_ids, words_suffix_ids = utils.get_words_affix_ids(data.str_words, prefix_dicts, suffix_dicts) data.words_prefix_ids = words_prefix_ids # List[List[int]], dim0: words, dim1: n-grams (# = 4), value: id (>=0) data.words_suffix_ids = words_suffix_ids return prefix_dicts, suffix_dicts
[ "codecs.open", "utils.update_tag_scheme", "utils.create_dico", "utils.create_desc_mapping", "model.cap_feature", "utils.align_char_lists", "utils.get_words_affix_ids", "numpy.sqrt", "utils.get_affix_dict_list" ]
[((218, 249), 'codecs.open', 'codecs.open', (['path', '"""r"""', '"""utf-8"""'], {}), "(path, 'r', 'utf-8')\n", (229, 249), False, 'import codecs\n'), ((774, 817), 'utils.update_tag_scheme', 'utils.update_tag_scheme', (['sentences', '"""iobes"""'], {}), "(sentences, 'iobes')\n", (797, 817), False, 'import utils\n'), ((971, 995), 'utils.create_dico', 'utils.create_dico', (['words'], {}), '(words)\n', (988, 995), False, 'import utils\n'), ((1136, 1167), 'utils.create_desc_mapping', 'utils.create_desc_mapping', (['dico'], {}), '(dico)\n', (1161, 1167), False, 'import utils\n'), ((1466, 1490), 'utils.create_dico', 'utils.create_dico', (['chars'], {}), '(chars)\n', (1483, 1490), False, 'import utils\n'), ((1549, 1580), 'utils.create_desc_mapping', 'utils.create_desc_mapping', (['dico'], {}), '(dico)\n', (1574, 1580), False, 'import utils\n'), ((1801, 1824), 'utils.create_dico', 'utils.create_dico', (['tags'], {}), '(tags)\n', (1818, 1824), False, 'import utils\n'), ((1910, 1941), 'utils.create_desc_mapping', 'utils.create_desc_mapping', (['dico'], {}), '(dico)\n', (1935, 1941), False, 'import utils\n'), ((2481, 2518), 'utils.create_desc_mapping', 'utils.create_desc_mapping', (['dictionary'], {}), '(dictionary)\n', (2506, 2518), False, 'import utils\n'), ((4981, 5066), 'utils.get_affix_dict_list', 'utils.get_affix_dict_list', (['[data.str_words for data in train_data]'], {'threshold': '(125)'}), '([data.str_words for data in train_data],\n threshold=125)\n', (5006, 5066), False, 'import utils\n'), ((2238, 2280), 'codecs.open', 'codecs.open', (['pretrained_path', '"""r"""', '"""utf-8"""'], {}), "(pretrained_path, 'r', 'utf-8')\n", (2249, 2280), False, 'import codecs\n'), ((2781, 2794), 'numpy.sqrt', 'np.sqrt', (['(0.06)'], {}), '(0.06)\n', (2788, 2794), True, 'import numpy as np\n'), ((4434, 4463), 'utils.align_char_lists', 'utils.align_char_lists', (['chars'], {}), '(chars)\n', (4456, 4463), False, 'import utils\n'), ((2766, 2779), 'numpy.sqrt', 'np.sqrt', (['(0.06)'], {}), '(0.06)\n', (2773, 2779), True, 'import numpy as np\n'), ((4480, 4503), 'model.cap_feature', 'model.cap_feature', (['word'], {}), '(word)\n', (4497, 4503), False, 'import model\n'), ((5196, 5265), 'utils.get_words_affix_ids', 'utils.get_words_affix_ids', (['data.str_words', 'prefix_dicts', 'suffix_dicts'], {}), '(data.str_words, prefix_dicts, suffix_dicts)\n', (5221, 5265), False, 'import utils\n')]
from DataSets.DS.fashion_mnist import FashionMnist from DataSets.DS.svhn_cropped import SVHN from DataSets.DS.cifar10 import Cifar10 from DataSets.DS.mnist import MNIST import numpy as np class GetData: @staticmethod def get_ds(name): """ Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data """ if name == "MNIST": ds = MNIST() return ds[name] elif name == "MNIST-C": ds = MNIST() return ds[name] elif name == "FashionMnist": ds = FashionMnist() return ds["Fashion"] elif name == "svhn_cropped": ds = SVHN() return ds["svhn_cropped"] elif name == "cifar10": ds = Cifar10() return ds["cifar10"] elif name == "cifar10-C": ds = Cifar10() return ds["cifar10-C"] else: print("Not found") return None @staticmethod def get_filter(x_data, y_data, list_values): """ Filter data :param x_data: original x_data :param y_data: original y_data :param list_values: list values to take :return: new x_data, new y_data """ for j, value in enumerate(list_values): if j == 0: x_data_index = np.array(list(map(lambda x: (x == value), y_data))) x_data_index = x_data_index.astype(int) else: x_data_index2 = np.array(list(map(lambda x: (x == value), y_data))) x_data_index2= x_data_index2.astype(int) x_data_index = x_data_index + x_data_index2 x_data_index = np.nonzero(x_data_index)[0] x_data = x_data[x_data_index] y_data = y_data[x_data_index] return x_data, y_data @staticmethod def split_data(x_data, y_data, split=0.8): """ Split data :param x_data: original x_data :param y_data: original y_data :param split: percentage to split [0,1] :return: x_split_1, y_split_1, x_split_2, y_split_2 """ split = int(len(x_data) * split) x_split_1 = x_data[:split] y_split_1 = y_data[:split] x_split_2 = x_data[split:] y_split_2 = y_data[split:] return x_split_1, y_split_1, x_split_2, y_split_2
[ "DataSets.DS.svhn_cropped.SVHN", "numpy.nonzero", "DataSets.DS.fashion_mnist.FashionMnist", "DataSets.DS.cifar10.Cifar10", "DataSets.DS.mnist.MNIST" ]
[((416, 423), 'DataSets.DS.mnist.MNIST', 'MNIST', ([], {}), '()\n', (421, 423), False, 'from DataSets.DS.mnist import MNIST\n'), ((1725, 1749), 'numpy.nonzero', 'np.nonzero', (['x_data_index'], {}), '(x_data_index)\n', (1735, 1749), True, 'import numpy as np\n'), ((501, 508), 'DataSets.DS.mnist.MNIST', 'MNIST', ([], {}), '()\n', (506, 508), False, 'from DataSets.DS.mnist import MNIST\n'), ((591, 605), 'DataSets.DS.fashion_mnist.FashionMnist', 'FashionMnist', ([], {}), '()\n', (603, 605), False, 'from DataSets.DS.fashion_mnist import FashionMnist\n'), ((693, 699), 'DataSets.DS.svhn_cropped.SVHN', 'SVHN', ([], {}), '()\n', (697, 699), False, 'from DataSets.DS.svhn_cropped import SVHN\n'), ((787, 796), 'DataSets.DS.cifar10.Cifar10', 'Cifar10', ([], {}), '()\n', (794, 796), False, 'from DataSets.DS.cifar10 import Cifar10\n'), ((881, 890), 'DataSets.DS.cifar10.Cifar10', 'Cifar10', ([], {}), '()\n', (888, 890), False, 'from DataSets.DS.cifar10 import Cifar10\n')]
# HASPR - High-Altitude Solar Power Research # Script to calculate aggregate lower bounds and historic variance given a directory of individual expected output # Version 0.1 # Author: neyring import numpy as np from numpy import genfromtxt from os import walk import haspr from haspr import Result # Parameters # # directory containing individual expected outputs: inputDirectory = "D:\\00_Results\\02_Generation Profiles\\Case 1 - Flat\\0 Individual Expected Output" # directory to write output to: haspr.outputDirectory = "D:\\00_Results\\Out" # OS path delimiter ("\\" for windows, "/" for unix)" haspr.osPathDelimiter = "\\" # get all file names in inputDirectory: file_names = [] for (dirpath, dirnames, filenames) in walk(inputDirectory): file_names.extend(filenames) # sum lower bound and historic variance at each timestep lower_bound = np.zeros(17520) historic_variance = np.zeros(17520) normalized_variance = np.zeros(17520) for f in file_names: file_path = inputDirectory + haspr.osPathDelimiter + f extracted_array = genfromtxt(file_path, delimiter=',', skip_header=1) lb_values = extracted_array[:, 2] hist_var_values = extracted_array[:, 3] norm_var_values = extracted_array[:, 4] lower_bound = np.add(lower_bound, lb_values) historic_variance = np.add(historic_variance, hist_var_values) normalized_variance = np.add(normalized_variance, norm_var_values) # dump results result = Result("Lower Bound & Variances") result.payload.append("Lower Bound, Historic Variance, Normalized Variance") for i in range(17520): str_to_append = str(lower_bound[i]) + ", " + str(historic_variance[i]) + ", " + str(normalized_variance[i]) result.payload.append(str_to_append) result.dump()
[ "os.walk", "numpy.zeros", "numpy.genfromtxt", "haspr.Result", "numpy.add" ]
[((747, 767), 'os.walk', 'walk', (['inputDirectory'], {}), '(inputDirectory)\n', (751, 767), False, 'from os import walk\n'), ((878, 893), 'numpy.zeros', 'np.zeros', (['(17520)'], {}), '(17520)\n', (886, 893), True, 'import numpy as np\n'), ((915, 930), 'numpy.zeros', 'np.zeros', (['(17520)'], {}), '(17520)\n', (923, 930), True, 'import numpy as np\n'), ((954, 969), 'numpy.zeros', 'np.zeros', (['(17520)'], {}), '(17520)\n', (962, 969), True, 'import numpy as np\n'), ((1476, 1509), 'haspr.Result', 'Result', (['"""Lower Bound & Variances"""'], {}), "('Lower Bound & Variances')\n", (1482, 1509), False, 'from haspr import Result\n'), ((1075, 1126), 'numpy.genfromtxt', 'genfromtxt', (['file_path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(file_path, delimiter=',', skip_header=1)\n", (1085, 1126), False, 'from numpy import genfromtxt\n'), ((1277, 1307), 'numpy.add', 'np.add', (['lower_bound', 'lb_values'], {}), '(lower_bound, lb_values)\n', (1283, 1307), True, 'import numpy as np\n'), ((1333, 1375), 'numpy.add', 'np.add', (['historic_variance', 'hist_var_values'], {}), '(historic_variance, hist_var_values)\n', (1339, 1375), True, 'import numpy as np\n'), ((1403, 1447), 'numpy.add', 'np.add', (['normalized_variance', 'norm_var_values'], {}), '(normalized_variance, norm_var_values)\n', (1409, 1447), True, 'import numpy as np\n')]
# # Copyright (c) 2020 IBM Corp. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # arrow_conversion.py # # Part of text_extensions_for_pandas # # Provide Arrow compatible classes for serializing to pyarrow. # from distutils.version import LooseVersion import numpy as np import pyarrow as pa from text_extensions_for_pandas.array.span import SpanArray from text_extensions_for_pandas.array.token_span import TokenSpanArray, _EMPTY_SPAN_ARRAY_SINGLETON from text_extensions_for_pandas.array.tensor import TensorArray from text_extensions_for_pandas.array.string_table import StringTable class ArrowSpanType(pa.PyExtensionType): """ PyArrow extension type definition for conversions to/from Span columns """ BEGINS_NAME = "span_begins" ENDS_NAME = "span_ends" TARGET_TEXT_DICT_NAME = "target_text" def __init__(self, index_dtype, target_text_dict_dtype): """ Create an instance of a Span data type with given index type and target text dictionary type. The dictionary type will hold target text ids that map to a dictionary of document target texts. :param index_dtype: type for the begin, end index arrays :param target_text_dict_dtype: type for the target text dictionary array """ assert pa.types.is_integer(index_dtype) assert pa.types.is_dictionary(target_text_dict_dtype) fields = [ pa.field(self.BEGINS_NAME, index_dtype), pa.field(self.ENDS_NAME, index_dtype), pa.field(self.TARGET_TEXT_DICT_NAME, target_text_dict_dtype) ] pa.PyExtensionType.__init__(self, pa.struct(fields)) def __reduce__(self): index_dtype = self.storage_type[self.BEGINS_NAME].type target_text_dict_dtype = self.storage_type[self.TARGET_TEXT_DICT_NAME].type return ArrowSpanType, (index_dtype, target_text_dict_dtype) class ArrowTokenSpanType(pa.PyExtensionType): """ PyArrow extension type definition for conversions to/from TokenSpan columns """ BEGINS_NAME = "token_begins" ENDS_NAME = "token_ends" TOKENS_NAME = "tokens" def __init__(self, index_dtype, token_dict_dtype): """ Create an instance of a TokenSpan data type with given index type and target text that will be stored in Field metadata. :param index_dtype: type for the begin, end index arrays :param token_dict_dtype: type for the tokens dictionary array """ assert pa.types.is_integer(index_dtype) assert pa.types.is_dictionary(token_dict_dtype) fields = [ pa.field(self.BEGINS_NAME, index_dtype), pa.field(self.ENDS_NAME, index_dtype), pa.field(self.TOKENS_NAME, token_dict_dtype), ] pa.PyExtensionType.__init__(self, pa.struct(fields)) def __reduce__(self): index_dtype = self.storage_type[self.BEGINS_NAME].type token_dict_dtype = self.storage_type[self.TOKENS_NAME].type return ArrowTokenSpanType, (index_dtype, token_dict_dtype) def span_to_arrow(char_span: SpanArray) -> pa.ExtensionArray: """ Convert a SpanArray to a pyarrow.ExtensionArray with a type of ArrowSpanType and struct as the storage type. The resulting extension array can be serialized and transferred with standard Arrow protocols. :param char_span: A SpanArray to be converted :return: pyarrow.ExtensionArray containing Span data """ if LooseVersion(pa.__version__) < LooseVersion("2.0.0"): raise NotImplementedError("Arrow serialization for SpanArray is not supported with " "PyArrow versions < 2.0.0") # Create array for begins, ends begins_array = pa.array(char_span.begin) ends_array = pa.array(char_span.end) # Create a dictionary array from StringTable used in this span dictionary = pa.array([char_span._string_table.unbox(s) for s in char_span._string_table.things]) target_text_dict_array = pa.DictionaryArray.from_arrays(char_span._text_ids, dictionary) typ = ArrowSpanType(begins_array.type, target_text_dict_array.type) fields = list(typ.storage_type) storage = pa.StructArray.from_arrays([begins_array, ends_array, target_text_dict_array], fields=fields) return pa.ExtensionArray.from_storage(typ, storage) def arrow_to_span(extension_array: pa.ExtensionArray) -> SpanArray: """ Convert a pyarrow.ExtensionArray with type ArrowSpanType to a SpanArray. ..NOTE: Only supported with PyArrow >= 2.0.0 :param extension_array: pyarrow.ExtensionArray with type ArrowSpanType :return: SpanArray """ if LooseVersion(pa.__version__) < LooseVersion("2.0.0"): raise NotImplementedError("Arrow serialization for SpanArray is not supported with " "PyArrow versions < 2.0.0") if isinstance(extension_array, pa.ChunkedArray): if extension_array.num_chunks > 1: raise ValueError("Only pyarrow.Array with a single chunk is supported") extension_array = extension_array.chunk(0) # NOTE: workaround for bug in parquet reading if pa.types.is_struct(extension_array.type): index_dtype = extension_array.field(ArrowSpanType.BEGINS_NAME).type target_text_dict_dtype = extension_array.field(ArrowSpanType.TARGET_TEXT_DICT_NAME).type extension_array = pa.ExtensionArray.from_storage( ArrowSpanType(index_dtype, target_text_dict_dtype), extension_array) assert pa.types.is_struct(extension_array.storage.type) # Create target text StringTable and text_ids from dictionary array target_text_dict_array = extension_array.storage.field(ArrowSpanType.TARGET_TEXT_DICT_NAME) table_texts = target_text_dict_array.dictionary.to_pylist() string_table = StringTable.from_things(table_texts) text_ids = target_text_dict_array.indices.to_numpy() # Get the begins/ends pyarrow arrays begins_array = extension_array.storage.field(ArrowSpanType.BEGINS_NAME) ends_array = extension_array.storage.field(ArrowSpanType.ENDS_NAME) # Zero-copy convert arrays to numpy begins = begins_array.to_numpy() ends = ends_array.to_numpy() return SpanArray((string_table, text_ids), begins, ends) def token_span_to_arrow(token_span: TokenSpanArray) -> pa.ExtensionArray: """ Convert a TokenSpanArray to a pyarrow.ExtensionArray with a type of ArrowTokenSpanType and struct as the storage type. The resulting extension array can be serialized and transferred with standard Arrow protocols. :param token_span: A TokenSpanArray to be converted :return: pyarrow.ExtensionArray containing TokenSpan data """ if LooseVersion(pa.__version__) < LooseVersion("2.0.0"): raise NotImplementedError("Arrow serialization for TokenSpanArray is not supported with " "PyArrow versions < 2.0.0") # Create arrays for begins/ends token_begins_array = pa.array(token_span.begin_token) token_ends_array = pa.array(token_span.end_token) # Filter out any empty SpanArrays non_null_tokens = token_span.tokens[~token_span.isna()] assert len(non_null_tokens) > 0 # Get either single document as a list or use a list of all if multiple docs if all([token is non_null_tokens[0] for token in non_null_tokens]): tokens_arrays = [non_null_tokens[0]] tokens_indices = pa.array([0] * len(token_span.tokens), mask=token_span.isna()) else: raise NotImplementedError("TokenSpan Multi-doc serialization not yet implemented due to " "ArrowNotImplementedError: Concat with dictionary unification NYI") tokens_arrays = non_null_tokens tokens_indices = np.zeros_like(token_span.tokens) tokens_indices[~token_span.isna()] = range(len(tokens_arrays)) tokens_indices = pa.array(tokens_indices, mask=token_span.isna()) # Convert each token SpanArray to Arrow and get as raw storage arrow_tokens_arrays = [span_to_arrow(sa).storage for sa in tokens_arrays] # Create a list array with each element is an ArrowSpanArray # TODO: pyarrow.lib.ArrowNotImplementedError: ('Sequence converter for type dictionary<values=string, indices=int8, ordered=0> not implemented', 'Conversion failed for column ts1 with type TokenSpanDtype') #arrow_tokens_arrays_array = pa.array(arrow_tokens_arrays, type=pa.list_(arrow_tokens_arrays[0].type)) offsets = [0] + [len(a) for a in arrow_tokens_arrays] values = pa.concat_arrays(arrow_tokens_arrays) # TODO: can't concat extension arrays? arrow_tokens_arrays_array = pa.ListArray.from_arrays(offsets, values) # Create a dictionary array mapping each token SpanArray index used to the list of ArrowSpanArrays tokens_dict_array = pa.DictionaryArray.from_arrays(tokens_indices, arrow_tokens_arrays_array) typ = ArrowTokenSpanType(token_begins_array.type, tokens_dict_array.type) fields = list(typ.storage_type) storage = pa.StructArray.from_arrays([token_begins_array, token_ends_array, tokens_dict_array], fields=fields) return pa.ExtensionArray.from_storage(typ, storage) def arrow_to_token_span(extension_array: pa.ExtensionArray) -> TokenSpanArray: """ Convert a pyarrow.ExtensionArray with type ArrowTokenSpanType to a TokenSpanArray. :param extension_array: pyarrow.ExtensionArray with type ArrowTokenSpanType :return: TokenSpanArray """ if LooseVersion(pa.__version__) < LooseVersion("2.0.0"): raise NotImplementedError("Arrow serialization for TokenSpanArray is not supported with " "PyArrow versions < 2.0.0") if isinstance(extension_array, pa.ChunkedArray): if extension_array.num_chunks > 1: raise ValueError("Only pyarrow.Array with a single chunk is supported") extension_array = extension_array.chunk(0) assert pa.types.is_struct(extension_array.storage.type) # Get the begins/ends pyarrow arrays token_begins_array = extension_array.storage.field(ArrowTokenSpanType.BEGINS_NAME) token_ends_array = extension_array.storage.field(ArrowTokenSpanType.ENDS_NAME) # Get the tokens as a dictionary array where indices map to a list of ArrowSpanArrays tokens_dict_array = extension_array.storage.field(ArrowTokenSpanType.TOKENS_NAME) tokens_indices = tokens_dict_array.indices arrow_tokens_arrays_array = tokens_dict_array.dictionary # Breakup the list of ArrowSpanArrays and convert back to individual SpanArrays tokens_arrays = [] span_type = None for i in range(1, len(arrow_tokens_arrays_array.offsets)): start = arrow_tokens_arrays_array.offsets[i - 1].as_py() stop = arrow_tokens_arrays_array.offsets[i].as_py() arrow_tokens_array = arrow_tokens_arrays_array.values[start:stop] # Make an instance of ArrowSpanType if span_type is None: begins_array = arrow_tokens_array.field(ArrowSpanType.BEGINS_NAME) target_text_dict_array = arrow_tokens_array.field(ArrowSpanType.TARGET_TEXT_DICT_NAME) span_type = ArrowSpanType(begins_array.type, target_text_dict_array.type) # Re-make the Arrow extension type to convert back to a SpanArray tokens_array = arrow_to_span(pa.ExtensionArray.from_storage(span_type, arrow_tokens_array)) tokens_arrays.append(tokens_array) # Map the token indices to the actual token SpanArray for each element in the TokenSpanArray tokens = [_EMPTY_SPAN_ARRAY_SINGLETON if i is None else tokens_arrays[i] for i in tokens_indices.to_pylist()] # Zero-copy convert arrays to numpy token_begins = token_begins_array.to_numpy() token_ends = token_ends_array.to_numpy() return TokenSpanArray(tokens, token_begins, token_ends) class ArrowTensorType(pa.PyExtensionType): """ pyarrow ExtensionType definition for TensorDtype :param element_shape: Fixed shape for each tensor element of the array, the outer dimension is the number of elements, or length, of the array. """ def __init__(self, element_shape, pyarrow_dtype): self._element_shape = element_shape pa.PyExtensionType.__init__(self, pa.list_(pyarrow_dtype)) def __reduce__(self): return ArrowTensorType, (self._element_shape, self.storage_type.value_type) @property def shape(self): return self._element_shape def __arrow_ext_class__(self): return ArrowTensorArray class ArrowTensorArray(pa.ExtensionArray): """ A batch of tensors with fixed shape. """ def __init__(self): raise TypeError("Do not call ArrowTensorBatch constructor directly, " "use one of the `ArrowTensorBatch.from_*` functions " "instead.") @staticmethod def from_numpy(obj, batch_size=None): """ Convert a list of numpy.ndarrays with equal shapes or as single numpy.ndarray with outer-dim as batch size to a pyarrow.Array """ if isinstance(obj, (list, tuple)): if batch_size is not None: def list_gen(): for i in range(0, len(obj), batch_size): slc = obj[i:i + batch_size] yield ArrowTensorArray.from_numpy(slc, batch_size=None) return list_gen() elif np.isscalar(obj[0]): return pa.array(obj) elif isinstance(obj[0], np.ndarray): # continue with batched ndarray obj = np.stack(obj, axis=0) if isinstance(obj, dict): names = list(obj.keys()) arrs = [ArrowTensorArray.from_numpy(obj[k], batch_size=batch_size) for k in names] batch = pa.RecordBatch.from_arrays(arrs, names) return pa.Table.from_batches([batch]) elif isinstance(obj, np.ndarray): # currently require contiguous ndarray if not obj.flags.c_contiguous: obj = np.ascontiguousarray(obj) pa_dtype = pa.from_numpy_dtype(obj.dtype) batch_size = obj.shape[0] element_shape = obj.shape[1:] total_num_elements = obj.size num_elements = 1 if len(obj.shape) == 1 else np.prod(element_shape) child_buf = pa.py_buffer(obj) child_array = pa.Array.from_buffers(pa_dtype, total_num_elements, [None, child_buf]) offset_buf = pa.py_buffer(np.int32([i * num_elements for i in range(batch_size + 1)])) storage = pa.Array.from_buffers(pa.list_(pa_dtype), batch_size, [None, offset_buf], children=[child_array]) typ = ArrowTensorType(element_shape, pa_dtype) return pa.ExtensionArray.from_storage(typ, storage) elif np.isscalar(obj): return pa.array([obj]) else: def iter_gen(): if batch_size is None: for d in obj: yield ArrowTensorArray.from_numpy(d, batch_size=batch_size) else: batch = [] for o in obj: batch.append(o) if len(batch) == batch_size: # merge dict if isinstance(batch[0], dict): d = {k: [v] for k, v in batch[0].items()} for i in range(1, len(batch)): for k, v in batch[i].items(): d[k].append(v) for k in d.keys(): d[k] = np.stack(d[k], axis=0) batch = d yield ArrowTensorArray.from_numpy(batch, batch_size=None) batch = [] return iter_gen() def to_numpy(self): shape = (len(self),) + self.type.shape buf = self.storage.buffers()[3] storage_list_type = self.storage.type ext_dtype = storage_list_type.value_type.to_pandas_dtype() return np.ndarray(shape, buffer=buf, dtype=ext_dtype) def arrow_to_tensor_array(extension_array: pa.ExtensionArray) -> TensorArray: """ Convert a pyarrow.ExtensionArray with type ArrowTensorType to a TensorArray. :param extension_array: pyarrow.ExtensionArray with type ArrowTensorType :return: TensorArray """ if isinstance(extension_array, pa.ChunkedArray): if extension_array.num_chunks > 1: # TODO: look into removing concat and constructing from list w/ shape values = np.concatenate([chunk.to_numpy() for chunk in extension_array.iterchunks()]) else: values = extension_array.chunk(0).to_numpy() else: values = extension_array.to_numpy() return TensorArray(values)
[ "pyarrow.ExtensionArray.from_storage", "pyarrow.concat_arrays", "pyarrow.ListArray.from_arrays", "pyarrow.types.is_struct", "text_extensions_for_pandas.array.tensor.TensorArray", "numpy.ndarray", "numpy.prod", "numpy.zeros_like", "pyarrow.from_numpy_dtype", "text_extensions_for_pandas.array.token_span.TokenSpanArray", "pyarrow.field", "pyarrow.struct", "pyarrow.Array.from_buffers", "text_extensions_for_pandas.array.span.SpanArray", "pyarrow.StructArray.from_arrays", "numpy.stack", "pyarrow.Table.from_batches", "distutils.version.LooseVersion", "pyarrow.list_", "pyarrow.array", "pyarrow.types.is_integer", "pyarrow.DictionaryArray.from_arrays", "pyarrow.RecordBatch.from_arrays", "pyarrow.types.is_dictionary", "numpy.isscalar", "text_extensions_for_pandas.array.string_table.StringTable.from_things", "pyarrow.py_buffer", "numpy.ascontiguousarray" ]
[((4249, 4274), 'pyarrow.array', 'pa.array', (['char_span.begin'], {}), '(char_span.begin)\n', (4257, 4274), True, 'import pyarrow as pa\n'), ((4292, 4315), 'pyarrow.array', 'pa.array', (['char_span.end'], {}), '(char_span.end)\n', (4300, 4315), True, 'import pyarrow as pa\n'), ((4542, 4605), 'pyarrow.DictionaryArray.from_arrays', 'pa.DictionaryArray.from_arrays', (['char_span._text_ids', 'dictionary'], {}), '(char_span._text_ids, dictionary)\n', (4572, 4605), True, 'import pyarrow as pa\n'), ((4730, 4827), 'pyarrow.StructArray.from_arrays', 'pa.StructArray.from_arrays', (['[begins_array, ends_array, target_text_dict_array]'], {'fields': 'fields'}), '([begins_array, ends_array,\n target_text_dict_array], fields=fields)\n', (4756, 4827), True, 'import pyarrow as pa\n'), ((4836, 4880), 'pyarrow.ExtensionArray.from_storage', 'pa.ExtensionArray.from_storage', (['typ', 'storage'], {}), '(typ, storage)\n', (4866, 4880), True, 'import pyarrow as pa\n'), ((5702, 5742), 'pyarrow.types.is_struct', 'pa.types.is_struct', (['extension_array.type'], {}), '(extension_array.type)\n', (5720, 5742), True, 'import pyarrow as pa\n'), ((6080, 6128), 'pyarrow.types.is_struct', 'pa.types.is_struct', (['extension_array.storage.type'], {}), '(extension_array.storage.type)\n', (6098, 6128), True, 'import pyarrow as pa\n'), ((6381, 6417), 'text_extensions_for_pandas.array.string_table.StringTable.from_things', 'StringTable.from_things', (['table_texts'], {}), '(table_texts)\n', (6404, 6417), False, 'from text_extensions_for_pandas.array.string_table import StringTable\n'), ((6788, 6837), 'text_extensions_for_pandas.array.span.SpanArray', 'SpanArray', (['(string_table, text_ids)', 'begins', 'ends'], {}), '((string_table, text_ids), begins, ends)\n', (6797, 6837), False, 'from text_extensions_for_pandas.array.span import SpanArray\n'), ((7561, 7593), 'pyarrow.array', 'pa.array', (['token_span.begin_token'], {}), '(token_span.begin_token)\n', (7569, 7593), True, 'import pyarrow as pa\n'), ((7617, 7647), 'pyarrow.array', 'pa.array', (['token_span.end_token'], {}), '(token_span.end_token)\n', (7625, 7647), True, 'import pyarrow as pa\n'), ((9123, 9160), 'pyarrow.concat_arrays', 'pa.concat_arrays', (['arrow_tokens_arrays'], {}), '(arrow_tokens_arrays)\n', (9139, 9160), True, 'import pyarrow as pa\n'), ((9233, 9274), 'pyarrow.ListArray.from_arrays', 'pa.ListArray.from_arrays', (['offsets', 'values'], {}), '(offsets, values)\n', (9257, 9274), True, 'import pyarrow as pa\n'), ((9403, 9476), 'pyarrow.DictionaryArray.from_arrays', 'pa.DictionaryArray.from_arrays', (['tokens_indices', 'arrow_tokens_arrays_array'], {}), '(tokens_indices, arrow_tokens_arrays_array)\n', (9433, 9476), True, 'import pyarrow as pa\n'), ((9607, 9711), 'pyarrow.StructArray.from_arrays', 'pa.StructArray.from_arrays', (['[token_begins_array, token_ends_array, tokens_dict_array]'], {'fields': 'fields'}), '([token_begins_array, token_ends_array,\n tokens_dict_array], fields=fields)\n', (9633, 9711), True, 'import pyarrow as pa\n'), ((9720, 9764), 'pyarrow.ExtensionArray.from_storage', 'pa.ExtensionArray.from_storage', (['typ', 'storage'], {}), '(typ, storage)\n', (9750, 9764), True, 'import pyarrow as pa\n'), ((10526, 10574), 'pyarrow.types.is_struct', 'pa.types.is_struct', (['extension_array.storage.type'], {}), '(extension_array.storage.type)\n', (10544, 10574), True, 'import pyarrow as pa\n'), ((12393, 12441), 'text_extensions_for_pandas.array.token_span.TokenSpanArray', 'TokenSpanArray', (['tokens', 'token_begins', 'token_ends'], {}), '(tokens, token_begins, token_ends)\n', (12407, 12441), False, 'from text_extensions_for_pandas.array.token_span import TokenSpanArray, _EMPTY_SPAN_ARRAY_SINGLETON\n'), ((17682, 17701), 'text_extensions_for_pandas.array.tensor.TensorArray', 'TensorArray', (['values'], {}), '(values)\n', (17693, 17701), False, 'from text_extensions_for_pandas.array.tensor import TensorArray\n'), ((1794, 1826), 'pyarrow.types.is_integer', 'pa.types.is_integer', (['index_dtype'], {}), '(index_dtype)\n', (1813, 1826), True, 'import pyarrow as pa\n'), ((1842, 1888), 'pyarrow.types.is_dictionary', 'pa.types.is_dictionary', (['target_text_dict_dtype'], {}), '(target_text_dict_dtype)\n', (1864, 1888), True, 'import pyarrow as pa\n'), ((3002, 3034), 'pyarrow.types.is_integer', 'pa.types.is_integer', (['index_dtype'], {}), '(index_dtype)\n', (3021, 3034), True, 'import pyarrow as pa\n'), ((3050, 3090), 'pyarrow.types.is_dictionary', 'pa.types.is_dictionary', (['token_dict_dtype'], {}), '(token_dict_dtype)\n', (3072, 3090), True, 'import pyarrow as pa\n'), ((3985, 4013), 'distutils.version.LooseVersion', 'LooseVersion', (['pa.__version__'], {}), '(pa.__version__)\n', (3997, 4013), False, 'from distutils.version import LooseVersion\n'), ((4016, 4037), 'distutils.version.LooseVersion', 'LooseVersion', (['"""2.0.0"""'], {}), "('2.0.0')\n", (4028, 4037), False, 'from distutils.version import LooseVersion\n'), ((5204, 5232), 'distutils.version.LooseVersion', 'LooseVersion', (['pa.__version__'], {}), '(pa.__version__)\n', (5216, 5232), False, 'from distutils.version import LooseVersion\n'), ((5235, 5256), 'distutils.version.LooseVersion', 'LooseVersion', (['"""2.0.0"""'], {}), "('2.0.0')\n", (5247, 5256), False, 'from distutils.version import LooseVersion\n'), ((7286, 7314), 'distutils.version.LooseVersion', 'LooseVersion', (['pa.__version__'], {}), '(pa.__version__)\n', (7298, 7314), False, 'from distutils.version import LooseVersion\n'), ((7317, 7338), 'distutils.version.LooseVersion', 'LooseVersion', (['"""2.0.0"""'], {}), "('2.0.0')\n", (7329, 7338), False, 'from distutils.version import LooseVersion\n'), ((8345, 8377), 'numpy.zeros_like', 'np.zeros_like', (['token_span.tokens'], {}), '(token_span.tokens)\n', (8358, 8377), True, 'import numpy as np\n'), ((10069, 10097), 'distutils.version.LooseVersion', 'LooseVersion', (['pa.__version__'], {}), '(pa.__version__)\n', (10081, 10097), False, 'from distutils.version import LooseVersion\n'), ((10100, 10121), 'distutils.version.LooseVersion', 'LooseVersion', (['"""2.0.0"""'], {}), "('2.0.0')\n", (10112, 10121), False, 'from distutils.version import LooseVersion\n'), ((16900, 16946), 'numpy.ndarray', 'np.ndarray', (['shape'], {'buffer': 'buf', 'dtype': 'ext_dtype'}), '(shape, buffer=buf, dtype=ext_dtype)\n', (16910, 16946), True, 'import numpy as np\n'), ((1921, 1960), 'pyarrow.field', 'pa.field', (['self.BEGINS_NAME', 'index_dtype'], {}), '(self.BEGINS_NAME, index_dtype)\n', (1929, 1960), True, 'import pyarrow as pa\n'), ((1974, 2011), 'pyarrow.field', 'pa.field', (['self.ENDS_NAME', 'index_dtype'], {}), '(self.ENDS_NAME, index_dtype)\n', (1982, 2011), True, 'import pyarrow as pa\n'), ((2025, 2085), 'pyarrow.field', 'pa.field', (['self.TARGET_TEXT_DICT_NAME', 'target_text_dict_dtype'], {}), '(self.TARGET_TEXT_DICT_NAME, target_text_dict_dtype)\n', (2033, 2085), True, 'import pyarrow as pa\n'), ((2139, 2156), 'pyarrow.struct', 'pa.struct', (['fields'], {}), '(fields)\n', (2148, 2156), True, 'import pyarrow as pa\n'), ((3123, 3162), 'pyarrow.field', 'pa.field', (['self.BEGINS_NAME', 'index_dtype'], {}), '(self.BEGINS_NAME, index_dtype)\n', (3131, 3162), True, 'import pyarrow as pa\n'), ((3176, 3213), 'pyarrow.field', 'pa.field', (['self.ENDS_NAME', 'index_dtype'], {}), '(self.ENDS_NAME, index_dtype)\n', (3184, 3213), True, 'import pyarrow as pa\n'), ((3227, 3271), 'pyarrow.field', 'pa.field', (['self.TOKENS_NAME', 'token_dict_dtype'], {}), '(self.TOKENS_NAME, token_dict_dtype)\n', (3235, 3271), True, 'import pyarrow as pa\n'), ((3326, 3343), 'pyarrow.struct', 'pa.struct', (['fields'], {}), '(fields)\n', (3335, 3343), True, 'import pyarrow as pa\n'), ((11914, 11975), 'pyarrow.ExtensionArray.from_storage', 'pa.ExtensionArray.from_storage', (['span_type', 'arrow_tokens_array'], {}), '(span_type, arrow_tokens_array)\n', (11944, 11975), True, 'import pyarrow as pa\n'), ((12897, 12920), 'pyarrow.list_', 'pa.list_', (['pyarrow_dtype'], {}), '(pyarrow_dtype)\n', (12905, 12920), True, 'import pyarrow as pa\n'), ((14481, 14520), 'pyarrow.RecordBatch.from_arrays', 'pa.RecordBatch.from_arrays', (['arrs', 'names'], {}), '(arrs, names)\n', (14507, 14520), True, 'import pyarrow as pa\n'), ((14540, 14570), 'pyarrow.Table.from_batches', 'pa.Table.from_batches', (['[batch]'], {}), '([batch])\n', (14561, 14570), True, 'import pyarrow as pa\n'), ((14075, 14094), 'numpy.isscalar', 'np.isscalar', (['obj[0]'], {}), '(obj[0])\n', (14086, 14094), True, 'import numpy as np\n'), ((14779, 14809), 'pyarrow.from_numpy_dtype', 'pa.from_numpy_dtype', (['obj.dtype'], {}), '(obj.dtype)\n', (14798, 14809), True, 'import pyarrow as pa\n'), ((15037, 15054), 'pyarrow.py_buffer', 'pa.py_buffer', (['obj'], {}), '(obj)\n', (15049, 15054), True, 'import pyarrow as pa\n'), ((15081, 15151), 'pyarrow.Array.from_buffers', 'pa.Array.from_buffers', (['pa_dtype', 'total_num_elements', '[None, child_buf]'], {}), '(pa_dtype, total_num_elements, [None, child_buf])\n', (15102, 15151), True, 'import pyarrow as pa\n'), ((15496, 15540), 'pyarrow.ExtensionArray.from_storage', 'pa.ExtensionArray.from_storage', (['typ', 'storage'], {}), '(typ, storage)\n', (15526, 15540), True, 'import pyarrow as pa\n'), ((15555, 15571), 'numpy.isscalar', 'np.isscalar', (['obj'], {}), '(obj)\n', (15566, 15571), True, 'import numpy as np\n'), ((14119, 14132), 'pyarrow.array', 'pa.array', (['obj'], {}), '(obj)\n', (14127, 14132), True, 'import pyarrow as pa\n'), ((14730, 14755), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['obj'], {}), '(obj)\n', (14750, 14755), True, 'import numpy as np\n'), ((14989, 15011), 'numpy.prod', 'np.prod', (['element_shape'], {}), '(element_shape)\n', (14996, 15011), True, 'import numpy as np\n'), ((15297, 15315), 'pyarrow.list_', 'pa.list_', (['pa_dtype'], {}), '(pa_dtype)\n', (15305, 15315), True, 'import pyarrow as pa\n'), ((15592, 15607), 'pyarrow.array', 'pa.array', (['[obj]'], {}), '([obj])\n', (15600, 15607), True, 'import pyarrow as pa\n'), ((14252, 14273), 'numpy.stack', 'np.stack', (['obj'], {'axis': '(0)'}), '(obj, axis=0)\n', (14260, 14273), True, 'import numpy as np\n'), ((16440, 16462), 'numpy.stack', 'np.stack', (['d[k]'], {'axis': '(0)'}), '(d[k], axis=0)\n', (16448, 16462), True, 'import numpy as np\n')]