[
"# Graph to visualize predicted versus actual acid pKa for similarity model\n# Splits the same way as the model training\nimport matplotlib.pyplot as plt\nfrom rdkit import Chem\nfrom rdkit.Chem import rdMolDescriptors\nfrom chemical_models import AcidSimilarity\nfrom sklearn.model_selection import train_test_split\n\n# Load model\nacid_model = AcidSimilarity('acid_sim')\n\nacid_data = open('data/pKa/formatted_acidic.txt', 'r')\nacids = []\n\n# Read file to gather reference acids\nfor line in acid_data.readlines():\n split = line.split(' ')\n mol = Chem.MolFromSmiles(split[0])\n fingerprint = rdMolDescriptors.GetHashedAtomPairFingerprintAsBitVect(mol)\n acids.append([split[0], float(split[1][:-1]), fingerprint])\n\n# Split data into reference set that will be used to get similarity and\n# test set which will be used to train and validate the model\nreference, test = train_test_split(acids, test_size=0.5, random_state=1)\n\nX = []\ny = []\n\n# Set x to predicted values and y to actual\nfor acid in test:\n X.append(acid_model.run(acid[0], acids))\n y.append(acid[1])\n\n# Split data into training and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=1)\n\n# Plot the data used to train the model as red and validation data as blue\n# If overfit the red data will fit the line significantly more frequently\n# than blue\nplt.scatter(X_train, y_train, s=1, color='red')\nplt.scatter(X_test, y_test, s=1, color='blue')\nplt.show()\n"
]
[
"# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\nimport time\nimport pandas as pd\nimport subprocess\nimport ipywidgets as widgets\nimport logging\nimport numpy as np\nimport os\nimport signal\nfrom turbine import WindTurbine\n\nclass WindTurbineFarmSimulator(object):\n def __init__(self, n_turbines=5):\n self.n_turbines = n_turbines\n \n # read the raw data. This data was captured from real sensors installed in the mini Wind Turbine\n self.raw_data = pd.read_csv('data/dataset_wind.csv.gz', compression=\"gzip\", sep=',', low_memory=False).values\n \n # now create the virtual wind turbines\n self.turbines = [WindTurbine(i, self.raw_data) for i in range(n_turbines)]\n self.data_buffer = [[] for i in range(n_turbines)]\n self.running = False\n self.agents = None\n self.halted = False \n \n self.feature_ids = np.array([8,9,10,7, 22, 5, 6]) # qX,qy,qz,qw ,wind_seed_rps, rps, voltage \n self.feature_names = np.array(['qx', 'qy', 'qz', 'qw', 'wind speed rps', 'rps', 'voltage'])\n self.colors = np.array([ 'r', 'g', 'y', 'b', 'r', 'g', 'b'])\n \n self.max_buffer_size = 500\n for idx in range(n_turbines):\n for j in range(self.max_buffer_size):\n self.__read_next_turbine_sample__(idx)\n\n self.dashboard = widgets.Textarea(value='\\n' * self.n_turbines, disabled=True,\n layout={'border': '1px solid black', 'width': '850px', 'height': '90px'})\n\n def __del__(self):\n self.halt()\n \n def __launch_agent__(self, agent_id):\n \"\"\"\n Launches Linux processes for each Edge Agent. \n They will run in background and listen to a unix socket\n \"\"\"\n # remove channel\n subprocess.Popen([\"rm\", \"-f\", \"/tmp/agent%d\" % agent_id])\n # launch main process\n cmd = \"./agent/bin/sagemaker_edge_agent_binary -c agent/conf/config_edge_device_%d.json -a /tmp/agent%d\" % (agent_id, agent_id)\n logs = open(\"agent/logs/agent%d.log\" % agent_id, \"+w\")\n # we need to return the process in order to terminate it later\n return subprocess.Popen(cmd.split(' '), stdout=logs)\n\n def __prep_turbine_sample__(self, turbine_id, data):\n vib_noise,rot_noise,vol_noise = self.is_noise_enabled(turbine_id)\n #np.array([8,9,10,7, 22, 5, 6]) # qX,qy,qz,qw ,wind_seed_rps, rps, voltage \n if vib_noise: data[self.feature_ids[0:4]] = np.random.rand(4) * 100 # out of the radians range\n if rot_noise: data[self.feature_ids[5]] = np.random.rand(1) * 100 # out of the normalized wind range\n if vol_noise: data[self.feature_ids[6]] = int(np.random.rand(1)[0] * 10000) # out of the normalized voltage range\n\n self.data_buffer[turbine_id].append(data)\n if len(self.data_buffer[turbine_id]) > self.max_buffer_size:\n del self.data_buffer[turbine_id][0]\n \n def __read_next_turbine_sample__(self, turbine_id):\n self.__prep_turbine_sample__(turbine_id, self.turbines[turbine_id].read_next_sample() )\n \n def is_turbine_running(self, turbine_id):\n return self.turbines[turbine_id].is_running()\n \n def show(self): \n return widgets.VBox([\n widgets.HBox([t.show() for t in self.turbines]),\n self.dashboard\n ])\n\n def update_dashboard(self, turbine_id, data):\n if not self.turbines[turbine_id].is_running(): return\n lines = self.dashboard.value.split('\\n') \n features = np.mean(data[-50:,self.feature_ids], axis=0)\n tokens = [\"%s: %0.3f\" % (self.feature_names[i], features[i]) for i in range(len(features))]\n lines[turbine_id] = ' '.join([\"Turbine: %d\" % turbine_id] + tokens) \n self.dashboard.value = '\\n'.join(lines)\n\n def start(self):\n \"\"\"\n Run the main application by creating the Edge Agents, loading the model and\n kicking-off the anomaly detector program\n \"\"\"\n if not self.running and not self.halted:\n self.running = True\n logging.info(\"Launching Edge Manager Agents...\")\n self.agents = [self.__launch_agent__(i) for i in range(self.n_turbines)]\n logging.info(\"Agents launched! (waiting 5 secs)\")\n time.sleep(5) # give some time for the agents to launch\n \n def halt(self):\n if self.running:\n self.running = False\n self.halted = True\n # halt all the turbines\n for i in self.turbines: i.halt() \n # kill the agents\n for i in self.agents: \n #os.kill(i.pid, signal.SIGINT)\n i.kill()\n i.wait()\n\n def get_num_turbines(self):\n return self.n_turbines\n \n def get_raw_data(self, turbine_id): \n assert(turbine_id >= 0 and turbine_id < len(self.data_buffer))\n self.__read_next_turbine_sample__(turbine_id)\n return self.data_buffer[turbine_id]\n \n def detected_anomalies(self, turbine_id, values, anomalies):\n assert(turbine_id >= 0 and turbine_id < len(self.data_buffer))\n self.turbines[turbine_id].detected_anomalies(values, anomalies)\n\n def update_label(self, turbine_id, value ):\n self.turbines[turbine_id].update_label(value)\n\n def is_noise_enabled(self, turbine_id):\n return [self.turbines[turbine_id].is_noise_enabled('Vib'),\n self.turbines[turbine_id].is_noise_enabled('Rot'),\n self.turbines[turbine_id].is_noise_enabled('Vol')]\n\n"
]
[
"import tensorflow as tf\nimport random\nimport numpy as np\n\nclass Reinforce():\n def __init__(self,\n sess,\n optimizer,\n policy_network,\n max_layers,\n global_step,\n division_rate= 100.0,\n reg_param=0.001,\n discount_factor=0.99,\n exploration=0.3):\n\n '''\n Notation:\n policy network : used describe model that predicts hyperparameters\n learned network : learned network with hyper params as recommended\n\n Args:\n sess: tensorflow session\n optimizer : type of optimization algorithm used for minimization\n policy network : final tensorflow output state of the policy network\n max_layers: the maximum number of layers for the learned neural network\n global_step : number of cycles of learning of policy network (i,e gradient updates)\n reg_param : lambda for l2 regularizaion of loss of policy network\n discoun_factor : as stated\n exploration : not used for anything right now (but meant for random exploration)\n '''\n \n self.sess = sess\n self.optimizer = optimizer\n self.policy_network = policy_network \n self.division_rate = division_rate\n self.reg_param = reg_param\n self.discount_factor=discount_factor\n self.max_layers = max_layers\n self.global_step = global_step\n\n self.reward_buffer = []\n self.state_buffer = []\n\n self.create_variables()\n var_lists = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n self.sess.run(tf.variables_initializer(var_lists))\n\n def get_action(self, state):\n '''Given the state of the neural network (Rewards so far are stored\n interanally as member variables) get new state.\n '''\n return self.sess.run(self.predicted_action, {self.states: state})\n\n def create_variables(self):\n\n with tf.name_scope(\"model_inputs\"):\n # raw state representation\n self.states = tf.placeholder(tf.float32, [None, self.max_layers*4], name=\"states\")\n\n with tf.name_scope(\"predict_actions\"):\n \n # initialize policy network\n with tf.variable_scope(\"policy_network\"):\n\n # In this case this is just the final state of the RNN\n self.policy_outputs = self.policy_network(self.states,\n self.max_layers)\n\n # Identity is used to remember the last policy_output how\n # tf.identity works isn't completely clear to me but for\n # now I'll trust that this works: it's basically deep copy\n self.action_scores = tf.identity(self.policy_outputs,\n name=\"action_scores\")\n\n # Scale them and cast them into int:\n # Note this doesn't depend on the reward\n # All that matters is the hidden weights of my policy controller\n # The reward is used to update those weights\n self.predicted_action = tf.cast(tf.scalar_mul(self.division_rate, self.action_scores),\n tf.int32,\n name=\"predicted_action\")\n\n\n # regularization loss\n policy_network_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"policy_network\")\n\n # compute loss and gradients\n with tf.name_scope(\"compute_gradients\"):\n # gradients for selecting action from policy network\n self.discounted_rewards = tf.placeholder(tf.float32, (None,), name=\"discounted_rewards\")\n\n with tf.variable_scope(\"policy_network\", reuse=True):\n self.logprobs = self.policy_network(self.states,\n self.max_layers)\n \n print(\"self.logprobs\", self.logprobs)\n\n # compute policy loss and regularization loss\n self.cross_entropy_loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logprobs[:, -1, :],\n labels=self.states)\n \n self.pg_loss = tf.reduce_mean(self.cross_entropy_loss)\n self.reg_loss = tf.reduce_sum([tf.reduce_sum(tf.square(x)) for x in policy_network_variables]) # L2 by the look of itRegularization\n self.loss = self.pg_loss + self.reg_param * self.reg_loss\n\n #compute gradients\n self.gradients = self.optimizer.compute_gradients(self.loss)\n \n # compute policy gradients\n for i, (grad, var) in enumerate(self.gradients):\n if grad is not None:\n self.gradients[i] = (grad * self.discounted_rewards, var)\n\n # training update\n with tf.name_scope(\"train_policy_network\"):\n # apply gradients to update policy network\n self.train_op = self.optimizer.apply_gradients(self.gradients,\n global_step=self.global_step)\n\n def storeRollout(self, state, reward):\n '''Caching for the win: for long running programs this is a shite\n solution\n '''\n self.reward_buffer.append(reward)\n self.state_buffer.append(state[0])\n\n \n def train_step(self, steps_count):\n '''\n This is where policy gradientx happens \n but to understand this also understand create_variable function\n \n steps_count: how many previous states to consider\n '''\n\n # take the last steps_count number of states\n states = np.array(self.state_buffer[-steps_count:])/self.division_rate\n\n # rewards are never discounted\n rewars = self.reward_buffer[-steps_count:]\n \n _, ls = self.sess.run([self.train_op, self.loss],\n {self.states: states,\n self.discounted_rewards: rewars})\n \n return ls\n"
]
[
"import numpy as np\nfrom scipy.sparse import isspmatrix_coo, coo_matrix\n\n\ndef drop_data(mat, threshold):\n \"\"\"Removes common from the matrix that is smaller then threshold.\n\n Parameters\n ----------\n mat : coo_matrix\n matrix\n threshold : float\n value below which we want to drop common\n\n Returns\n -------\n mat : coo\n matrix in the same format\n\n \"\"\"\n if not isspmatrix_coo(mat):\n raise ValueError('Given matrix is not in COO format')\n\n mat.data[mat.data < threshold] = 0\n mat.eliminate_zeros()\n return mat\n\n\ndef drop_cols(mat, idx_to_drop):\n \"\"\"Removes columns from the matrix.\n\n Parameters\n ----------\n mat : coo_matrix\n matrix\n idx_to_drop : array-like\n indices of columns we want to drop\n\n Returns\n -------\n mat: coo_matrix\n matrix without dropped columns\n \"\"\"\n if not isspmatrix_coo(mat):\n raise ValueError('Given matrix is not in COO format')\n if np.max(idx_to_drop) >= mat.shape[1]:\n raise ValueError('Column indices are bigger then shape of the matrix.')\n\n idx_to_drop = np.unique(idx_to_drop)\n keep = ~np.in1d(mat.col, idx_to_drop)\n mat.data, mat.row, mat.col = mat.data[keep], mat.row[keep], mat.col[keep]\n mat.col -= idx_to_drop.searchsorted(mat.col) # decrement column indices\n mat._shape = (mat.shape[0], mat.shape[1] - len(idx_to_drop))\n return coo_matrix(mat)\n\n\ndef drop_rows(mat, idx_to_drop):\n \"\"\"Removes rows from the matrix.\n\n Parameters\n ----------\n mat : coo_matrix\n matrix\n idx_to_drop : array-like\n indices of rows we want to drop\n Returns\n -------\n mat: coo_matrix\n matrix without dropped rows\n \"\"\"\n if not isspmatrix_coo(mat):\n raise ValueError('Given matrix is not in COO format')\n if not np.max(idx_to_drop) < mat.shape[0]:\n raise ValueError('Row indices are bigger then shape of the matrix.')\n\n idx_to_drop = np.unique(idx_to_drop)\n keep = ~np.in1d(mat.row, idx_to_drop)\n mat.data, mat.row, mat.col = mat.data[keep], mat.row[keep], mat.col[keep]\n mat.row -= idx_to_drop.searchsorted(mat.row) # decrement row indices\n mat._shape = (mat.shape[0] - len(idx_to_drop), mat.shape[1])\n return coo_matrix(mat)\n\n\ndef make_zero_cols(mat, columns):\n \"\"\"Annihilate entries in the given columns\n\n Parameters\n ----------\n mat : coo_matrix\n matrix\n columns : array-like\n indices of columns to set to 0\n\n Returns\n -------\n mat: coo_matrix\n matrix with given columns set to 0\n \"\"\"\n if not isspmatrix_coo(mat):\n raise ValueError('Given matrix is not in COO format')\n if not np.max(columns) < mat.shape[1]:\n raise ValueError('Column indices are bigger then shape of the matrix.')\n\n columns = np.unique(columns)\n make_zero = np.in1d(mat.col, columns)\n mat.data[make_zero] = 0\n mat.eliminate_zeros()\n return mat.tocsr()\n"
]
[
"######################\n# Authors:\n# Xianghang Liu <[email protected]>\n# Andreas Mueller <[email protected]>\n#\n# License: BSD 3-clause\n#\n# Implements structured SVM as described in Joachims et. al.\n# Cutting-Plane Training of Structural SVMs\n\nimport warnings\nfrom time import time\nimport numpy as np\nfrom sklearn.utils import check_random_state\n\nfrom pystruct.learners.ssvm import BaseSSVM\nfrom pystruct.utils import find_constraint\n\n\nclass FrankWolfeSSVM(BaseSSVM):\n \"\"\"Structured SVM solver using Block-coordinate Frank-Wolfe.\n\n This implementation is somewhat experimental. Use with care.\n\n This implementation follows the paper:\n Lacoste-Julien, Jaggi, Schmidt, Pletscher JMLR 2013\n Block-Coordinage Frank-Wolfe Optimization for Structural SVMs\n\n With batch_mode=False, this implements the online (block-coordinate)\n version of the algorithm (BCFW)\n BCFW is an attractive alternative to subgradient methods, as no\n learning rate is needed and a duality gap guarantee is given.\n\n Parameters\n ----------\n model : StructuredModel\n Object containing the model structure. Has to implement\n `loss`, `inference` and `loss_augmented_inference`.\n\n max_iter : int, default=1000\n Maximum number of passes over dataset to find constraints.\n\n C : float, default=1\n Regularization parameter. Corresponds to 1 / (lambda * n_samples).\n\n verbose : int\n Verbosity.\n\n n_jobs : int, default=1\n Number of parallel processes. Currently only n_jobs=1 is supported.\n\n show_loss_every : int, default=0\n How often the training set loss should be computed.\n Zero corresponds to never.\n\n tol : float, default=1e-3\n Convergence tolerance on the duality gap.\n\n logger : logger object, default=None\n Pystruct logger for storing the model or extracting additional\n information.\n\n batch_mode : boolean, default=False\n Whether to use batch updates. Will slow down learning enormously.\n\n line_search : boolean, default=True\n Whether to compute the optimum step size in each step.\n The line-search is done in closed form and cheap.\n There is usually no reason to turn this off.\n\n check_dual_every : int, default=10\n How often the stopping criterion should be checked. Computing\n the stopping criterion is as costly as doing one pass over the dataset,\n so check_dual_every=1 will make learning twice as slow.\n\n do_averaging : bool, default=True\n Whether to use weight averaging as described in the reference paper.\n Currently this is only supported in the block-coordinate version.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n\n Attributes\n ----------\n w : nd-array, shape=(model.size_psi,)\n The learned weights of the SVM.\n\n ``loss_curve_`` : list of float\n List of loss values if show_loss_every > 0.\n\n ``objective_curve_`` : list of float\n Cutting plane objective after each pass through the dataset.\n\n ``primal_objective_curve_`` : list of float\n Primal objective after each pass through the dataset.\n\n ``timestamps_`` : list of int\n Total training time stored before each iteration.\n \"\"\"\n def __init__(self, model, max_iter=1000, C=1.0, verbose=0, n_jobs=1,\n show_loss_every=0, logger=None, batch_mode=False,\n line_search=True, check_dual_every=10, tol=.001,\n do_averaging=True, sample_method='perm', random_state=None):\n\n if n_jobs != 1:\n warnings.warn(\"FrankWolfeSSVM does not support multiprocessing\"\n \" yet. Ignoring n_jobs != 1.\")\n\n if sample_method not in ['perm', 'rnd', 'seq']:\n raise ValueError(\"sample_method can only be perm, rnd, or seq\")\n\n BaseSSVM.__init__(self, model, max_iter, C, verbose=verbose,\n n_jobs=n_jobs, show_loss_every=show_loss_every,\n logger=logger)\n self.tol = tol\n self.batch_mode = batch_mode\n self.line_search = line_search\n self.check_dual_every = check_dual_every\n self.do_averaging = do_averaging\n self.sample_method = sample_method\n self.random_state = random_state\n\n def _calc_dual_gap(self, X, Y, l):\n n_samples = len(X)\n psi_gt = self.model.batch_psi(X, Y, Y) # FIXME don't calculate this again\n Y_hat = self.model.batch_loss_augmented_inference(X, Y, self.w,\n relaxed=True)\n dpsi = psi_gt - self.model.batch_psi(X, Y_hat)\n ls = np.sum(self.model.batch_loss(Y, Y_hat))\n ws = dpsi * self.C\n l = l * n_samples * self.C\n\n dual_val = -0.5 * np.sum(self.w ** 2) + l\n w_diff = self.w - ws\n dual_gap = w_diff.T.dot(self.w) - l + ls * self.C\n primal_val = dual_val + dual_gap\n self.primal_objective_curve_.append(primal_val)\n self.objective_curve_.append(dual_val)\n self.timestamps_.append(time() - self.timestamps_[0])\n return dual_val, dual_gap, primal_val\n\n def _frank_wolfe_batch(self, X, Y):\n \"\"\"Batch Frank-Wolfe learning.\n\n This is basically included for reference / comparision only,\n as the block-coordinate version is much faster.\n\n Compare Algorithm 2 in the reference paper.\n \"\"\"\n l = 0.0\n n_samples = float(len(X))\n psi_gt = self.model.batch_psi(X, Y, Y)\n\n for k in xrange(self.max_iter):\n Y_hat = self.model.batch_loss_augmented_inference(X, Y, self.w,\n relaxed=True)\n dpsi = psi_gt - self.model.batch_psi(X, Y_hat)\n ls = np.mean(self.model.batch_loss(Y, Y_hat))\n ws = dpsi * self.C\n\n w_diff = self.w - ws\n dual_gap = 1.0 / (self.C * n_samples) * w_diff.T.dot(self.w) - l + ls\n\n # line search for gamma\n if self.line_search:\n eps = 1e-15\n gamma = dual_gap / (np.sum(w_diff ** 2) / (self.C * n_samples) + eps)\n gamma = max(0.0, min(1.0, gamma))\n else:\n gamma = 2.0 / (k + 2.0)\n\n dual_val = -0.5 * np.sum(self.w ** 2) + l * (n_samples * self.C)\n dual_gap_display = dual_gap * n_samples * self.C\n primal_val = dual_val + dual_gap_display\n\n self.primal_objective_curve_.append(primal_val)\n self.objective_curve_.append(dual_val)\n self.timestamps_.append(time() - self.timestamps_[0])\n if self.verbose > 0:\n print(\"k = %d, dual: %f, dual_gap: %f, primal: %f, gamma: %f\"\n % (k, dual_val, dual_gap_display, primal_val, gamma))\n\n # update w and l\n self.w = (1.0 - gamma) * self.w + gamma * ws\n l = (1.0 - gamma) * l + gamma * ls\n\n if self.logger is not None:\n self.logger(self, k)\n\n if dual_gap < self.tol:\n return\n\n def _frank_wolfe_bc(self, X, Y):\n \"\"\"Block-Coordinate Frank-Wolfe learning.\n\n Compare Algorithm 3 in the reference paper.\n \"\"\"\n n_samples = len(X)\n w = self.w.copy()\n w_mat = np.zeros((n_samples, self.model.size_psi))\n l_mat = np.zeros(n_samples)\n l_avg = 0.0\n l = 0.0\n k = 0\n\n rng = check_random_state(self.random_state)\n for p in xrange(self.max_iter):\n if self.verbose > 0:\n print(\"Iteration %d\" % p)\n\n perm = np.arange(n_samples)\n if self.sample_method == 'perm':\n rng.shuffle(perm)\n elif self.sample_method == 'rnd':\n perm = rng.randint(low=0, high=n_samples, size=n_samples)\n\n for j in range(n_samples):\n i = perm[j]\n x, y = X[i], Y[i]\n y_hat, delta_psi, slack, loss = find_constraint(self.model, x, y, w)\n # ws and ls\n ws = delta_psi * self.C\n ls = loss / n_samples\n\n # line search\n if self.line_search:\n eps = 1e-15\n w_diff = w_mat[i] - ws\n gamma = (w_diff.T.dot(w) - (self.C * n_samples)*(l_mat[i] - ls)) / (np.sum(w_diff ** 2) + eps)\n gamma = max(0.0, min(1.0, gamma))\n else:\n gamma = 2.0 * n_samples / (k + 2.0 * n_samples)\n\n w -= w_mat[i]\n w_mat[i] = (1.0 - gamma) * w_mat[i] + gamma * ws\n w += w_mat[i]\n\n l -= l_mat[i]\n l_mat[i] = (1.0 - gamma) * l_mat[i] + gamma * ls\n l += l_mat[i]\n\n if self.do_averaging:\n rho = 2.0 / (k + 2.0)\n self.w = (1.0 - rho) * self.w + rho * w\n l_avg = (1.0 - rho) * l_avg + rho * l\n else:\n self.w = w\n k += 1\n\n if self.logger is not None:\n self.logger(self, p)\n if (self.check_dual_every != 0) and (p % self.check_dual_every == 0):\n dual_val, dual_gap, primal_val = self._calc_dual_gap(X, Y, l)\n self.primal_objective_curve_.append(primal_val)\n self.objective_curve_.append(dual_val)\n self.timestamps_.append(time() - self.timestamps_[0])\n if self.verbose > 0:\n print(\"dual: %f, dual_gap: %f, primal: %f\"\n % (dual_val, dual_gap, primal_val))\n if dual_gap < self.tol:\n return\n\n def fit(self, X, Y, constraints=None, initialize=True):\n \"\"\"Learn parameters using (block-coordinate) Frank-Wolfe learning.\n\n Parameters\n ----------\n X : iterable\n Traing instances. Contains the structured input objects.\n No requirement on the particular form of entries of X is made.\n\n Y : iterable\n Training labels. Contains the strctured labels for inputs in X.\n Needs to have the same length as X.\n\n contraints : ignored\n\n initialize : boolean, default=True\n Whether to initialize the model for the data.\n Leave this true except if you really know what you are doing.\n \"\"\"\n if initialize:\n self.model.initialize(X, Y)\n self.objective_curve_, self.primal_objective_curve_ = [], []\n self.timestamps_ = [time()]\n self.w = getattr(self, \"w\", np.zeros(self.model.size_psi))\n try:\n if self.batch_mode:\n self._frank_wolfe_batch(X, Y)\n else:\n self._frank_wolfe_bc(X, Y)\n except KeyboardInterrupt:\n pass\n if self.verbose:\n print(\"Calculating final objective.\")\n self.timestamps_.append(time() - self.timestamps_[0])\n self.primal_objective_curve_.append(self._objective(X, Y))\n self.objective_curve_.append(self.objective_curve_[-1])\n if self.logger is not None:\n self.logger(self, 'final')\n\n return self\n"
]
[
"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"Contains the definition for inception v3 classification network.\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport tensorflow as tf\r\n\r\nfrom nets import inception_utils\r\n\r\nslim = tf.contrib.slim\r\ntrunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)\r\n\r\n\r\ndef inception_v3_base(inputs,\r\n final_endpoint='Mixed_7c',\r\n min_depth=16,\r\n depth_multiplier=1.0,\r\n scope=None):\r\n \"\"\"Inception model from http://arxiv.org/abs/1512.00567.\r\n\r\n Constructs an Inception v3 network from inputs to the given final endpoint.\r\n This method can construct the network up to the final inception block\r\n Mixed_7c.\r\n\r\n Note that the names of the layers in the paper do not correspond to the names\r\n of the endpoints registered by this function although they build the same\r\n network.\r\n\r\n Here is a mapping from the old_names to the new names:\r\n Old name | New name\r\n =======================================\r\n conv0 | Conv2d_1a_3x3\r\n conv1 | Conv2d_2a_3x3\r\n conv2 | Conv2d_2b_3x3\r\n pool1 | MaxPool_3a_3x3\r\n conv3 | Conv2d_3b_1x1\r\n conv4 | Conv2d_4a_3x3\r\n pool2 | MaxPool_5a_3x3\r\n mixed_35x35x256a | Mixed_5b\r\n mixed_35x35x288a | Mixed_5c\r\n mixed_35x35x288b | Mixed_5d\r\n mixed_17x17x768a | Mixed_6a\r\n mixed_17x17x768b | Mixed_6b\r\n mixed_17x17x768c | Mixed_6c\r\n mixed_17x17x768d | Mixed_6d\r\n mixed_17x17x768e | Mixed_6e\r\n mixed_8x8x1280a | Mixed_7a\r\n mixed_8x8x2048a | Mixed_7b\r\n mixed_8x8x2048b | Mixed_7c\r\n\r\n Args:\r\n inputs: a tensor of size [batch_size, height, width, channels].\r\n final_endpoint: specifies the endpoint to construct the network up to. It\r\n can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3',\r\n 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3',\r\n 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c',\r\n 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c'].\r\n min_depth: Minimum depth value (number of channels) for all convolution ops.\r\n Enforced when depth_multiplier < 1, and not an active constraint when\r\n depth_multiplier >= 1.\r\n depth_multiplier: Float multiplier for the depth (number of channels)\r\n for all convolution ops. The value must be greater than zero. Typical\r\n usage will be to set this value in (0, 1) to reduce the number of\r\n parameters or computation cost of the model.\r\n scope: Optional variable_scope.\r\n\r\n Returns:\r\n tensor_out: output tensor corresponding to the final_endpoint.\r\n end_points: a set of activations for external use, for example summaries or\r\n losses.\r\n\r\n Raises:\r\n ValueError: if final_endpoint is not set to one of the predefined values,\r\n or depth_multiplier <= 0\r\n \"\"\"\r\n # end_points will collect relevant activations for external use, for example\r\n # summaries or losses.\r\n end_points = {}\r\n\r\n if depth_multiplier <= 0:\r\n raise ValueError('depth_multiplier is not greater than zero.')\r\n depth = lambda d: max(int(d * depth_multiplier), min_depth)\r\n\r\n with tf.variable_scope(scope, 'InceptionV3', [inputs]):\r\n with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],\r\n stride=1, padding='VALID'):\r\n # 299 x 299 x 3\r\n end_point = 'Conv2d_1a_3x3'\r\n net = slim.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 149 x 149 x 32\r\n end_point = 'Conv2d_2a_3x3'\r\n net = slim.conv2d(net, depth(32), [3, 3], scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 147 x 147 x 32\r\n end_point = 'Conv2d_2b_3x3'\r\n net = slim.conv2d(net, depth(64), [3, 3], padding='SAME', scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 147 x 147 x 64\r\n end_point = 'MaxPool_3a_3x3'\r\n net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 73 x 73 x 64\r\n end_point = 'Conv2d_3b_1x1'\r\n net = slim.conv2d(net, depth(80), [1, 1], scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 73 x 73 x 80.\r\n end_point = 'Conv2d_4a_3x3'\r\n net = slim.conv2d(net, depth(192), [3, 3], scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 71 x 71 x 192.\r\n end_point = 'MaxPool_5a_3x3'\r\n net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point)\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # 35 x 35 x 192.\r\n\r\n # Inception blocks\r\n with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],\r\n stride=1, padding='SAME'):\r\n # mixed: 35 x 35 x 256.\r\n end_point = 'Mixed_5b'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(64), [5, 5],\r\n scope='Conv2d_0b_5x5')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(96), [3, 3],\r\n scope='Conv2d_0b_3x3')\r\n branch_2 = slim.conv2d(branch_2, depth(96), [3, 3],\r\n scope='Conv2d_0c_3x3')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(32), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_1: 35 x 35 x 288.\r\n end_point = 'Mixed_5c'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0b_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(64), [5, 5],\r\n scope='Conv_1_0c_5x5')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(64), [1, 1],\r\n scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(96), [3, 3],\r\n scope='Conv2d_0b_3x3')\r\n branch_2 = slim.conv2d(branch_2, depth(96), [3, 3],\r\n scope='Conv2d_0c_3x3')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(64), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_2: 35 x 35 x 288.\r\n end_point = 'Mixed_5d'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(64), [5, 5],\r\n scope='Conv2d_0b_5x5')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(96), [3, 3],\r\n scope='Conv2d_0b_3x3')\r\n branch_2 = slim.conv2d(branch_2, depth(96), [3, 3],\r\n scope='Conv2d_0c_3x3')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(64), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_3: 17 x 17 x 768.\r\n end_point = 'Mixed_6a'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(384), [3, 3], stride=2,\r\n padding='VALID', scope='Conv2d_1a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(96), [3, 3],\r\n scope='Conv2d_0b_3x3')\r\n branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], stride=2,\r\n padding='VALID', scope='Conv2d_1a_1x1')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID',\r\n scope='MaxPool_1a_3x3')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed4: 17 x 17 x 768.\r\n end_point = 'Mixed_6b'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(128), [1, 7],\r\n scope='Conv2d_0b_1x7')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [7, 1],\r\n scope='Conv2d_0c_7x1')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(128), [7, 1],\r\n scope='Conv2d_0b_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(128), [1, 7],\r\n scope='Conv2d_0c_1x7')\r\n branch_2 = slim.conv2d(branch_2, depth(128), [7, 1],\r\n scope='Conv2d_0d_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [1, 7],\r\n scope='Conv2d_0e_1x7')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(192), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_5: 17 x 17 x 768.\r\n end_point = 'Mixed_6c'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(160), [1, 7],\r\n scope='Conv2d_0b_1x7')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [7, 1],\r\n scope='Conv2d_0c_7x1')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(160), [7, 1],\r\n scope='Conv2d_0b_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(160), [1, 7],\r\n scope='Conv2d_0c_1x7')\r\n branch_2 = slim.conv2d(branch_2, depth(160), [7, 1],\r\n scope='Conv2d_0d_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [1, 7],\r\n scope='Conv2d_0e_1x7')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(192), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # mixed_6: 17 x 17 x 768.\r\n end_point = 'Mixed_6d'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(160), [1, 7],\r\n scope='Conv2d_0b_1x7')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [7, 1],\r\n scope='Conv2d_0c_7x1')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(160), [7, 1],\r\n scope='Conv2d_0b_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(160), [1, 7],\r\n scope='Conv2d_0c_1x7')\r\n branch_2 = slim.conv2d(branch_2, depth(160), [7, 1],\r\n scope='Conv2d_0d_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [1, 7],\r\n scope='Conv2d_0e_1x7')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(192), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_7: 17 x 17 x 768.\r\n end_point = 'Mixed_6e'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [1, 7],\r\n scope='Conv2d_0b_1x7')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [7, 1],\r\n scope='Conv2d_0c_7x1')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [7, 1],\r\n scope='Conv2d_0b_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [1, 7],\r\n scope='Conv2d_0c_1x7')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [7, 1],\r\n scope='Conv2d_0d_7x1')\r\n branch_2 = slim.conv2d(branch_2, depth(192), [1, 7],\r\n scope='Conv2d_0e_1x7')\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(branch_3, depth(192), [1, 1],\r\n scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_8: 8 x 8 x 1280.\r\n end_point = 'Mixed_7a'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_0 = slim.conv2d(branch_0, depth(320), [3, 3], stride=2,\r\n padding='VALID', scope='Conv2d_1a_3x3')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [1, 7],\r\n scope='Conv2d_0b_1x7')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [7, 1],\r\n scope='Conv2d_0c_7x1')\r\n branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], stride=2,\r\n padding='VALID', scope='Conv2d_1a_3x3')\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID',\r\n scope='MaxPool_1a_3x3')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n # mixed_9: 8 x 8 x 2048.\r\n end_point = 'Mixed_7b'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = tf.concat(axis=3, values=[\r\n slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'),\r\n slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1')])\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(\r\n branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3')\r\n branch_2 = tf.concat(axis=3, values=[\r\n slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'),\r\n slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')])\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(\r\n branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n\r\n # mixed_10: 8 x 8 x 2048.\r\n end_point = 'Mixed_7c'\r\n with tf.variable_scope(end_point):\r\n with tf.variable_scope('Branch_0'):\r\n branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1')\r\n with tf.variable_scope('Branch_1'):\r\n branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_1 = tf.concat(axis=3, values=[\r\n slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'),\r\n slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1')])\r\n with tf.variable_scope('Branch_2'):\r\n branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1')\r\n branch_2 = slim.conv2d(\r\n branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3')\r\n branch_2 = tf.concat(axis=3, values=[\r\n slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'),\r\n slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')])\r\n with tf.variable_scope('Branch_3'):\r\n branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')\r\n branch_3 = slim.conv2d(\r\n branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1')\r\n net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])\r\n end_points[end_point] = net\r\n if end_point == final_endpoint: return net, end_points\r\n raise ValueError('Unknown final endpoint %s' % final_endpoint)\r\n\r\n\r\ndef inception_v3(inputs,\r\n num_classes=1000,\r\n is_training=True,\r\n dropout_keep_prob=0.8,\r\n min_depth=16,\r\n depth_multiplier=1.0,\r\n prediction_fn=slim.softmax,\r\n spatial_squeeze=True,\r\n reuse=None,\r\n create_aux_logits=True,\r\n scope='InceptionV3',\r\n global_pool=False):\r\n \"\"\"Inception model from http://arxiv.org/abs/1512.00567.\r\n\r\n \"Rethinking the Inception Architecture for Computer Vision\"\r\n\r\n Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens,\r\n Zbigniew Wojna.\r\n\r\n With the default arguments this method constructs the exact model defined in\r\n the paper. However, one can experiment with variations of the inception_v3\r\n network by changing arguments dropout_keep_prob, min_depth and\r\n depth_multiplier.\r\n\r\n The default image size used to train this network is 299x299.\r\n\r\n Args:\r\n inputs: a tensor of size [batch_size, height, width, channels].\r\n num_classes: number of predicted classes. If 0 or None, the logits layer\r\n is omitted and the input features to the logits layer (before dropout)\r\n are returned instead.\r\n is_training: whether is training or not.\r\n dropout_keep_prob: the percentage of activation values that are retained.\r\n min_depth: Minimum depth value (number of channels) for all convolution ops.\r\n Enforced when depth_multiplier < 1, and not an active constraint when\r\n depth_multiplier >= 1.\r\n depth_multiplier: Float multiplier for the depth (number of channels)\r\n for all convolution ops. The value must be greater than zero. Typical\r\n usage will be to set this value in (0, 1) to reduce the number of\r\n parameters or computation cost of the model.\r\n prediction_fn: a function to get predictions out of logits.\r\n spatial_squeeze: if True, logits is of shape [B, C], if false logits is of\r\n shape [B, 1, 1, C], where B is batch_size and C is number of classes.\r\n reuse: whether or not the network and its variables should be reused. To be\r\n able to reuse 'scope' must be given.\r\n create_aux_logits: Whether to create the auxiliary logits.\r\n scope: Optional variable_scope.\r\n global_pool: Optional boolean flag to control the avgpooling before the\r\n logits layer. If false or unset, pooling is done with a fixed window\r\n that reduces default-sized inputs to 1x1, while larger inputs lead to\r\n larger outputs. If true, any input size is pooled down to 1x1.\r\n\r\n Returns:\r\n net: a Tensor with the logits (pre-softmax activations) if num_classes\r\n is a non-zero integer, or the non-dropped-out input to the logits layer\r\n if num_classes is 0 or None.\r\n end_points: a dictionary from components of the network to the corresponding\r\n activation.\r\n\r\n Raises:\r\n ValueError: if 'depth_multiplier' is less than or equal to zero.\r\n \"\"\"\r\n if depth_multiplier <= 0:\r\n raise ValueError('depth_multiplier is not greater than zero.')\r\n depth = lambda d: max(int(d * depth_multiplier), min_depth)\r\n\r\n with tf.variable_scope(scope, 'InceptionV3', [inputs], reuse=reuse) as scope:\r\n with slim.arg_scope([slim.batch_norm, slim.dropout],\r\n is_training=is_training):\r\n net, end_points = inception_v3_base(\r\n inputs, scope=scope, min_depth=min_depth,\r\n depth_multiplier=depth_multiplier)\r\n\r\n # Auxiliary Head logits\r\n if create_aux_logits and num_classes:\r\n with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],\r\n stride=1, padding='SAME'):\r\n aux_logits = end_points['Mixed_6e']\r\n with tf.variable_scope('AuxLogits'):\r\n aux_logits = slim.avg_pool2d(\r\n aux_logits, [5, 5], stride=3, padding='VALID',\r\n scope='AvgPool_1a_5x5')\r\n aux_logits = slim.conv2d(aux_logits, depth(128), [1, 1],\r\n scope='Conv2d_1b_1x1')\r\n\r\n # Shape of feature map before the final layer.\r\n kernel_size = _reduced_kernel_size_for_small_input(\r\n aux_logits, [5, 5])\r\n aux_logits = slim.conv2d(\r\n aux_logits, depth(768), kernel_size,\r\n weights_initializer=trunc_normal(0.01),\r\n padding='VALID', scope='Conv2d_2a_{}x{}'.format(*kernel_size))\r\n aux_logits = slim.conv2d(\r\n aux_logits, num_classes, [1, 1], activation_fn=None,\r\n normalizer_fn=None, weights_initializer=trunc_normal(0.001),\r\n scope='Conv2d_2b_1x1')\r\n if spatial_squeeze:\r\n aux_logits = tf.squeeze(aux_logits, [1, 2], name='SpatialSqueeze')\r\n end_points['AuxLogits'] = aux_logits\r\n\r\n # Final pooling and prediction\r\n with tf.variable_scope('Logits'):\r\n if global_pool:\r\n # Global average pooling.\r\n net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='GlobalPool')\r\n end_points['global_pool'] = net\r\n else:\r\n # Pooling with a fixed kernel size.\r\n kernel_size = _reduced_kernel_size_for_small_input(net, [8, 8])\r\n net = slim.avg_pool2d(net, kernel_size, padding='VALID',\r\n scope='AvgPool_1a_{}x{}'.format(*kernel_size))\r\n end_points['AvgPool_1a'] = net\r\n if not num_classes:\r\n return net, end_points\r\n # 1 x 1 x 2048\r\n net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b')\r\n end_points['PreLogits'] = net\r\n # 2048\r\n logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None,\r\n normalizer_fn=None, scope='Conv2d_1c_1x1')\r\n if spatial_squeeze:\r\n logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze')\r\n # 1000\r\n end_points['Logits'] = logits\r\n end_points['Predictions'] = prediction_fn(logits, scope='Predictions')\r\n return logits, end_points\r\ninception_v3.default_image_size = 299\r\n\r\n\r\ndef _reduced_kernel_size_for_small_input(input_tensor, kernel_size):\r\n \"\"\"Define kernel size which is automatically reduced for small input.\r\n\r\n If the shape of the input images is unknown at graph construction time this\r\n function assumes that the input images are is large enough.\r\n\r\n Args:\r\n input_tensor: input tensor of size [batch_size, height, width, channels].\r\n kernel_size: desired kernel size of length 2: [kernel_height, kernel_width]\r\n\r\n Returns:\r\n a tensor with the kernel size.\r\n\r\n TODO(jrru): Make this function work with unknown shapes. Theoretically, this\r\n can be done with the code below. Problems are two-fold: (1) If the shape was\r\n known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot\r\n handle tensors that define the kernel size.\r\n shape = tf.shape(input_tensor)\r\n return = tf.stack([tf.minimum(shape[1], kernel_size[0]),\r\n tf.minimum(shape[2], kernel_size[1])])\r\n\r\n \"\"\"\r\n shape = input_tensor.get_shape().as_list()\r\n if shape[1] is None or shape[2] is None:\r\n kernel_size_out = kernel_size\r\n else:\r\n kernel_size_out = [min(shape[1], kernel_size[0]),\r\n min(shape[2], kernel_size[1])]\r\n return kernel_size_out\r\n\r\n\r\ninception_v3_arg_scope = inception_utils.inception_arg_scope\r\n"
]
[
"import numpy as np\nimport scipy.fft as sp_fft\n\n\ndef fftconvolve3(rho, *greens):\n \"\"\"\n Efficiently perform a 3D convolution of a charge density rho and multiple Green functions. \n \n Parameters\n ----------\n \n rho : np.array (3D)\n Charge mesh\n \n *greens : np.arrays (3D)\n Charge meshes for the Green functions, which should be twice the size of rho \n \n \n Returns\n -------\n \n fields : tuple of np.arrays with the same shape as rho. \n \n \"\"\"\n\n # FFT Configuration\n fft = lambda x: sp_fft.fftn(x, overwrite_x=True)\n ifft = lambda x: sp_fft.ifftn(x, overwrite_x=True) \n \n # Place rho in double-sized array. Should match the shape of green\n nx, ny, nz = rho.shape\n crho = np.zeros( (2*nx, 2*ny, 2*nz))\n crho[0:nx,0:ny,0:nz] = rho[0:nx,0:ny,0:nz]\n \n # FFT\n crho = fft(crho) \n \n results = []\n for green in greens:\n assert crho.shape == green.shape, f'Green array shape {green.shape} should be twice rho shape {rho.shape}'\n result = ifft(crho*fft(green))\n # Extract the result\n result = np.real(result[nx-1:2*nx-1,ny-1:2*ny-1,nz-1:2*nz-1])\n results.append(result)\n \n return tuple(results)"
]
[
"from typing import List, Tuple\n\nimport nltk\nimport numpy as np\n\n# Spacy needs this module, but it's used only implicitly\nimport pyinflect # noqa: F401\nimport spacy\nfrom gender_extractor import GenderExtractor\n\nfrom initialize import spacy_nlp\nfrom interfaces.QuestionAnswerOperation import QuestionAnswerOperation\nfrom tasks.TaskTypes import TaskType\n\n\"\"\"\nBase Class for implementing the different input transformations a generation should be robust against.\n\"\"\"\n\n\nclass SuspectingParaphraser(QuestionAnswerOperation):\n \"\"\"This paraphraser transforms a yes/no question into a tag one.\n\n Example: \"Did the American National Shipment company really break its own fleet?\"\n -> \"The American National Shipment company really broke its own fleet, didn't it?\"\n \"\"\"\n\n tasks = [TaskType.QUESTION_ANSWERING, TaskType.QUESTION_GENERATION]\n\n languages = [\"en\"]\n\n def __init__(self, seed=0, max_outputs=1, pronoun_mod=0.9):\n super().__init__(seed, max_outputs=max_outputs)\n np.random.seed(seed)\n nltk.download(\"punkt\")\n\n self.nlp = spacy_nlp if spacy_nlp else spacy.load(\"en_core_web_sm\")\n\n self.gender_detector = GenderExtractor()\n self.pronouns = [\"he\", \"she\", \"it\", \"they\"]\n self.static_pronouns = [\"i\", \"we\", \"you\", *self.pronouns]\n\n self._special_endings = {\n \"may\": \"may {} not\",\n \"might\": \"might {} not\",\n \"shall\": \"shan't {}\",\n \"will\": \"won't {}\",\n }\n\n self.pronoun_mod = pronoun_mod\n self._pronoun_alt = (1 - pronoun_mod) / (len(self.pronouns) - 1)\n\n def _transform(self, question):\n text = nltk.word_tokenize(question)\n doc = self.nlp(question)\n modal = str(doc[0]).lower()\n token = doc[0]\n\n verb_position = [\n i for i in range(len(doc)) if str(doc[i]) == token.head.text\n ][0]\n\n rest_of_sentence = [i for i in text[verb_position:]]\n\n if text[1].lower() == \"n't\":\n text = text[1:]\n doc = doc[1:]\n verb_position = verb_position - 1\n\n beginning = [text[1].capitalize()]\n beginning.extend(text[2:verb_position])\n sentence = nltk.tokenize.treebank.TreebankWordDetokenizer().detokenize(\n beginning + rest_of_sentence\n )\n\n first_verb = doc[verb_position]\n\n # If 'did' is our modal, the verb will be in a present tense\n # It means that we need to inflect it to the past one (VBD)\n # (Did John _drink_ my tea? -> John _drank_ my tea, didn't he?)\n # Otherwise, the verb is already in a good form and we can use\n # it directly\n if modal == \"did\":\n demodded = first_verb._.inflect(\"VBD\")\n else:\n demodded = modal + \" \" + str(first_verb)\n sentence = sentence.replace(str(first_verb), str(demodded)).replace(\n \"?\", \"\"\n )\n\n ending = self._resolve_ending(doc, modal)\n result = sentence + ending\n return result\n\n def _resolve_ending(self, doc, modal):\n try:\n subject = str([tok for tok in doc if (tok.dep_ == \"nsubj\")][0])\n except IndexError:\n return \", right?\"\n\n prob = {i: 1 / len(self.pronouns) for i in self.pronouns}\n\n tagged = [(X.text, X.label_) for X in doc.ents]\n if subject.lower() in self.static_pronouns:\n pronoun = subject.lower()\n if pronoun == \"i\":\n pronoun = \"I\"\n else:\n if len(tagged) > 0 and tagged[0][1] != \"PERSON\":\n prob = {i: 0 for i in self.pronouns}\n prob[\"it\"] = 1\n else:\n noun_gender = self.gender_detector.extract_gender(subject)\n\n if noun_gender in [\"male\", \"mostly_male\"]:\n prob = {i: self._pronoun_alt for i in self.pronouns}\n\n prob[\"he\"] = self.pronoun_mod\n\n elif noun_gender in [\"female\", \"mostly_female\"]:\n prob = {i: self._pronoun_alt for i in self.pronouns}\n\n prob[\"she\"] = self.pronoun_mod\n\n pronoun = np.random.choice(self.pronouns, p=list(prob.values()))\n\n ending = \", \"\n if modal in self._special_endings.keys():\n ending += self._special_endings[modal].format(pronoun)\n else:\n ending += f\"{modal}n't {pronoun}\"\n ending += \"?\"\n return ending\n\n def _filter_phrase(self, question):\n try:\n if question.strip()[-1] != \"?\":\n return False\n except IndexError:\n return False\n\n if \" or \" in question:\n return False\n\n doc = self.nlp(question)\n token = doc[0]\n if token.pos_ != \"AUX\":\n return False\n\n return True\n\n def generate(\n self, context: str, question: str, answers: [str]\n ) -> List[Tuple[str, str, List[str]]]:\n if not self._filter_phrase(question):\n return [(context, question, answers)]\n\n paraphrased = self._transform(question)\n return [(context, paraphrased, answers)]\n\n\nif __name__ == \"__main__\":\n import json\n\n from TestRunner import convert_to_snake_case\n\n tf = SuspectingParaphraser()\n\n test_cases = []\n for i, sentence in enumerate(\n [\n \"Did Sally finally return the french book to Chris?\",\n \"Did the American National Shipment company really break its own fleet?\",\n \"Couldn't she just leave?\",\n \"Shall you begone, lad?\",\n \"Has Buzz Aldrin, the first person who walked on the moon, brought back some aliens?\",\n ]\n ):\n res = tf.generate(\"\", sentence, [])\n test_cases.append(\n {\n \"class\": tf.name(),\n \"inputs\": {\"context\": \"\", \"question\": sentence, \"answers\": []},\n \"outputs\": [],\n }\n )\n\n for p_context, p_question, p_answers in res:\n print(sentence)\n print(p_question)\n print()\n test_cases[i][\"outputs\"].append(\n {\n \"context\": p_context,\n \"question\": p_question,\n \"answers\": p_answers,\n }\n )\n\n json_file = {\n \"type\": convert_to_snake_case(tf.name()),\n \"test_cases\": test_cases,\n }\n\n with open(\"test.json\", \"w\") as f:\n json.dump(json_file, f, indent=2)\n"
]
[
"import cv2\nimport os\nimport numpy as np\nimport io\nimport time\nfrom google.cloud import vision\n\n# MySql / PhpMyAdmin Connection Variable\nhost = u'sql132.main-hosting.eu'\nuser = u'u824500046_fyp'\npw = u'7pmfyvTNvyeU'\ndb = u'u824500046_fyp'\n\n# Initialize Cloud Vision API and Firebase Admin SDK\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'google_vision.json'\n\n\n# [START vision_text_detection]\ndef detect_text(frame):\n \"\"\"Detects text in the file.\"\"\"\n client = vision.ImageAnnotatorClient()\n\n # [START vision_python_migration_text_detection]\n with io.open(frame, 'rb') as image_file:\n content = image_file.read()\n\n image = vision.types.Image(content=content)\n response = client.text_detection(image=image)\n texts = response.text_annotations\n print('Texts:')\n for text in texts:\n if len(text.description) == 4:\n # print(text.description)\n return text.description\n\n\n# Function that return canny detection\ndef auto_canny(image, sigma=0.33):\n # compute the median of the single channel pixel intensities\n v = np.median(image)\n\n # apply automatic Canny edge detection using the computed median\n # In practice, sigma=0.33 tends to give good results on most of the dataset\n lower = int(max(0, (1.0 - sigma) * v))\n upper = int(min(255, (1.0 + sigma) * v))\n edged = cv2.Canny(image, lower, upper)\n\n # return the edged image\n return edged\n # [END vision_python_migration_text_detection]\n# [END vision_text_detection]\n"
]
[
"import math\nimport matplotlib.pyplot as plt\n\nclass Gaussian():\n \"\"\" Gaussian distribution class for calculating and \n visualizing a Gaussian distribution.\n \n Attributes:\n mean (float) representing the mean value of the distribution\n stdev (float) representing the standard deviation of the distribution\n data_list (list of floats) a list of floats extracted from the data file\n \n \"\"\"\n def __init__(self, mu = 0, sigma = 1):\n \n self.mean = mu\n self.stdev = sigma\n self.data = []\n\n\n \n def calculate_mean(self):\n \n \"\"\"Method to calculate the mean of the data set.\n \n Args: \n None\n \n Returns: \n float: mean of the data set\n \n \"\"\"\n \n #TODO: Calculate the mean of the data set. Remember that the data set is stored in self.data\n # Change the value of the mean attribute to be the mean of the data set\n # Return the mean of the data set\n # \n # Mean (average) is the sum of all values in the list divided by the number of values \n average = 1.0 * sum(self.data) / len(self.data)\n self.mean = average\n return self.mean\n\n\n def calculate_stdev(self, sample=True):\n\n \"\"\"Method to calculate the standard deviation of the data set.\n \n Args: \n sample (bool): whether the data represents a sample or population\n \n Returns: \n float: standard deviation of the data set\n \n \"\"\"\n\n # TODO:\n # Calculate the standard deviation of the data set\n # \n # The sample variable determines if the data set contains a sample or a population\n # If sample = True, this means the data is a sample. \n # Keep the value of sample in mind for calculating the standard deviation\n #\n # Make sure to update self.stdev and return the standard deviation as well \n \n # Dividing by n − 1 rather than by n gives an unbiased estimate of the variance of the larger parent population.\n # if sample:\n # n = len(self.data) - 1\n # else:\n # n = len(self.data)\n\n # # We need ot find the average of all the data points\n # average = self.mean\n # # sigma represents deviation\n # sigma = 0\n # # We take deviations of each data point fron the\n # # average, and then square the result.\n # # (data_point - mean)^2\n # for deviation in self.data:\n # sigma += (deviation - average) ** 2\n # # We get the variance calculating the mean of those values\n # sigma = math.sqrt(sigma / n)\n # # We square root the variance to get our standard deviation\n # self.stdev = sigma\n # return self.stdev\n\n if sample:\n n = len(self.data) - 1\n else:\n n = len(self.data)\n \n mean = self.mean\n \n sigma = 0\n \n for d in self.data:\n sigma += (d - mean) ** 2\n \n sigma = math.sqrt(sigma / n)\n \n self.stdev = sigma\n \n return self.stdev\n\n def read_data_file(self, file_name, sample=True):\n \n \"\"\"Method to read in data from a txt file. The txt file should have\n one number (float) per line. The numbers are stored in the data attribute. \n After reading in the file, the mean and standard deviation are calculated\n \n Args:\n file_name (string): name of a file to read from\n \n Returns:\n None\n \n \"\"\"\n \n # This code opens a data file and appends the data to a list called data_list\n with open(file_name) as file:\n data_list = []\n line = file.readline()\n while line:\n data_list.append(int(line))\n line = file.readline()\n file.close()\n \n # TODO: \n # Update the self.data attribute with the data_list\n self.data = data_list\n # Update self.mean with the mean of the data_list.\n self.mean = self.calculate_mean() \n # You can use the calculate_mean() method with self.calculate_mean()\n # Update self.stdev with the standard deviation of the data_list. Use the \n # calculate_stdev() method.\n self.stdev = self.calculate_stdev(sample) \n \n def plot_histogram(self):\n \"\"\"Method to output a histogram of the instance variable data using \n matplotlib pyplot library.\n \n Args:\n None\n \n Returns:\n None\n \"\"\"\n \n # TODO: Plot a histogram of the data_list using the matplotlib package.\n # Be sure to label the x and y axes and also give the chart a title\n plt.hist(self.data)\n plt.title(\"Histogram of Data Points\")\n plt.xlabel(\"Data\")\n plt.set_ylabel(\"Counts\")\n \n \n def pdf(self, x):\n \"\"\"Probability density function calculator for the gaussian distribution.\n \n Args:\n x (float): point for calculating the probability density function\n \n \n Returns:\n float: probability density function output\n \"\"\"\n \n # TODO: Calculate the probability density function of the Gaussian distribution\n # at the value x. You'll need to use self.stdev and self.mean to do the calculation\n return (1.0 / (self.stdev * math.sqrt(2 * math.pi))) * math.exp(-0.5 * ((x - self.mean) / self.stdev) ** 2)\n\n def plot_histogram_pdf(self, n_spaces = 50):\n\n \"\"\"Method to plot the normalized histogram of the data and a plot of the \n probability density function along the same range\n \n Args:\n n_spaces (int): number of data points \n \n Returns:\n list: x values for the pdf plot\n list: y values for the pdf plot\n \n \"\"\"\n \n #TODO: Nothing to do for this method. Try it out and see how it works.\n \n mu = self.mean\n sigma = self.stdev\n\n min_range = min(self.data)\n max_range = max(self.data)\n \n # calculates the interval between x values\n interval = 1.0 * (max_range - min_range) / n_spaces\n\n x = []\n y = []\n \n # calculate the x values to visualize\n for i in range(n_spaces):\n tmp = min_range + interval*i\n x.append(tmp)\n y.append(self.pdf(tmp))\n\n # make the plots\n fig, axes = plt.subplots(2,sharex=True)\n fig.subplots_adjust(hspace=.5)\n axes[0].hist(self.data, density=True)\n axes[0].set_title('Normed Histogram of Data')\n axes[0].set_ylabel('Density')\n\n axes[1].plot(x, y)\n axes[1].set_title('Normal Distribution for \\n Sample Mean and Sample Standard Deviation')\n axes[0].set_ylabel('Density')\n plt.show()\n\n return x, y"
]
[
"import datetime as dt\nfrom os.path import dirname, join\n\nimport numpy as np\n\nimport pandas as pd\n\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import column, gridplot, row\nfrom bokeh.models import ColumnDataSource, DataRange1d, Select, HoverTool, Panel, Tabs, LinearColorMapper, Range1d\nfrom bokeh.models import NumeralTickFormatter, Title, Label, Paragraph, Div, CustomJSHover, BoxAnnotation\nfrom bokeh.models import ColorBar\nfrom bokeh.palettes import brewer, Spectral6\nfrom bokeh.plotting import figure\nfrom bokeh.embed import server_document\nfrom bokeh.transform import factor_cmap\n\n#################################################################################\n# This just loads in the data...\n# Alot of this was built of this \"cross-fire demo\"\n# https://github.com/bokeh/bokeh/blob/branch-2.3/examples/app/crossfilter/main.py\n\nstart_date = dt.datetime(2017,7,1)\nend_date = dt.datetime(2022,1,1)\n\nbackground = \"#ffffff\"\n\nfile = \"./data\"+ \"/data.parquet\"\n\ndf = pq.read_table(file).to_pandas()\n\ndf.sort_index(inplace=True)\n\noptions = df.index.unique(0).to_list()\n\n#print(options)\n\nproduct = \"HS CODE 72, IRON AND STEEL\"\n\nlevel = \"US Dollars\"\n\n#################################################################################\n#These are functions used in the plot...\n\ndef growth_trade(foo):\n # what this function does is take a dataframe and create a relative \n \n return 100*((foo[\"china_exports\"]/foo[\"china_exports\"].shift(12)) - 1)\n\ndef cum_trade(foo):\n \n outdf = pd.DataFrame([])\n \n outdf[\"cuml_trade_2017\"] = foo[\"china_exports\"].loc[\"2017\"].cumsum()\n \n outdf.index = pd.date_range(start=\"2020-01-01\", end=\"2020-12-01\", freq = \"MS\")\n \n outdf[\"cuml_trade_2020\"] = foo[\"china_exports\"].loc[\"2020\"].cumsum()\n \n return outdf\n\n#################################################################################\n# Then this makes the simple plots:\n\ndef make_plot():\n \n height = int(1.15*533)\n width = int(1.15*750)\n \n foo = df.loc[product_select.value]\n #foo = df.query(\"@a < a\")\n # below there is an object of selections which will be one of the values in \n # the list of options. So the .value then grabs that particular option selected.\n\n x = foo.index\n \n if level_select.value == 'US Dollars':\n y = foo['china_exports']\n \n if level_select.value == 'Year over Year % Change':\n y = growth_trade(foo)\n \n if level_select.value == \"Cumulative Purchases 2020 vs 2017\":\n cuml = cum_trade(foo)\n x = cuml.index\n y2017 = cuml[\"cuml_trade_2017\"]\n y2020 = cuml[\"cuml_trade_2020\"] \n\n \n title = \"US Exports to China of \" + product_select.value.title().upper()\n \n if level_select.value != \"Cumulative Purchases 2020 vs 2017\":\n \n # This is standard bokeh stuff so far\n plot = figure(x_axis_type=\"datetime\", plot_height = height, plot_width=width, toolbar_location = 'below',\n tools = \"box_zoom, reset, pan, xwheel_zoom\", title = title,\n x_range = (start_date,end_date) )\n\n plot.line(x = x,\n y = y, line_width=3.5, line_alpha=0.75, line_color = \"slategray\")\n \n if level_select.value == \"Cumulative Purchases 2020 vs 2017\":\n \n plot = figure(x_axis_type=\"datetime\", plot_height = height, plot_width=width, toolbar_location = 'below',\n tools = \"box_zoom, reset, pan\", title = title,\n x_range = (dt.datetime(2020,1,1),dt.datetime(2021,2,1)) )\n\n plot.line(x = x,\n y = y2017, line_width=3.5, line_alpha=0.5, line_color = \"red\", line_dash = \"dashed\"\n , legend_label= \"2017\")\n \n plot.line(x = x,\n y = y2020, line_width=3.5, line_alpha=0.75, line_color = \"darkblue\"\n , legend_label= \"2020\")\n \n plot.legend.title = 'Cumulative Purchases'\n plot.legend.location = \"top_left\"\n plot.legend.title_text_font_style = \"bold\"\n \n # fixed attributes\n plot.xaxis.axis_label = None\n plot.yaxis.axis_label = \"\"\n plot.axis.axis_label_text_font_style = \"bold\"\n plot.grid.grid_line_alpha = 0.3\n \n TIMETOOLTIPS = \"\"\"\n <div style=\"background-color:#F5F5F5; opacity: 0.95; border: 15px 15px 15px 15px;\">\n <div style = \"text-align:left;\">\"\"\"\n \n if level_select.value == 'Year over Year % Change':\n \n TIMETOOLTIPS = TIMETOOLTIPS + \"\"\"\n <span style=\"font-size: 13px; font-weight: bold\"> $data_x{%b %Y}: $data_y{0}%</span> \n </div>\n </div>\n \"\"\"\n \n plot.add_tools(HoverTool(tooltips = TIMETOOLTIPS, line_policy='nearest', formatters={'$data_x': 'datetime'}))\n \n if level_select.value == 'US Dollars':\n \n TIMETOOLTIPS = TIMETOOLTIPS + \"\"\"\n <span style=\"font-size: 13px; font-weight: bold\"> $data_x{%b %Y}: $data_y{$0.0a}</span> \n </div>\n </div>\n \"\"\"\n plot.add_tools(HoverTool(tooltips = TIMETOOLTIPS, line_policy='nearest', formatters={'$data_x': 'datetime'}))\n \n if level_select.value == \"Cumulative Purchases 2020 vs 2017\":\n #################################################################################\n singlesource2020 = ColumnDataSource({\n 'xs': x.values,\n 'ys': y2020.values,\n \"dates\": np.array(x),\n })\n\n \n c2020 = plot.circle(x=\"xs\", y=\"ys\", size=35,\n source = singlesource2020, color = \"crimson\",alpha=0.0)\n \n singlesource2017 = ColumnDataSource({\n 'xs': x.values,\n 'ys': y2017.values,\n \"dates\": np.array(pd.date_range(start=\"2017-01-01\", end=\"2017-12-01\", freq = \"MS\")),\n })\n \n c2017 = plot.circle(x=\"xs\", y=\"ys\", size=35,\n source = singlesource2017, color = \"darkblue\",alpha=0.0)\n\n \n TIMETOOLTIPS = TIMETOOLTIPS + \"\"\"\n <span style=\"font-size: 13px; font-weight: bold\"> @dates{%b %Y}: $data_y{$0.0a}</span> \n </div>\n </div>\n \"\"\"\n \n plot.add_tools(HoverTool(tooltips = TIMETOOLTIPS, line_policy='nearest', formatters={'@dates': 'datetime'}, renderers = [c2017,c2020]))\n \n if level_select.value == 'Year over Year % Change':\n if y.max() > 1500:\n plot.y_range.end = 1500\n \n \n \n plot.title.text_font_size = '13pt'\n plot.background_fill_color = background \n plot.background_fill_alpha = 0.75\n plot.border_fill_color = background \n \n tradewar_box = BoxAnnotation(left=dt.datetime(2018,7,1), right=dt.datetime(2019,10,11), fill_color='red', fill_alpha=0.1)\n plot.add_layout(tradewar_box)\n \n tradewar_box = BoxAnnotation(left=dt.datetime(2020,1,1), right=dt.datetime(2021,12,31), fill_color='blue', fill_alpha=0.1)\n plot.add_layout(tradewar_box)\n \n #p.yaxis.axis_label = \n plot.yaxis.axis_label_text_font_style = 'bold'\n plot.yaxis.axis_label_text_font_size = \"13px\"\n \n plot.sizing_mode= \"scale_both\"\n \n \n if level_select.value != 'Year over Year % Change':\n \n plot.yaxis.formatter = NumeralTickFormatter(format=\"($0. a)\")\n \n plot.yaxis.axis_label = \"US Dollars\"\n \n if level_select.value == 'Year over Year % Change':\n \n plot.yaxis.axis_label = level_select.value\n \n plot.max_height = height\n plot.max_width = width\n \n plot.min_height = int(0.25*height)\n plot.min_width = int(0.25*width)\n \n return plot\n\ndef update_plot(attrname, old, new):\n layout.children[0] = make_plot()\n \n# This part is still not clear to me. but it tells it what to update and where to put it\n# so it updates the layout and [0] is the first option (see below there is a row with the\n# first entry the plot, then the controls)\n\nlevel_select = Select(value=level, title='Tranformations', options=['US Dollars', 'Year over Year % Change', \"Cumulative Purchases 2020 vs 2017\"])\nlevel_select.on_change('value', update_plot)\n\n#print(sorted(options))\n\nproduct_select = Select(value=product, title='Product', options=sorted(options), width=400)\n# This is the key thing that creates teh selection object\n\nproduct_select.on_change('value', update_plot)\n# Change the value upone selection via the update plot \n\ndiv0 = Div(text = \"\"\"Categories are at both the HS2 and HS4 level. Only Phase One covered products as defined in Annex 6-1 of The Agreement within that HS Code are shown. Red marks the period of Section 301 tariffs and retaliation. Blue is period of agreement.\\n\n \\n\n \\n\n \"\"\", width=400, background = background, style={\"justify-content\": \"space-between\", \"display\": \"flex\"} )\n\ndiv1 = Div(text = \"\"\"Transformations: US Dollars, year over year growth rate and cumulative purchases in 2017 vs 2020.\\n The later transformation cumulates Chinese purchases over each month in 2017 and 2020 and compares each. Because 2017 is the benchmark year for The Agreement, this measure provides a sense, for each product category, China's progress towards meeting their purchase commitments.\\n\n \"\"\", width=400, background = background, style={\"justify-content\": \"space-between\", \"display\": \"flex\"} )\n\ncontrols = column(product_select, div0, level_select, div1)\n\nheight = int(1.95*533)\nwidth = int(1.95*675)\n\nlayout = row(make_plot(), controls, sizing_mode = \"scale_height\", max_height = height, max_width = width,\n min_height = int(0.25*height), min_width = int(0.25*width))\n\ncurdoc().add_root(layout)\ncurdoc().title = \"us-china-products\"\n"
]
[
"# Copyright (c) 2016, Xilinx, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\nimport os\nimport warnings\nfrom .mmio import MMIO\nfrom .registers import Register\n\n__author__ = \"Yun Rock Qu\"\n__copyright__ = \"Copyright 2017, Xilinx\"\n__email__ = \"[email protected]\"\n\nZYNQ_ARCH = \"armv7l\"\nZU_ARCH = \"aarch64\"\nCPU_ARCH = os.uname().machine\nCPU_ARCH_IS_SUPPORTED = CPU_ARCH in [ZYNQ_ARCH, ZU_ARCH]\n\nDEFAULT_PL_CLK_MHZ = 100.0\n\n\nclass _ClocksMeta(type):\n \"\"\"Meta class for all the PS and PL clocks not exposed to users.\n\n Since this is the abstract base class for all the clocks, no\n attributes or methods are exposed to users. Users should use the class\n `Clocks` instead.\n\n Note\n ----\n If this class is parsed on an unsupported architecture it will issue\n a warning and leave class variables undefined\n\n \"\"\"\n @property\n def cpu_mhz(cls):\n \"\"\"The getter method for CPU clock.\n\n The returned clock rate is measured in MHz.\n\n \"\"\"\n return cls.get_cpu_mhz()\n\n @cpu_mhz.setter\n def cpu_mhz(cls, clk_mhz):\n \"\"\"The setter method for CPU clock.\n\n Since the CPU clock should not be changed, setting it will raise\n an exception.\n\n \"\"\"\n raise RuntimeError(\"Not allowed to change CPU clock.\")\n\n @property\n def fclk0_mhz(cls):\n \"\"\"The getter method for PL clock 0.\n\n This method will read the register values, do the calculation,\n and return the current clock rate.\n\n Returns\n -------\n float\n The returned clock rate measured in MHz.\n\n \"\"\"\n return cls.get_pl_clk(0)\n\n @fclk0_mhz.setter\n def fclk0_mhz(cls, clk_mhz):\n \"\"\"The setter method for PL clock 0.\n\n Parameters\n ----------\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n cls.set_pl_clk(0, clk_mhz=clk_mhz)\n\n @property\n def fclk1_mhz(cls):\n \"\"\"The getter method for PL clock 1.\n\n This method will read the register values, do the calculation,\n and return the current clock rate.\n\n Returns\n -------\n float\n The returned clock rate measured in MHz.\n\n \"\"\"\n return cls.get_pl_clk(1)\n\n @fclk1_mhz.setter\n def fclk1_mhz(cls, clk_mhz):\n \"\"\"The setter method for PL clock 1.\n\n Parameters\n ----------\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n cls.set_pl_clk(1, clk_mhz=clk_mhz)\n\n @property\n def fclk2_mhz(cls):\n \"\"\"The getter method for PL clock 2.\n\n This method will read the register values, do the calculation,\n and return the current clock rate.\n\n Returns\n -------\n float\n The returned clock rate measured in MHz.\n\n \"\"\"\n return cls.get_pl_clk(2)\n\n @fclk2_mhz.setter\n def fclk2_mhz(cls, clk_mhz):\n \"\"\"The setter method for PL clock 2.\n\n Parameters\n ----------\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n cls.set_pl_clk(2, clk_mhz=clk_mhz)\n\n @property\n def fclk3_mhz(cls):\n \"\"\"The getter method for PL clock 3.\n\n This method will read the register values, do the calculation,\n and return the current clock rate.\n\n Returns\n -------\n float\n The returned clock rate measured in MHz.\n\n \"\"\"\n return cls.get_pl_clk(3)\n\n @fclk3_mhz.setter\n def fclk3_mhz(cls, clk_mhz):\n \"\"\"The setter method for PL clock 3.\n\n Parameters\n ----------\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n cls.set_pl_clk(3, clk_mhz=clk_mhz)\n\n @classmethod\n def get_pl_clk(mcs, clk_idx):\n \"\"\"This method will return the clock frequency.\n\n This method is not exposed to users.\n\n Parameters\n ----------\n clk_idx : int\n The index of the PL clock to be changed, from 0 to 3.\n\n \"\"\"\n if clk_idx not in range(4):\n raise ValueError(\"Valid PL clock index is 0 - 3.\")\n\n pl_clk_reg = mcs.PL_CLK_CTRLS[clk_idx]\n src_clk_idx = pl_clk_reg[mcs.PL_CLK_SRC_FIELD]\n src_clk_mhz = mcs._get_src_clk_mhz(src_clk_idx)\n pl_clk_odiv0 = pl_clk_reg[mcs.PL_CLK_ODIV0_FIELD]\n pl_clk_odiv1 = pl_clk_reg[mcs.PL_CLK_ODIV1_FIELD]\n\n return round(src_clk_mhz / (pl_clk_odiv0 * pl_clk_odiv1), 6)\n\n @classmethod\n def set_pl_clk(mcs, clk_idx, div0=None, div1=None,\n clk_mhz=DEFAULT_PL_CLK_MHZ):\n \"\"\"This method sets a PL clock frequency.\n\n Users have to specify the index of the PL clock to be changed.\n For example, for fclk1 (Zynq) or pl_clk_1 (ZynqUltrascale),\n `clk_idx` is 1.\n\n The CPU, and other source clocks, by default, should not get changed.\n\n Users have two options:\n 1. specify the two frequency divider values directly (div0, div1), or\n 2. specify the clock rate, in which case the divider values will be\n calculated.\n\n Note\n ----\n In case `div0` and `div1` are both specified, the parameter `clk_mhz`\n will be ignored.\n\n Parameters\n ----------\n clk_idx : int\n The index of the PL clock to be changed, from 0 to 3.\n div0 : int\n The first frequency divider value.\n div1 : int\n The second frequency divider value.\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n if clk_idx not in range(4):\n raise ValueError(\"Valid PL clock index is 0 - 3.\")\n\n pl_clk_reg = mcs.PL_CLK_CTRLS[clk_idx]\n div0_width = Register.count(mcs.PL_CLK_ODIV0_FIELD)\n div1_width = Register.count(mcs.PL_CLK_ODIV1_FIELD)\n src_clk_idx = pl_clk_reg[mcs.PL_CLK_SRC_FIELD]\n src_clk_mhz = mcs._get_src_clk_mhz(src_clk_idx)\n\n if div0 is None and div1 is None:\n div0, div1 = mcs._get_2_divisors(src_clk_mhz, clk_mhz,\n div0_width, div1_width)\n elif div0 is not None and div1 is None:\n div1 = round(src_clk_mhz / clk_mhz / div0)\n elif div1 is not None and div0 is None:\n div0 = round(src_clk_mhz / clk_mhz / div1)\n\n if div0 <= 0 or div0 > ((1 << div0_width) - 1):\n raise ValueError(\"Frequency divider 0 value out of range.\")\n if div1 <= 0 or div1 > ((1 << div1_width) - 1):\n raise ValueError(\"Frequency divider 1 value out of range.\")\n\n pl_clk_reg[mcs.PL_CLK_ODIV0_FIELD] = div0\n pl_clk_reg[mcs.PL_CLK_ODIV1_FIELD] = div1\n\n @classmethod\n def _get_src_clk_mhz(mcs, clk_idx):\n \"\"\"The getter method for PL clock (pl_clk) sources.\n\n The returned clock rate is measured in MHz.\n\n \"\"\"\n if clk_idx not in range(4):\n raise ValueError(\"Valid PL clock index is 0 - 3.\")\n\n src_pll_reg = mcs.PL_SRC_PLL_CTRLS[clk_idx]\n return round(mcs.get_pll_mhz(src_pll_reg), 6)\n\n @classmethod\n def _get_2_divisors(mcs, freq_high, freq_desired, reg0_width, reg1_width):\n \"\"\"Return 2 divisors of the specified width for frequency divider.\n\n Warning will be raised if the closest clock rate achievable\n differs more than 1 percent of the desired value.\n\n Parameters\n ----------\n freq_high : float\n High frequency to be divided.\n freq_desired : float\n Desired frequency to be get.\n reg0_width: int\n The register width of the first divisor.\n reg1_width : int\n The register width of the second divisor.\n\n Returns\n -------\n tuple\n A pair of 2 divisors, each of 6 bits at most.\n\n \"\"\"\n div_product_desired = round(freq_high / freq_desired, 6)\n _, q0 = min(enumerate(mcs.VALID_CLOCK_DIV_PRODUCTS),\n key=lambda x: abs(x[1] - div_product_desired))\n if abs(freq_desired - freq_high / q0) > 0.01 * freq_desired:\n warnings.warn(\n \"Setting frequency to the closet possible value {}MHz.\".format(\n round(freq_high / q0, 5)))\n\n max_val0 = 1 << reg0_width\n max_val1 = 1 << reg1_width\n for i in range(1, max_val0):\n for j in range(1, max_val1):\n if i * j == q0:\n return i, j\n\n\nclass _ClocksUltrascale(_ClocksMeta):\n \"\"\"Implementation class for all Zynq Ultrascale PS and PL clocks\n not exposed to users.\n\n Since this is the abstract base class for all Zynq Ultrascale clocks, no\n attributes or methods are exposed to users. Users should use the class\n `Clocks` instead.\n\n \"\"\"\n DEFAULT_SRC_CLK_MHZ = 33.333\n\n # Registers in the CRL \"Namespace\"\n CRL_APB_ADDRESS = 0xFF5E0000\n IOPLL_CTRL_OFFSET = 0x20\n RPLL_CTRL_OFFSET = 0x30\n\n PL0_CTRL_OFFSET = 0xC0\n PL1_CTRL_OFFSET = 0xC4\n PL2_CTRL_OFFSET = 0xC8\n PL3_CTRL_OFFSET = 0xCC\n PLX_CTRL_CLKACT_FIELD = 24\n PLX_CTRL_ODIV1_FIELD = slice(21, 16)\n PLX_CTRL_ODIV0_FIELD = slice(13, 8)\n PLX_CTRL_SRC_FIELD = slice(2, 0)\n\n PLX_CTRL_SRC_DEFAULT = 0\n\n PL_CLK_SRC_FIELD = PLX_CTRL_SRC_FIELD\n PL_CLK_ODIV0_FIELD = PLX_CTRL_ODIV0_FIELD\n PL_CLK_ODIV1_FIELD = PLX_CTRL_ODIV1_FIELD\n\n # Registers in the CRF \"Namespace\"\n CRF_APB_ADDRESS = 0xFD1A0000\n APLL_CTRL_OFFSET = 0x20\n DPLL_CTRL_OFFSET = 0x2C\n VPLL_CTRL_OFFSET = 0x38\n\n ACPU_CTRL_OFFSET = 0x60\n ACPU_CTRL_CLKHALF_FIELD = 25\n ACPU_CTRL_CLKFULL_FIELD = 24\n ACPU_CTRL_ODIV_FIELD = slice(13, 8)\n ACPU_CTRL_SRC_FIELD = slice(2, 0)\n\n # Fields shared between CRF and CRL \"Namespaces\"\n CRX_APB_SRC_DEFAULT = 0\n CRX_APB_SRC_FIELD = slice(22, 20)\n CRX_APB_ODIVBY2_FIELD = 16\n CRX_APB_FBDIV_FIELD = slice(14, 8)\n\n PLX_CTRL_ODIV1_WIDTH = (PLX_CTRL_ODIV1_FIELD.start -\n PLX_CTRL_ODIV1_FIELD.stop + 1)\n PLX_CTRL_ODIV0_WIDTH = (PLX_CTRL_ODIV0_FIELD.start -\n PLX_CTRL_ODIV0_FIELD.stop + 1)\n VALID_CLOCK_DIV_PRODUCTS = sorted(list(set(\n (np.multiply(\n np.arange(1 << PLX_CTRL_ODIV1_WIDTH).reshape(\n 1 << PLX_CTRL_ODIV1_WIDTH, 1),\n np.arange(1 << PLX_CTRL_ODIV0_WIDTH))).reshape(-1))))\n\n if CPU_ARCH_IS_SUPPORTED:\n IOPLL_CTRL = Register(CRL_APB_ADDRESS + IOPLL_CTRL_OFFSET)\n RPLL_CTRL = Register(CRL_APB_ADDRESS + RPLL_CTRL_OFFSET)\n\n PL_CLK_CTRLS = [Register(CRL_APB_ADDRESS + PL0_CTRL_OFFSET),\n Register(CRL_APB_ADDRESS + PL1_CTRL_OFFSET),\n Register(CRL_APB_ADDRESS + PL2_CTRL_OFFSET),\n Register(CRL_APB_ADDRESS + PL3_CTRL_OFFSET)]\n\n ACPU_CTRL = Register(CRF_APB_ADDRESS + ACPU_CTRL_OFFSET)\n\n APLL_CTRL = Register(CRF_APB_ADDRESS + APLL_CTRL_OFFSET)\n DPLL_CTRL = Register(CRF_APB_ADDRESS + DPLL_CTRL_OFFSET)\n VPLL_CTRL = Register(CRF_APB_ADDRESS + VPLL_CTRL_OFFSET)\n\n PL_SRC_PLL_CTRLS = [IOPLL_CTRL, IOPLL_CTRL, RPLL_CTRL, DPLL_CTRL]\n ACPU_SRC_PLL_CTRLS = [APLL_CTRL, APLL_CTRL, DPLL_CTRL, VPLL_CTRL]\n else:\n warnings.warn(\"Pynq does not support the CPU Architecture: {}\"\n .format(CPU_ARCH), ResourceWarning)\n\n\n @classmethod\n def set_pl_clk(mcs, clk_idx, div0=None, div1=None,\n clk_mhz=DEFAULT_PL_CLK_MHZ):\n \"\"\"This method sets a PL clock frequency.\n\n Users have to specify the index of the PL clock to be changed.\n\n The CPU, and other source clocks, by default, should not get changed.\n\n Users have two options:\n 1. specify the two frequency divider values directly (div0, div1), or\n 2. specify the clock rate, in which case the divider values will be\n calculated.\n\n Note\n ----\n In case `div0` and `div1` are both specified, the parameter `clk_mhz`\n will be ignored.\n\n Parameters\n ----------\n clk_idx : int\n The index of the PL clock to be changed, from 0 to 3.\n div0 : int\n The first frequency divider value.\n div1 : int\n The second frequency divider value.\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n pl_clk_reg = mcs.PL_CLK_CTRLS[clk_idx]\n pl_clk_reg[mcs.PLX_CTRL_CLKACT_FIELD] = 1\n pl_clk_reg[mcs.PLX_CTRL_SRC_FIELD] = mcs.PLX_CTRL_SRC_DEFAULT\n super().set_pl_clk(clk_idx, div0, div1, clk_mhz)\n\n @classmethod\n def get_pll_mhz(mcs, pll_reg):\n \"\"\"The getter method for PLL output clocks.\n\n Parameters\n ----------\n pll_reg : Register\n The control register for a PLL\n\n Returns\n -------\n float\n The PLL output clock rate measured in MHz.\n\n \"\"\"\n if pll_reg[mcs.CRX_APB_SRC_FIELD] != mcs.CRX_APB_SRC_DEFAULT:\n raise ValueError(\"Invalid PLL Source\")\n\n pll_fbdiv = pll_reg[mcs.CRX_APB_FBDIV_FIELD]\n if pll_reg[mcs.CRX_APB_ODIVBY2_FIELD] == 1:\n pll_odiv2 = 2\n else:\n pll_odiv2 = 1\n\n return mcs.DEFAULT_SRC_CLK_MHZ * pll_fbdiv / pll_odiv2\n\n @classmethod\n def get_cpu_mhz(mcs):\n \"\"\"The getter method for CPU clock.\n\n The returned clock rate is measured in MHz.\n\n \"\"\"\n arm_src_pll_idx = mcs.ACPU_CTRL[mcs.ACPU_CTRL_SRC_FIELD]\n arm_clk_odiv = mcs.ACPU_CTRL[mcs.ACPU_CTRL_ODIV_FIELD]\n src_pll_reg = mcs.ACPU_SRC_PLL_CTRLS[arm_src_pll_idx]\n return round(mcs.get_pll_mhz(src_pll_reg) / arm_clk_odiv, 6)\n\n\nclass _ClocksZynq(_ClocksMeta):\n \"\"\"Implementation class for all Zynq 7-Series PS and PL clocks\n not exposed to users.\n\n Since this is the abstract base class for all Zynq 7-Series clocks, no\n attributes or methods are exposed to users. Users should use the class\n `Clocks` instead.\n\n \"\"\"\n DEFAULT_SRC_CLK_MHZ = 50.0\n\n SLCR_BASE_ADDRESS = 0xF8000000\n ARM_PLL_CTRL_OFFSET = 0x100\n DDR_PLL_CTRL_OFFSET = 0x104\n IO_PLL_CTRL_OFFSET = 0x108\n SRC_PLL_FBDIV_FIELD = slice(18, 12)\n\n FCLK0_CTRL_OFFSET = 0x170\n FCLK1_CTRL_OFFSET = 0x180\n FCLK2_CTRL_OFFSET = 0x190\n FCLK3_CTRL_OFFSET = 0x1A0\n FCLKX_CTRL_ODIV1_FIELD = slice(25, 20)\n FCLKX_CTRL_ODIV0_FIELD = slice(13, 8)\n FCLKX_CTRL_SRC_FIELD = slice(5, 4)\n\n PL_CLK_SRC_FIELD = FCLKX_CTRL_SRC_FIELD\n PL_CLK_ODIV0_FIELD = FCLKX_CTRL_ODIV0_FIELD\n PL_CLK_ODIV1_FIELD = FCLKX_CTRL_ODIV1_FIELD\n\n ARM_CLK_CTRL_OFFSET = 0x120\n ARM_CLK_ODIV_FIELD = slice(13, 8)\n ARM_CLK_SRC_FIELD = slice(5, 4)\n\n FCLKX_CTRL_ODIV1_WIDTH = (FCLKX_CTRL_ODIV1_FIELD.start -\n FCLKX_CTRL_ODIV1_FIELD.stop + 1)\n FCLKX_CTRL_ODIV0_WIDTH = (FCLKX_CTRL_ODIV0_FIELD.start -\n FCLKX_CTRL_ODIV0_FIELD.stop + 1)\n VALID_CLOCK_DIV_PRODUCTS = sorted(list(set(\n (np.multiply(\n np.arange(1 << FCLKX_CTRL_ODIV1_WIDTH).reshape(\n 1 << FCLKX_CTRL_ODIV1_WIDTH, 1),\n np.arange(1 << FCLKX_CTRL_ODIV0_WIDTH))).reshape(-1))))\n\n if CPU_ARCH_IS_SUPPORTED:\n ARM_PLL_CTRL = Register(SLCR_BASE_ADDRESS + ARM_PLL_CTRL_OFFSET)\n DDR_PLL_CTRL = Register(SLCR_BASE_ADDRESS + DDR_PLL_CTRL_OFFSET)\n IO_PLL_CTRL = Register(SLCR_BASE_ADDRESS + IO_PLL_CTRL_OFFSET)\n\n PL_SRC_PLL_CTRLS = [IO_PLL_CTRL, IO_PLL_CTRL,\n ARM_PLL_CTRL, DDR_PLL_CTRL]\n\n PL_CLK_CTRLS = [Register(SLCR_BASE_ADDRESS + FCLK0_CTRL_OFFSET),\n Register(SLCR_BASE_ADDRESS + FCLK1_CTRL_OFFSET),\n Register(SLCR_BASE_ADDRESS + FCLK2_CTRL_OFFSET),\n Register(SLCR_BASE_ADDRESS + FCLK3_CTRL_OFFSET)]\n\n ARM_CLK_CTRL = Register(SLCR_BASE_ADDRESS + ARM_CLK_CTRL_OFFSET)\n\n ARM_SRC_PLL_CTRLS = [ARM_PLL_CTRL, ARM_PLL_CTRL,\n DDR_PLL_CTRL, IO_PLL_CTRL]\n else:\n warnings.warn(\"Pynq does not support the CPU Architecture: {}\"\n .format(CPU_ARCH), ResourceWarning)\n\n\n @classmethod\n def set_pl_clk(mcs, clk_idx, div0=None, div1=None,\n clk_mhz=DEFAULT_PL_CLK_MHZ):\n \"\"\"This method sets a PL clock frequency.\n\n Users have to specify the index of the PL clock to be changed.\n\n The CPU, and other source clocks, by default, should not get changed.\n\n Users have two options:\n 1. specify the two frequency divider values directly (div0, div1), or\n 2. specify the clock rate, in which case the divider values will be\n calculated.\n\n Note\n ----\n In case `div0` and `div1` are both specified, the parameter `clk_mhz`\n will be ignored.\n\n Parameters\n ----------\n clk_idx : int\n The index of the PL clock to be changed, from 0 to 3.\n div0 : int\n The first frequency divider value.\n div1 : int\n The second frequency divider value.\n clk_mhz : float\n The clock rate in MHz.\n\n \"\"\"\n super().set_pl_clk(clk_idx, div0, div1, clk_mhz)\n\n @classmethod\n def get_pll_mhz(mcs, pll_reg):\n \"\"\"The getter method for PLL output clocks.\n\n Parameters\n ----------\n pll_reg : Register\n The control register for a PLL\n\n Returns\n -------\n float\n The PLL output clock rate measured in MHz.\n\n \"\"\"\n pll_fbdiv = pll_reg[mcs.SRC_PLL_FBDIV_FIELD]\n clk_mhz = mcs.DEFAULT_SRC_CLK_MHZ * pll_fbdiv\n\n return round(clk_mhz, 6)\n\n @classmethod\n def get_cpu_mhz(mcs):\n \"\"\"The getter method for the CPU clock.\n\n Returns\n -------\n float\n The CPU clock rate measured in MHz.\n\n \"\"\"\n arm_src_pll_idx = mcs.ARM_CLK_CTRL[mcs.ARM_CLK_SRC_FIELD]\n arm_clk_odiv = mcs.ARM_CLK_CTRL[mcs.ARM_CLK_ODIV_FIELD]\n src_pll_reg = mcs.ARM_SRC_PLL_CTRLS[arm_src_pll_idx]\n return round(mcs.get_pll_mhz(src_pll_reg) / arm_clk_odiv, 6)\n\n\nif CPU_ARCH == ZU_ARCH:\n _ClockParent = _ClocksUltrascale\nelif CPU_ARCH == ZYNQ_ARCH:\n _ClockParent = _ClocksZynq\nelse:\n _ClockParent = object\n warnings.warn(\"PYNQ does not support the CPU Architecture: \"\n \"{}\".format(CPU_ARCH))\n\n\nclass Clocks(_ClockParent, metaclass=_ClocksMeta):\n \"\"\"Class for all the PS and PL clocks exposed to users.\n\n With this class, users can get the CPU clock and all the PL clocks. Users\n can also set PL clocks to other values using this class.\n\n Attributes\n ----------\n cpu_mhz : float\n The clock rate of the CPU, measured in MHz.\n fclk0_mhz : float\n The clock rate of the PL clock 0, measured in MHz.\n fclk1_mhz : float\n The clock rate of the PL clock 1, measured in MHz.\n fclk2_mhz : float\n The clock rate of the PL clock 2, measured in MHz.\n fclk3_mhz : float\n The clock rate of the PL clock 3, measured in MHz.\n\n \"\"\"\n pass\n"
]
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `tf.data.Dataset.map()`.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nimport threading\nimport warnings\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.data.experimental.ops import threading_options\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops import map_fn\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops import string_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\ndef _make_coordinated_sloppy_dataset(num_elements, num_parallel_calls):\n \"\"\"Produces a dataset iterator and events to control the order of elements.\n\n Args:\n num_elements: the number of input elements\n num_parallel_calls: the degree of map parallelism\n\n Returns:\n A dataset iterator (represented as `get_next` op) and events that can be\n used to control the order of output elements.\n \"\"\"\n\n # Set up threading events used to sequence when items are produced that\n # are subsequently interleaved. These events allow us to deterministically\n # simulate slowdowns and force sloppiness.\n coordination_events = {i: threading.Event() for i in range(num_elements)}\n\n def map_py_fn(x):\n coordination_events[x].wait()\n coordination_events[x].clear()\n return x * x\n\n def map_fn(x):\n return script_ops.py_func(map_py_fn, [x], x.dtype)\n\n options = dataset_ops.Options()\n options.experimental_deterministic = False\n dataset = dataset_ops.Dataset.range(num_elements).map(\n map_fn, num_parallel_calls).with_options(options)\n return dataset, coordination_events\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass MapTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n def _buildMapDataset(self, components, count):\n\n def _map_fn(x, y, z):\n return math_ops.square(x), math_ops.square(y), math_ops.square(z)\n\n dataset = dataset_ops.Dataset.from_tensor_slices(components).map(\n _map_fn).repeat(count)\n self.assertEqual([c.shape[1:] for c in components],\n [shape for shape in dataset.output_shapes])\n return dataset\n\n def testMapDataset(self):\n \"\"\"Test an dataset that maps a TF function across its input elements.\"\"\"\n # The pipeline is TensorSliceDataset -> MapDataset(square_3) ->\n # RepeatDataset(count).\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n\n # Test single-threaded access to the iterator.\n get_next = self.getNext(self._buildMapDataset(components, 14))\n for _ in range(14):\n for i in range(7):\n result = self.evaluate(get_next())\n for component, result_component in zip(components, result):\n self.assertAllEqual(component[i]**2, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n # TODO(b/117581999): add eager coverage, different threads run in graph\n # context.\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerMapDatasetMultithreaded(self):\n # Test multi-threaded access to the same iterator.\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n get_next = self.getNext(self._buildMapDataset(components, 18))\n results = []\n with self.cached_session() as sess:\n def iterator_thread():\n while True:\n try:\n results.append(sess.run(get_next()))\n except errors.OutOfRangeError:\n return\n threads = [self.checkedThread(target=iterator_thread) for _ in range(8)]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n # `results` will contain the same elements components**2\n # repeated 18 times, but in a non-deterministic order. Sort the\n # results, and assert that each element of components**2 is\n # produced 18 times.\n results.sort(key=lambda x: x[0])\n for i in range(7):\n for j in range(18):\n for component, result_component in zip(components,\n results[i * 18 + j]):\n self.assertAllEqual(component[i]**2, result_component)\n\n def _buildParallelMapDataset(self, components, count, num_parallel_calls,\n output_buffer_size):\n\n def _map_fn(x, y, z):\n return math_ops.square(x), math_ops.square(y), math_ops.square(z)\n\n dataset = dataset_ops.Dataset.from_tensor_slices(components).map(\n _map_fn, num_parallel_calls=num_parallel_calls).prefetch(\n output_buffer_size).repeat(count)\n\n self.assertEqual([c.shape[1:] for c in components],\n [shape for shape in dataset.output_shapes])\n return dataset\n\n def testParallelMapDataset(self):\n \"\"\"Test an dataset that maps a TF function across its input elements.\"\"\"\n\n # The pipeline is TensorSliceDataset -> ParallelMapDataset(square_3) ->\n # RepeatDataset(count).\n def do_test(num_parallel_calls, output_buffer_size):\n\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n # Test single-threaded access to the iterator.\n get_next = self.getNext(\n self._buildParallelMapDataset(components, 14, num_parallel_calls,\n output_buffer_size))\n for _ in range(14):\n for i in range(7):\n result = self.evaluate(get_next())\n for component, result_component in zip(components, result):\n self.assertAllEqual(component[i]**2, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n for num_parallel_calls_val, output_buffer_size_val in [(1, 1), (1, 2), (2,\n 2),\n (2, 4), (8, 8),\n (8, 16)]:\n do_test(num_parallel_calls_val, output_buffer_size_val)\n\n # TODO(b/117581999): add eager coverage, different threads run in graph\n # context.\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerParallelMapDatasetMultithreaded(self):\n\n def do_test(num_parallel_calls, output_buffer_size):\n # Test multi-threaded access to the same iterator.\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n get_next = self.getNext(\n self._buildParallelMapDataset(components, 18, num_parallel_calls,\n output_buffer_size))\n results = []\n with self.cached_session() as sess:\n\n def iterator_thread():\n while True:\n try:\n results.append(sess.run(get_next()))\n except errors.OutOfRangeError:\n return\n threads = [self.checkedThread(target=iterator_thread)\n for _ in range(64)]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n # `results` will contain the same elements components**2\n # repeated 18 times, but in a non-deterministic order. Sort the\n # results, and assert that each element of components**2 is\n # produced 18 times.\n results.sort(key=lambda x: x[0])\n for i in range(7):\n for j in range(18):\n for component, result_component in zip(components,\n results[i * 18 + j]):\n self.assertAllEqual(component[i]**2, result_component)\n\n for num_parallel_calls_val, output_buffer_size_val in [\n (1, 1), (1, 2), (2, 2), (2, 4), (8, 8), (8, 16)]:\n do_test(num_parallel_calls_val, output_buffer_size_val)\n\n def testImplicitDisposeParallelMapDataset(self):\n # Tests whether a parallel map dataset will be cleaned up correctly when\n # the pipeline does not run it until exhaustion.\n # The pipeline is TensorSliceDataset -> MapDataset(square_3) ->\n # RepeatDataset(1000).\n components = (np.arange(1000),\n np.array([[1, 2, 3]]) * np.arange(1000)[:, np.newaxis],\n np.array(37.0) * np.arange(1000))\n\n dataset = self._buildParallelMapDataset(components, 1000, 100, 100)\n # NOTE(mrry): Also test that the prefetching thread is cancelled correctly.\n dataset = dataset.prefetch(100)\n get_next = self.getNext(dataset)\n\n for _ in range(3):\n self.evaluate(get_next())\n\n def testParallelMapUnspecifiedOutputSize(self):\n components = np.array([1., 2., 3., np.nan, 5.]).astype(np.float32)\n\n dataset = (dataset_ops.Dataset.from_tensor_slices(components)\n .map(lambda x: array_ops.check_numerics(x, \"message\"),\n num_parallel_calls=2))\n get_next = self.getNext(dataset)\n\n for _ in range(3):\n self.evaluate(get_next())\n\n def testParallelMapError(self):\n components = np.array([1., 2., 3., np.nan, 5.]).astype(np.float32)\n\n dataset = (dataset_ops.Dataset.from_tensor_slices(components)\n .map(lambda x: array_ops.check_numerics(x, \"message\"),\n num_parallel_calls=2))\n get_next = self.getNext(dataset)\n\n for _ in range(3):\n self.evaluate(get_next())\n # The 4th element is NaN, so `array_ops.check_numerics()` should fail.\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(get_next())\n self.evaluate(get_next())\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testPrefetchError(self):\n components = np.array([1., 2., 3., np.nan, 5.]).astype(np.float32)\n\n dataset = (dataset_ops.Dataset.from_tensor_slices(components)\n .map(lambda x: array_ops.check_numerics(x, \"message\"))\n .prefetch(2))\n\n get_next = self.getNext(dataset)\n\n for _ in range(3):\n self.evaluate(get_next())\n # The 4th element is NaN, so `array_ops.check_numerics()` should fail.\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(get_next())\n self.evaluate(get_next())\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testCaptureIterator(self):\n\n def _build_ds(iterator):\n\n def _map_fn(x):\n get_next = iterator.get_next()\n return x * get_next\n\n return dataset_ops.Dataset.range(10).map(_map_fn)\n\n def _build_graph():\n if context.executing_eagerly():\n captured_iterator = iter(dataset_ops.Dataset.range(10))\n else:\n captured_iterator = dataset_ops.make_initializable_iterator(\n dataset_ops.Dataset.range(10))\n ds = _build_ds(captured_iterator)\n return captured_iterator, ds\n\n captured_iter, ds = _build_graph()\n if not context.executing_eagerly():\n self.evaluate(captured_iter.initializer)\n get_next = self.getNext(ds, requires_initialization=True)\n for i in range(10):\n self.assertEqual(i * i, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testCaptureHashTable(self):\n # NOTE(mrry): We must use the V2 variants of `HashTable`\n # etc. because these produce a `tf.resource`-typed output that is\n # compatible with the in-graph function implementation.\n default_val = -1\n keys = constant_op.constant([\"brain\", \"salad\", \"surgery\"])\n values = constant_op.constant([0, 1, 2], dtypes.int64)\n table = lookup_ops.HashTable(\n lookup_ops.KeyValueTensorInitializer(keys, values), default_val)\n\n input_sentences = dataset_ops.Dataset.from_tensor_slices(\n [\"brain brain tank salad surgery\", \"surgery brain\"])\n\n dataset = input_sentences.map(lambda x: string_ops.string_split([x]).values\n ).map(table.lookup)\n\n get_next = self.getNext(dataset, requires_initialization=True)\n\n self.evaluate(table.initializer)\n self.evaluate(get_next())\n self.evaluate(get_next())\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n @test_util.run_v1_only(\"b/123904513\")\n def testCaptureQueue(self):\n elements = np.random.randint(100, size=[200])\n queue = data_flow_ops.FIFOQueue(200, dtypes.int64, shapes=[])\n enqueue_op = queue.enqueue_many(elements)\n close_op = queue.close()\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(\n -1).map(lambda _: queue.dequeue())\n\n get_next = self.getNext(dataset, requires_initialization=True)\n self.evaluate(enqueue_op)\n self.evaluate(close_op)\n\n for element in elements:\n self.assertEqual(element, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n # TODO(b/117581999): Possible deadlock in eager mode, debug.\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerCaptureSameResourceMultipleTimes(self):\n elements = np.random.randint(100, size=[200])\n queue = data_flow_ops.FIFOQueue(\n 200, dtypes.int64, shapes=[], shared_name=\"shared_queue\")\n queue_2 = data_flow_ops.FIFOQueue(\n 200, dtypes.int64, shapes=[], shared_name=\"shared_queue\")\n\n enqueue_op = queue.enqueue_many(elements)\n close_op = queue.close()\n\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(\n -1).map(lambda _: (queue.dequeue(), queue_2.dequeue()))\n\n self.evaluate(enqueue_op)\n self.evaluate(close_op)\n get_next = self.getNext(dataset, requires_initialization=True)\n for i in range(100):\n self.assertCountEqual([elements[i * 2], elements[i * 2 + 1]],\n self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n # TODO(b/121264236): add eager mode coverage when we have mutli-device setup.\n @test_util.run_v1_only(\"b/121264236\")\n def testSkipEagerCaptureConstantsWithConflictingDevices(self):\n config = config_pb2.ConfigProto(device_count={\"CPU\": 3})\n with self.cached_session(config=config):\n with ops.device(\"/device:CPU:0\"):\n a = constant_op.constant(3.0)\n with ops.device(\"/device:CPU:1\"):\n b = constant_op.constant(5.0)\n\n def func(_):\n return math_ops.add(a, b)\n\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(10).map(func)\n expected_output = [8.0] * 10\n self.assertDatasetProduces(dataset, expected_output=expected_output)\n\n # TODO(b/121264236): add eager mode coverage when we have mutli-device setup.\n @test_util.run_v1_only(\n \"defun will convert RefVariables to ResourceVariables.\")\n def testSkipEagerRefVariablesWithConflictingDevices(self):\n config = config_pb2.ConfigProto(device_count={\"CPU\": 3})\n with self.cached_session(config=config):\n\n def func(_):\n with ops.device(\"/device:CPU:0\"):\n a = variables.VariableV1(3.0)\n with ops.device(\"/device:CPU:1\"):\n b = variables.VariableV1(5.0)\n return math_ops.add(a, b)\n\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(10).map(func)\n self.evaluate(variables.global_variables_initializer())\n expected_output = [8.0] * 10\n self.assertDatasetProduces(\n dataset,\n expected_output=expected_output,\n requires_initialization=True)\n\n # TODO(b/121264236): add eager mode coverage when we have mutli-device setup.\n @test_util.run_v1_only(\"b/121264236\")\n def testSkipEagerResourceVariablesWithConflictingDevices(self):\n config = config_pb2.ConfigProto(device_count={\"CPU\": 3})\n with self.cached_session(config=config):\n\n def func(_):\n with ops.device(\"/device:CPU:0\"):\n a = variables.Variable(3.0)\n with ops.device(\"/device:CPU:1\"):\n b = variables.Variable(5.0)\n return math_ops.add(a, b)\n\n # The MapDataset node ends up with two ResourceVariable inputs, one on\n # device CPU:0 and the other on device CPU:1. The placer cannot resolve\n # this as it cannot place the MapDatasetOp on both devices.\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(10).map(func)\n expected_error = (\n errors.InvalidArgumentError,\n \"Could not colocate node with its resource and reference inputs\")\n self.assertDatasetProduces(\n dataset, expected_error=expected_error, requires_initialization=True)\n\n def testCaptureVariable(self):\n counter_var = variable_scope.get_variable(\n \"counter\", (), dtypes.int32, use_resource=True)\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(\n 10).map(lambda _: counter_var.assign_add(1))\n get_next = self.getNext(dataset, requires_initialization=True)\n\n self.evaluate(counter_var.initializer)\n\n for i in range(10):\n self.assertEqual(i, self.evaluate(counter_var))\n self.assertEqual(i + 1, self.evaluate(get_next()))\n self.assertEqual(10, self.evaluate(counter_var))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n self.assertEqual(10, self.evaluate(counter_var))\n\n # TODO(b/117581999): error not captured for eager mode, debug.\n @test_util.run_v1_only(\"b/120545219\")\n def testSkipEagerCaptureUninitializedVariableError(self):\n counter_var = variable_scope.get_variable(\n \"counter\", (), dtypes.int32, use_resource=True)\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(\n 10).map(lambda _: counter_var.assign_add(1))\n\n get_next = self.getNext(dataset, requires_initialization=True)\n\n with self.assertRaises(errors.NotFoundError):\n self.evaluate(get_next())\n\n def testSeededStatefulOperatorIsProperlyStateful(self):\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(\n 10).map(lambda _: random_ops.random_uniform((), seed=11)).batch(2)\n\n get_next = self.getNext(dataset, requires_initialization=True)\n random_values = []\n with self.assertRaises(errors.OutOfRangeError):\n while True:\n random_values.extend(self.evaluate(get_next()))\n self.assertLen(random_values, 10)\n self.assertGreater(np.abs(np.diff(random_values)).max(), 1e-6)\n\n get_next = self.getNext(dataset, requires_initialization=True)\n random_values_2 = []\n with self.assertRaises(errors.OutOfRangeError):\n while True:\n random_values_2.extend(self.evaluate(get_next()))\n\n # Randomness is repeatable given same seed\n self.assertAllClose(random_values, random_values_2)\n\n def testStatefulMapKeepsStateAcrossIterators(self):\n dataset = dataset_ops.Dataset.from_tensors(0).repeat(10).map(\n lambda _: random_ops.random_uniform((), seed=11)).repeat(1000).batch(10)\n\n get_next = self.getNext(dataset)\n random_values = self.evaluate(get_next())\n\n # Assert that one of the next 99 batches yielded by the iterator is\n # different from the first.\n i = 0\n while i < 99:\n if np.any(random_values != self.evaluate(get_next())):\n break\n i += 1\n self.assertLess(i, 99)\n\n def testStatefulOperationInShortCircuit(self):\n counter_var = variable_scope.get_variable(\n \"counter\", (), dtypes.int32, use_resource=True)\n\n def increment_fn(x):\n counter_var.assign_add(1)\n return x\n\n dataset = dataset_ops.Dataset.range(10).map(increment_fn)\n\n get_next = self.getNext(dataset, requires_initialization=True)\n\n self.evaluate(counter_var.initializer)\n for i in range(10):\n self.assertEqual(i, self.evaluate(counter_var))\n self.assertEqual(i, self.evaluate(get_next()))\n self.assertEqual(10, self.evaluate(counter_var))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n self.assertEqual(10, self.evaluate(counter_var))\n\n def testMapDict(self):\n dataset = dataset_ops.Dataset.range(10).map(\n lambda x: {\"foo\": x * 2, \"bar\": x**2}).map(\n lambda d: d[\"foo\"] + d[\"bar\"])\n self.assertDatasetProduces(\n dataset, expected_output=[i * 2 + i**2 for i in range(10)])\n\n def testMapNamedtuple(self, count=10):\n # construct dataset of tuples\n labels = dataset_ops.Dataset.range(count)\n images = labels.map(lambda l: -l)\n dataset_tuple = dataset_ops.Dataset.zip((labels, images))\n\n # convert dataset of tuples to dataset of namedtuples\n example = namedtuple(\"Example\", [\"label\", \"image\"])\n dataset_namedtuple = dataset_tuple.map(example)\n\n def preprocess_tuple(label, image):\n image = 2 * image\n return label, image\n\n def preprocess_namedtuple(example):\n return example._replace(image=2 * example.image)\n\n # preprocess both datasets\n dataset_tuple = dataset_tuple.map(preprocess_tuple)\n dataset_namedtuple = dataset_namedtuple.map(preprocess_namedtuple)\n\n next_tuple = self.getNext(dataset_tuple)\n next_namedtuple = self.getNext(dataset_namedtuple)\n\n # make sure both datasets contain the same data\n for i in range(count):\n tuple_, namedtuple_ = self.evaluate([next_tuple(), next_namedtuple()])\n self.assertEqual(tuple_, namedtuple_)\n self.assertEqual(tuple_, (i, -2 * i))\n\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(next_namedtuple())\n\n def testUseStepContainerInMap(self):\n row = np.arange(6)\n dataset = dataset_ops.Dataset.from_tensors(\n row).map(lambda elems: map_fn.map_fn(lambda x: x * x, elems))\n self.assertDatasetProduces(dataset, expected_output=[row**2])\n\n def testCaseAndCondInMap(self):\n\n def control_map_fn(x, y):\n\n def multiply():\n return x * 2\n\n def divide():\n return x // 2\n\n def defaults_two():\n return control_flow_ops.cond(\n math_ops.equal(math_ops.mod(x, 2), 0),\n multiply,\n divide,\n name=\"cond_mult\")\n\n pred_fn_pairs = {\n math_ops.logical_or(math_ops.equal(y, 2), math_ops.equal(y, 3)):\n defaults_two,\n }\n\n return control_flow_ops.case(\n pred_fn_pairs, default=multiply, exclusive=True)\n\n def build_dataset(row, num):\n dataset = dataset_ops.Dataset.from_tensor_slices(\n row).map(lambda x: control_map_fn(x, num))\n return self.getNext(dataset)\n\n row = np.arange(6)\n for num in [2, 3, 4]:\n get_next = build_dataset(row, num)\n for i in range(6):\n self.assertEqual(\n (i // 2 if i % 2 else i * 2) if (num == 2 or num == 3) else i * 2,\n self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testCaseInWhileInMap(self):\n\n def control_map_fn(x, y):\n\n def multiply():\n return x * 2\n\n def divide():\n return x // 2\n\n pred_fn_pairs = {\n math_ops.logical_or(math_ops.equal(y, 2), math_ops.equal(y, 3)):\n divide,\n }\n\n return control_flow_ops.case(\n pred_fn_pairs, default=multiply, exclusive=True)\n\n def build_dataset(row, num):\n # pylint: disable=g-long-lambda\n dataset = dataset_ops.Dataset.from_tensors(\n row).map(lambda elems: map_fn.map_fn(\n lambda x: control_map_fn(x, num), elems))\n return self.getNext(dataset)\n\n row = np.arange(6)\n for num in [2, 3, 4]:\n get_next = build_dataset(row, num)\n self.assertAllEqual(\n [x // 2 if (num == 2 or num == 3) else x * 2 for x in row],\n self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testCaseAndCondInWhileInMap(self):\n\n def control_map_fn(x, y):\n\n def multiply():\n return x * 2\n\n def divide():\n return x // 2\n\n def defaults_two():\n return control_flow_ops.cond(\n math_ops.equal(math_ops.mod(x, 2), 0),\n multiply,\n divide,\n name=\"cond_mult\")\n\n pred_fn_pairs = {\n math_ops.logical_or(math_ops.equal(y, 2), math_ops.equal(y, 3)):\n defaults_two,\n }\n\n return control_flow_ops.case(\n pred_fn_pairs, default=multiply, exclusive=True)\n\n row = np.arange(6)\n num = 2\n # pylint: disable=g-long-lambda\n dataset = dataset_ops.Dataset.from_tensors(\n row).map(lambda elems: map_fn.map_fn(\n lambda x: control_map_fn(x, num), elems))\n # pylint: enable=g-long-lambda\n get_next = self.getNext(dataset)\n\n self.assertAllEqual([(x // 2 if x % 2 else x * 2) if\n (num == 2 or num == 3) else x * 2 for x in row],\n self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testNestedListMapDataset(self):\n dataset = dataset_ops.Dataset.from_tensors(\n [0, 1, 2]).repeat(10).map(lambda a: ([a[1], a[0] + a[2]], a[1]))\n\n expected_output = [(np.array([1, 2]), 1)] * 10\n self.assertDatasetProduces(dataset, expected_output=expected_output)\n\n def testPrefetch(self):\n # We will use this event to test that `_map_py_func()` has been\n # invoked a certain number of times (6 times, to be exact) after\n # consuming fewer elements from the iterator.\n ev = threading.Event()\n\n set_event_during_invocation = 5\n\n def _map_py_func(x):\n if x == set_event_during_invocation:\n ev.set()\n return x * x\n\n def _map_fn(x):\n return script_ops.py_func(_map_py_func, [x], x.dtype)\n\n def do_test(buffer_size):\n dataset = dataset_ops.Dataset.range(100).map(_map_fn).prefetch(\n buffer_size)\n\n get_next = self.getNext(dataset)\n # Simple test that prefetch yields the expected values in the\n # expected order.\n for i in range(100):\n self.assertEqual(i * i, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n for buffer_size in [1, 10, 100, 1000]:\n do_test(buffer_size)\n\n # We can indirectly observe that varying the buffer size has the\n # intended effect by observing when `ev` is set (on the 6th\n # invocation of `_map_py_func()`).\n # NOTE(mrry): We do not test with `buffer_size ==\n # set_event_during_invocation`, because we must consume at least\n # one element to start the prefetching.\n def do_test_ev(buffer_size):\n dataset = dataset_ops.Dataset.range(100).map(_map_fn).prefetch(\n buffer_size)\n\n get_next = self.getNext(dataset)\n\n event_will_be_set_after_consuming = (\n set_event_during_invocation - buffer_size + 1)\n\n ev.clear()\n for i in range(event_will_be_set_after_consuming):\n self.assertFalse(ev.is_set())\n self.assertEqual(i * i, self.evaluate(get_next()))\n ev.wait()\n for i in range(event_will_be_set_after_consuming, 100):\n self.assertEqual(i * i, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n for buffer_size in range(1, set_event_during_invocation):\n do_test_ev(buffer_size)\n\n def testReturnList(self):\n dataset = dataset_ops.Dataset.range(\n 10).map(lambda x: [x, constant_op.constant(37.0)])\n self.assertDatasetProduces(\n dataset, expected_output=[(i, 37.0) for i in range(10)])\n\n def testMultiOutputPyFunc(self):\n # The `tf.py_func()` op returns a list of tensors for its outputs.\n def _map_fn(x_tensor):\n def _map_py_func(x):\n return x, np.array(37.0, dtype=np.float64)\n return script_ops.py_func(\n _map_py_func, [x_tensor], [dtypes.int64, dtypes.float64])\n\n dataset = dataset_ops.Dataset.range(10).map(_map_fn)\n self.assertDatasetProduces(\n dataset, expected_output=[(i, 37.0) for i in range(10)])\n\n def testSparse(self):\n\n def _sparse(i):\n return sparse_tensor.SparseTensorValue(\n indices=np.array([[0, 0]]),\n values=(i * np.array([1])),\n dense_shape=np.array([1, 1]))\n\n dataset = dataset_ops.Dataset.range(10).map(_sparse)\n self.assertDatasetProduces(\n dataset, expected_output=[_sparse(i) for i in range(10)])\n\n def testSparseChain(self):\n\n def _sparse(i):\n return sparse_tensor.SparseTensorValue(\n indices=np.array([[0, 0]]),\n values=(i * np.array([1])),\n dense_shape=np.array([1, 1]))\n\n def _check(i):\n self.assertTrue(sparse_tensor.is_sparse(i))\n return sparse_ops.sparse_concat(0, [i, i])\n\n dataset = dataset_ops.Dataset.range(10).map(_sparse).map(_check)\n\n self.assertDatasetProduces(\n dataset,\n expected_output=[self.evaluate(_check(_sparse(i))) for i in range(10)])\n\n @test_util.run_v1_only(\"b/123904513\")\n def testParallelMapOutOfRangeError(self):\n def raising_py_func(i):\n if i == 100:\n raise StopIteration()\n else:\n return i\n\n dataset = dataset_ops.Dataset.range(105).map(\n lambda x: script_ops.py_func(raising_py_func, [x], dtypes.int64),\n num_parallel_calls=2)\n get_next = self.getNext(dataset)\n for i in range(100):\n self.assertEqual(i, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testConstantOutput(self):\n dataset = dataset_ops.Dataset.range(10).map(lambda x: [x, \"hello\", 10])\n self.assertDatasetProduces(dataset, [(i, b\"hello\", 10) for i in range(10)])\n\n def testWarnOnLookupTable(self):\n def collecting_function(x):\n _ = lookup_ops.HashTable(\n lookup_ops.KeyValueTensorInitializer([], []), 0.0, name=\"t1\")\n return x\n\n warnings.simplefilter(\"always\")\n with warnings.catch_warnings(record=True) as w:\n _ = dataset_ops.Dataset.range(10).map(collecting_function)\n # NOTE(mrry): Python 3 prints other warnings in addition to the one we are\n # testing, so we search for the expected warning.\n self.assertGreaterEqual(len(w), 1)\n found_warning = False\n for warning in w:\n if (\"Creating lookup tables inside a function passed to Dataset.map() is \"\n \"not supported.\" in str(warning)):\n found_warning = True\n break\n self.assertTrue(found_warning)\n\n def testNestedDatasetMap(self):\n # TODO(b/110122868): When iterators can yield a `tf.data.Dataset`, remove\n # the `get_single_element()` call.\n dataset = dataset_ops.Dataset.from_tensors([1.0, 2.0, 3.0]).map(\n dataset_ops.Dataset.from_tensor_slices).map(\n lambda ds: ds.batch(3)).flat_map(lambda x: x)\n\n self.assertDatasetProduces(dataset, expected_output=[[1.0, 2.0, 3.0]])\n\n def testReturnValueError(self):\n dataset = dataset_ops.Dataset.from_tensors([1.0, 2.0, 3.0])\n with self.assertRaisesRegexp(\n TypeError, r\"Unsupported return value from function passed to \"\n r\"Dataset.map\\(\\): None.\"):\n _ = dataset.map(lambda x: None)\n\n def testBrokenFunctionErrorOnInitialization(self):\n dataset = dataset_ops.Dataset.from_tensor_slices([1.0, 2.0, 3.0])\n\n def broken_function(_):\n \"\"\"A function deliberately designed to fail on instantiation.\"\"\"\n value = []\n tensor_value = attr_value_pb2.AttrValue()\n tensor_value.tensor.CopyFrom(\n tensor_util.make_tensor_proto(\n value, dtype=dtypes.float32, shape=[0], verify_shape=False))\n dtype_value = attr_value_pb2.AttrValue(type=dtypes.int32.as_datatype_enum)\n\n # Create a \"Const\" op with a `tf.float32` value and a `tf.int32` type\n # attr.\n const_tensor = ops.get_default_graph().create_op(\n \"Const\", [], [dtypes.int32],\n attrs={\n \"value\": tensor_value,\n \"dtype\": dtype_value\n },\n name=\"BrokenConst\").outputs[0]\n return const_tensor\n\n dataset = dataset.map(broken_function)\n self.assertDatasetProduces(\n dataset, expected_error=(errors.InvalidArgumentError, \"BrokenConst\"))\n\n# pylint: disable=g-long-lambda\n @parameterized.named_parameters(\n (\"Map\", lambda dataset, func:\n dataset_ops.MapDataset(dataset, func, use_inter_op_parallelism=False)),\n (\"ParallelMap\", lambda dataset, func:\n dataset_ops.ParallelMapDataset(dataset, func, num_parallel_calls=1,\n use_inter_op_parallelism=False)),\n )\n def testNoInterOpParallelism(self, make_dataset_fn):\n dataset = dataset_ops.Dataset.from_tensors(0)\n\n def _get_tid():\n return np.int64(threading.current_thread().ident)\n\n def _map_fn(_):\n tids = []\n for _ in range(10):\n tids.append(script_ops.py_func(_get_tid, [], dtypes.int64))\n return tids\n\n dataset = make_dataset_fn(dataset, _map_fn)\n get_next = self.getNext(dataset)\n\n tids = self.evaluate(get_next())\n self.assertTrue(all(tids[0] == tid for tid in tids))\n# pylint: enable=g-long-lambda\n\n @parameterized.named_parameters(\n (\"SequentialIdentity\", None, lambda x: x, None),\n (\"SequentialReplicate\", None, lambda x: (x, x), None),\n (\"SequentialSwap\", (None, None), lambda x, y: (y, x), None),\n (\"SequentialProject\", (None, None), lambda x, y: x, None),\n (\"ParallelIdentity\", None, lambda x: x, 10),\n (\"ParallelReplicate\", None, lambda x: (x, x), 10),\n (\"ParallelSwap\", (None, None), lambda x, y: (y, x), 10),\n (\"ParallelProject\", (None, None), lambda x, y: x, 10),\n )\n def testShortCircuit(self, structure, map_fn, num_parallel_calls):\n dataset = self.structuredDataset(structure).repeat().map(\n map_fn, num_parallel_calls=num_parallel_calls)\n get_next = self.getNext(dataset)\n\n if isinstance(structure, tuple):\n expected = map_fn(*self.evaluate(self.structuredElement(structure)))\n else:\n expected = map_fn(self.evaluate(self.structuredElement(structure)))\n self.assertEqual(expected, self.evaluate(get_next()))\n\n @parameterized.named_parameters(\n (\"Sequential\", None),\n (\"Parallel\", 10),\n )\n def testShortCircuitCapturedInput(self, num_parallel_calls):\n captured_t = variables.Variable(42)\n dataset = self.structuredDataset(None).repeat().map(\n lambda x: captured_t, num_parallel_calls=num_parallel_calls)\n self.evaluate(variables.global_variables_initializer())\n get_next = self.getNext(dataset, requires_initialization=True)\n\n self.assertEqual(42, self.evaluate(get_next()))\n\n @parameterized.named_parameters(\n (\"1\", 1, 1),\n (\"2\", 10, 1),\n (\"3\", 10, 10),\n (\"4\", 100, 1),\n (\"5\", 100, 10),\n (\"6\", 100, 100),\n )\n def testSloppyInterleaveInOrder(self, num_elements, num_parallel_calls):\n dataset, coordination_events = _make_coordinated_sloppy_dataset(\n num_elements, num_parallel_calls)\n options = dataset_ops.Options()\n options.experimental_threading = threading_options.ThreadingOptions()\n options.experimental_threading.private_threadpool_size = (\n num_parallel_calls + 1)\n dataset = dataset.with_options(options)\n get_next = self.getNext(dataset, requires_initialization=True)\n for i in range(num_elements):\n coordination_events[i].set()\n self.assertEqual(i * i, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n @parameterized.named_parameters(\n (\"1\", 10, 10),\n (\"2\", 100, 10),\n (\"3\", 100, 100),\n )\n def testSloppyInterleaveOutOfOrder(self, num_elements, num_parallel_calls):\n dataset, coordination_events = _make_coordinated_sloppy_dataset(\n num_elements, num_parallel_calls)\n options = dataset_ops.Options()\n options.experimental_threading = threading_options.ThreadingOptions()\n options.experimental_threading.private_threadpool_size = (\n num_parallel_calls + 1)\n dataset = dataset.with_options(options)\n\n get_next = self.getNext(dataset, requires_initialization=True)\n\n elements = [x for x in range(num_elements)]\n for i in [1, 4, 7]:\n elements[i], elements[i + 1] = elements[i + 1], elements[i]\n\n for element in elements:\n coordination_events[element].set()\n self.assertEqual(element * element, self.evaluate(get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n @parameterized.named_parameters(\n (\"Map\", None),\n (\"ParallelMap\", 12),\n )\n def testPreserveCardinality(self, num_parallel_calls):\n\n def py_fn(_):\n raise StopIteration()\n\n dataset = dataset_ops.DatasetV2.from_tensors(0).map(\n lambda x: script_ops.py_func(py_fn, [x], dtypes.int64),\n num_parallel_calls=num_parallel_calls)\n get_next = self.getNext(dataset)\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(get_next())\n\n\nif __name__ == \"__main__\":\n test.main()\n"
]
[
"from __future__ import division, print_function\n\nimport imp\nimport os\nimport sys\nimport shutil\nimport pickle\nimport copy\nimport warnings\nimport re\nfrom os.path import join\nfrom numpy.distutils import log\nfrom distutils.dep_util import newer\nfrom distutils.sysconfig import get_config_var\n\nfrom setup_common import *\n\n# Set to True to enable multiple file compilations (experimental)\nENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', \"1\") != \"0\")\n# Set to True to enable relaxed strides checking. This (mostly) means\n# that `strides[dim]` is ignored if `shape[dim] == 1` when setting flags.\nNPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', \"0\") != \"0\")\n\n# XXX: ugly, we use a class to avoid calling twice some expensive functions in\n# config.h/numpyconfig.h. I don't see a better way because distutils force\n# config.h generation inside an Extension class, and as such sharing\n# configuration informations between extensions is not easy.\n# Using a pickled-based memoize does not work because config_cmd is an instance\n# method, which cPickle does not like.\n#\n# Use pickle in all cases, as cPickle is gone in python3 and the difference\n# in time is only in build. -- Charles Harris, 2013-03-30\n\nclass CallOnceOnly(object):\n def __init__(self):\n self._check_types = None\n self._check_ieee_macros = None\n self._check_complex = None\n\n def check_types(self, *a, **kw):\n if self._check_types is None:\n out = check_types(*a, **kw)\n self._check_types = pickle.dumps(out)\n else:\n out = copy.deepcopy(pickle.loads(self._check_types))\n return out\n\n def check_ieee_macros(self, *a, **kw):\n if self._check_ieee_macros is None:\n out = check_ieee_macros(*a, **kw)\n self._check_ieee_macros = pickle.dumps(out)\n else:\n out = copy.deepcopy(pickle.loads(self._check_ieee_macros))\n return out\n\n def check_complex(self, *a, **kw):\n if self._check_complex is None:\n out = check_complex(*a, **kw)\n self._check_complex = pickle.dumps(out)\n else:\n out = copy.deepcopy(pickle.loads(self._check_complex))\n return out\n\nPYTHON_HAS_UNICODE_WIDE = True\n\ndef pythonlib_dir():\n \"\"\"return path where libpython* is.\"\"\"\n if sys.platform == 'win32':\n return os.path.join(sys.prefix, \"libs\")\n else:\n return get_config_var('LIBDIR')\n\ndef is_npy_no_signal():\n \"\"\"Return True if the NPY_NO_SIGNAL symbol must be defined in configuration\n header.\"\"\"\n return sys.platform == 'win32'\n\ndef is_npy_no_smp():\n \"\"\"Return True if the NPY_NO_SMP symbol must be defined in public\n header (when SMP support cannot be reliably enabled).\"\"\"\n # Python 2.3 causes a segfault when\n # trying to re-acquire the thread-state\n # which is done in error-handling\n # ufunc code. NPY_ALLOW_C_API and friends\n # cause the segfault. So, we disable threading\n # for now.\n if sys.version[:5] < '2.4.2':\n nosmp = 1\n else:\n # Perhaps a fancier check is in order here.\n # so that threads are only enabled if there\n # are actually multiple CPUS? -- but\n # threaded code can be nice even on a single\n # CPU so that long-calculating code doesn't\n # block.\n try:\n nosmp = os.environ['NPY_NOSMP']\n nosmp = 1\n except KeyError:\n nosmp = 0\n return nosmp == 1\n\ndef win32_checks(deflist):\n from numpy.distutils.misc_util import get_build_architecture\n a = get_build_architecture()\n\n # Distutils hack on AMD64 on windows\n print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' %\n (a, os.name, sys.platform))\n if a == 'AMD64':\n deflist.append('DISTUTILS_USE_SDK')\n\n # On win32, force long double format string to be 'g', not\n # 'Lg', since the MS runtime does not support long double whose\n # size is > sizeof(double)\n if a == \"Intel\" or a == \"AMD64\":\n deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING')\n\ndef check_math_capabilities(config, moredefs, mathlibs):\n def check_func(func_name):\n return config.check_func(func_name, libraries=mathlibs,\n decl=True, call=True)\n\n def check_funcs_once(funcs_name):\n decl = dict([(f, True) for f in funcs_name])\n st = config.check_funcs_once(funcs_name, libraries=mathlibs,\n decl=decl, call=decl)\n if st:\n moredefs.extend([(fname2def(f), 1) for f in funcs_name])\n return st\n\n def check_funcs(funcs_name):\n # Use check_funcs_once first, and if it does not work, test func per\n # func. Return success only if all the functions are available\n if not check_funcs_once(funcs_name):\n # Global check failed, check func per func\n for f in funcs_name:\n if check_func(f):\n moredefs.append((fname2def(f), 1))\n return 0\n else:\n return 1\n\n #use_msvc = config.check_decl(\"_MSC_VER\")\n\n if not check_funcs_once(MANDATORY_FUNCS):\n raise SystemError(\"One of the required function to build numpy is not\"\n \" available (the list is %s).\" % str(MANDATORY_FUNCS))\n\n # Standard functions which may not be available and for which we have a\n # replacement implementation. Note that some of these are C99 functions.\n\n # XXX: hack to circumvent cpp pollution from python: python put its\n # config.h in the public namespace, so we have a clash for the common\n # functions we test. We remove every function tested by python's\n # autoconf, hoping their own test are correct\n for f in OPTIONAL_STDFUNCS_MAYBE:\n if config.check_decl(fname2def(f),\n headers=[\"Python.h\", \"math.h\"]):\n OPTIONAL_STDFUNCS.remove(f)\n\n check_funcs(OPTIONAL_STDFUNCS)\n\n for h in OPTIONAL_HEADERS:\n if config.check_func(\"\", decl=False, call=False, headers=[h]):\n moredefs.append((fname2def(h).replace(\".\", \"_\"), 1))\n\n for tup in OPTIONAL_INTRINSICS:\n headers = None\n if len(tup) == 2:\n f, args = tup\n else:\n f, args, headers = tup[0], tup[1], [tup[2]]\n if config.check_func(f, decl=False, call=True, call_args=args,\n headers=headers):\n moredefs.append((fname2def(f), 1))\n\n for dec, fn in OPTIONAL_FUNCTION_ATTRIBUTES:\n if config.check_func(fn, decl='int %s %s(void *);' % (dec, fn),\n call=False):\n moredefs.append((fname2def(fn), 1))\n\n for fn in OPTIONAL_VARIABLE_ATTRIBUTES:\n if config.check_func(fn, decl='int %s a;' % (fn), call=False):\n m = fn.replace(\"(\", \"_\").replace(\")\", \"_\")\n moredefs.append((fname2def(m), 1))\n\n # C99 functions: float and long double versions\n check_funcs(C99_FUNCS_SINGLE)\n check_funcs(C99_FUNCS_EXTENDED)\n\ndef check_complex(config, mathlibs):\n priv = []\n pub = []\n\n try:\n if os.uname()[0] == \"Interix\":\n warnings.warn(\"Disabling broken complex support. See #1365\")\n return priv, pub\n except:\n # os.uname not available on all platforms. blanket except ugly but safe\n pass\n\n # Check for complex support\n st = config.check_header('complex.h')\n if st:\n priv.append(('HAVE_COMPLEX_H', 1))\n pub.append(('NPY_USE_C99_COMPLEX', 1))\n\n for t in C99_COMPLEX_TYPES:\n st = config.check_type(t, headers=[\"complex.h\"])\n if st:\n pub.append(('NPY_HAVE_%s' % type2def(t), 1))\n\n def check_prec(prec):\n flist = [f + prec for f in C99_COMPLEX_FUNCS]\n decl = dict([(f, True) for f in flist])\n if not config.check_funcs_once(flist, call=decl, decl=decl,\n libraries=mathlibs):\n for f in flist:\n if config.check_func(f, call=True, decl=True,\n libraries=mathlibs):\n priv.append((fname2def(f), 1))\n else:\n priv.extend([(fname2def(f), 1) for f in flist])\n\n check_prec('')\n check_prec('f')\n check_prec('l')\n\n return priv, pub\n\ndef check_ieee_macros(config):\n priv = []\n pub = []\n\n macros = []\n\n def _add_decl(f):\n priv.append(fname2def(\"decl_%s\" % f))\n pub.append('NPY_%s' % fname2def(\"decl_%s\" % f))\n\n # XXX: hack to circumvent cpp pollution from python: python put its\n # config.h in the public namespace, so we have a clash for the common\n # functions we test. We remove every function tested by python's\n # autoconf, hoping their own test are correct\n _macros = [\"isnan\", \"isinf\", \"signbit\", \"isfinite\"]\n for f in _macros:\n py_symbol = fname2def(\"decl_%s\" % f)\n already_declared = config.check_decl(py_symbol,\n headers=[\"Python.h\", \"math.h\"])\n if already_declared:\n if config.check_macro_true(py_symbol,\n headers=[\"Python.h\", \"math.h\"]):\n pub.append('NPY_%s' % fname2def(\"decl_%s\" % f))\n else:\n macros.append(f)\n # Normally, isnan and isinf are macro (C99), but some platforms only have\n # func, or both func and macro version. Check for macro only, and define\n # replacement ones if not found.\n # Note: including Python.h is necessary because it modifies some math.h\n # definitions\n for f in macros:\n st = config.check_decl(f, headers = [\"Python.h\", \"math.h\"])\n if st:\n _add_decl(f)\n\n return priv, pub\n\ndef check_types(config_cmd, ext, build_dir):\n private_defines = []\n public_defines = []\n\n # Expected size (in number of bytes) for each type. This is an\n # optimization: those are only hints, and an exhaustive search for the size\n # is done if the hints are wrong.\n expected = {}\n expected['short'] = [2]\n expected['int'] = [4]\n expected['long'] = [8, 4]\n expected['float'] = [4]\n expected['double'] = [8]\n expected['long double'] = [8, 12, 16]\n expected['Py_intptr_t'] = [4, 8]\n expected['PY_LONG_LONG'] = [8]\n expected['long long'] = [8]\n expected['off_t'] = [4, 8]\n\n # Check we have the python header (-dev* packages on Linux)\n result = config_cmd.check_header('Python.h')\n if not result:\n raise SystemError(\n \"Cannot compile 'Python.h'. Perhaps you need to \"\\\n \"install python-dev|python-devel.\")\n res = config_cmd.check_header(\"endian.h\")\n if res:\n private_defines.append(('HAVE_ENDIAN_H', 1))\n public_defines.append(('NPY_HAVE_ENDIAN_H', 1))\n\n # Check basic types sizes\n for type in ('short', 'int', 'long'):\n res = config_cmd.check_decl(\"SIZEOF_%s\" % sym2def(type), headers = [\"Python.h\"])\n if res:\n public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), \"SIZEOF_%s\" % sym2def(type)))\n else:\n res = config_cmd.check_type_size(type, expected=expected[type])\n if res >= 0:\n public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))\n else:\n raise SystemError(\"Checking sizeof (%s) failed !\" % type)\n\n for type in ('float', 'double', 'long double'):\n already_declared = config_cmd.check_decl(\"SIZEOF_%s\" % sym2def(type),\n headers = [\"Python.h\"])\n res = config_cmd.check_type_size(type, expected=expected[type])\n if res >= 0:\n public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))\n if not already_declared and not type == 'long double':\n private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))\n else:\n raise SystemError(\"Checking sizeof (%s) failed !\" % type)\n\n # Compute size of corresponding complex type: used to check that our\n # definition is binary compatible with C99 complex type (check done at\n # build time in npy_common.h)\n complex_def = \"struct {%s __x; %s __y;}\" % (type, type)\n res = config_cmd.check_type_size(complex_def, expected=2*expected[type])\n if res >= 0:\n public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res))\n else:\n raise SystemError(\"Checking sizeof (%s) failed !\" % complex_def)\n\n\n for type in ('Py_intptr_t', 'off_t'):\n res = config_cmd.check_type_size(type, headers=[\"Python.h\"],\n library_dirs=[pythonlib_dir()],\n expected=expected[type])\n\n if res >= 0:\n private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))\n public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))\n else:\n raise SystemError(\"Checking sizeof (%s) failed !\" % type)\n\n # We check declaration AND type because that's how distutils does it.\n if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']):\n res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'],\n library_dirs=[pythonlib_dir()],\n expected=expected['PY_LONG_LONG'])\n if res >= 0:\n private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))\n public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))\n else:\n raise SystemError(\"Checking sizeof (%s) failed !\" % 'PY_LONG_LONG')\n\n res = config_cmd.check_type_size('long long',\n expected=expected['long long'])\n if res >= 0:\n #private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res))\n public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res))\n else:\n raise SystemError(\"Checking sizeof (%s) failed !\" % 'long long')\n\n if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']):\n raise RuntimeError(\n \"Config wo CHAR_BIT is not supported\"\\\n \", please contact the maintainers\")\n\n return private_defines, public_defines\n\ndef check_mathlib(config_cmd):\n # Testing the C math library\n mathlibs = []\n mathlibs_choices = [[], ['m'], ['cpml']]\n mathlib = os.environ.get('MATHLIB')\n if mathlib:\n mathlibs_choices.insert(0, mathlib.split(','))\n for libs in mathlibs_choices:\n if config_cmd.check_func(\"exp\", libraries=libs, decl=True, call=True):\n mathlibs = libs\n break\n else:\n raise EnvironmentError(\"math library missing; rerun \"\n \"setup.py after setting the \"\n \"MATHLIB env variable\")\n return mathlibs\n\ndef visibility_define(config):\n \"\"\"Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty\n string).\"\"\"\n if config.check_compiler_gcc4():\n return '__attribute__((visibility(\"hidden\")))'\n else:\n return ''\n\ndef configuration(parent_package='',top_path=None):\n from numpy.distutils.misc_util import Configuration, dot_join\n from numpy.distutils.system_info import get_info, default_lib_dirs\n\n config = Configuration('core', parent_package, top_path)\n local_dir = config.local_path\n codegen_dir = join(local_dir, 'code_generators')\n\n if is_released(config):\n warnings.simplefilter('error', MismatchCAPIWarning)\n\n # Check whether we have a mismatch between the set C API VERSION and the\n # actual C API VERSION\n check_api_version(C_API_VERSION, codegen_dir)\n\n generate_umath_py = join(codegen_dir, 'generate_umath.py')\n n = dot_join(config.name, 'generate_umath')\n generate_umath = imp.load_module('_'.join(n.split('.')),\n open(generate_umath_py, 'U'), generate_umath_py,\n ('.py', 'U', 1))\n\n header_dir = 'include/numpy' # this is relative to config.path_in_package\n\n cocache = CallOnceOnly()\n\n def generate_config_h(ext, build_dir):\n target = join(build_dir, header_dir, 'config.h')\n d = os.path.dirname(target)\n if not os.path.exists(d):\n os.makedirs(d)\n\n if newer(__file__, target):\n config_cmd = config.get_config_cmd()\n log.info('Generating %s', target)\n\n # Check sizeof\n moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir)\n\n # Check math library and C99 math funcs availability\n mathlibs = check_mathlib(config_cmd)\n moredefs.append(('MATHLIB', ','.join(mathlibs)))\n\n check_math_capabilities(config_cmd, moredefs, mathlibs)\n moredefs.extend(cocache.check_ieee_macros(config_cmd)[0])\n moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0])\n\n # Signal check\n if is_npy_no_signal():\n moredefs.append('__NPY_PRIVATE_NO_SIGNAL')\n\n # Windows checks\n if sys.platform=='win32' or os.name=='nt':\n win32_checks(moredefs)\n\n # Inline check\n inline = config_cmd.check_inline()\n\n # Check whether we need our own wide character support\n if not config_cmd.check_decl('Py_UNICODE_WIDE', headers=['Python.h']):\n PYTHON_HAS_UNICODE_WIDE = True\n else:\n PYTHON_HAS_UNICODE_WIDE = False\n\n if ENABLE_SEPARATE_COMPILATION:\n moredefs.append(('ENABLE_SEPARATE_COMPILATION', 1))\n\n if NPY_RELAXED_STRIDES_CHECKING:\n moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))\n\n # Get long double representation\n if sys.platform != 'darwin':\n rep = check_long_double_representation(config_cmd)\n if rep in ['INTEL_EXTENDED_12_BYTES_LE',\n 'INTEL_EXTENDED_16_BYTES_LE',\n 'MOTOROLA_EXTENDED_12_BYTES_BE',\n 'IEEE_QUAD_LE', 'IEEE_QUAD_BE',\n 'IEEE_DOUBLE_LE', 'IEEE_DOUBLE_BE',\n 'DOUBLE_DOUBLE_BE', 'DOUBLE_DOUBLE_LE']:\n moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1))\n else:\n raise ValueError(\"Unrecognized long double format: %s\" % rep)\n\n # Py3K check\n if sys.version_info[0] == 3:\n moredefs.append(('NPY_PY3K', 1))\n\n # Generate the config.h file from moredefs\n target_f = open(target, 'w')\n for d in moredefs:\n if isinstance(d, str):\n target_f.write('#define %s\\n' % (d))\n else:\n target_f.write('#define %s %s\\n' % (d[0], d[1]))\n\n # define inline to our keyword, or nothing\n target_f.write('#ifndef __cplusplus\\n')\n if inline == 'inline':\n target_f.write('/* #undef inline */\\n')\n else:\n target_f.write('#define inline %s\\n' % inline)\n target_f.write('#endif\\n')\n\n # add the guard to make sure config.h is never included directly,\n # but always through npy_config.h\n target_f.write(\"\"\"\n#ifndef _NPY_NPY_CONFIG_H_\n#error config.h should never be included directly, include npy_config.h instead\n#endif\n\"\"\")\n\n target_f.close()\n print('File:', target)\n target_f = open(target)\n print(target_f.read())\n target_f.close()\n print('EOF')\n else:\n mathlibs = []\n target_f = open(target)\n for line in target_f:\n s = '#define MATHLIB'\n if line.startswith(s):\n value = line[len(s):].strip()\n if value:\n mathlibs.extend(value.split(','))\n target_f.close()\n\n # Ugly: this can be called within a library and not an extension,\n # in which case there is no libraries attributes (and none is\n # needed).\n if hasattr(ext, 'libraries'):\n ext.libraries.extend(mathlibs)\n\n incl_dir = os.path.dirname(target)\n if incl_dir not in config.numpy_include_dirs:\n config.numpy_include_dirs.append(incl_dir)\n\n return target\n\n def generate_numpyconfig_h(ext, build_dir):\n \"\"\"Depends on config.h: generate_config_h has to be called before !\"\"\"\n # put private include directory in build_dir on search path\n # allows using code generation in headers headers\n config.add_include_dirs(join(build_dir, \"src\", \"private\"))\n\n target = join(build_dir, header_dir, '_numpyconfig.h')\n d = os.path.dirname(target)\n if not os.path.exists(d):\n os.makedirs(d)\n if newer(__file__, target):\n config_cmd = config.get_config_cmd()\n log.info('Generating %s', target)\n\n # Check sizeof\n ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir)\n\n if is_npy_no_signal():\n moredefs.append(('NPY_NO_SIGNAL', 1))\n\n if is_npy_no_smp():\n moredefs.append(('NPY_NO_SMP', 1))\n else:\n moredefs.append(('NPY_NO_SMP', 0))\n\n mathlibs = check_mathlib(config_cmd)\n moredefs.extend(cocache.check_ieee_macros(config_cmd)[1])\n moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1])\n\n if ENABLE_SEPARATE_COMPILATION:\n moredefs.append(('NPY_ENABLE_SEPARATE_COMPILATION', 1))\n\n if NPY_RELAXED_STRIDES_CHECKING:\n moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))\n\n # Check wether we can use inttypes (C99) formats\n if config_cmd.check_decl('PRIdPTR', headers = ['inttypes.h']):\n moredefs.append(('NPY_USE_C99_FORMATS', 1))\n\n # visibility check\n hidden_visibility = visibility_define(config_cmd)\n moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility))\n\n # Add the C API/ABI versions\n moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION))\n moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION))\n\n # Add moredefs to header\n target_f = open(target, 'w')\n for d in moredefs:\n if isinstance(d, str):\n target_f.write('#define %s\\n' % (d))\n else:\n target_f.write('#define %s %s\\n' % (d[0], d[1]))\n\n # Define __STDC_FORMAT_MACROS\n target_f.write(\"\"\"\n#ifndef __STDC_FORMAT_MACROS\n#define __STDC_FORMAT_MACROS 1\n#endif\n\"\"\")\n target_f.close()\n\n # Dump the numpyconfig.h header to stdout\n print('File: %s' % target)\n target_f = open(target)\n print(target_f.read())\n target_f.close()\n print('EOF')\n config.add_data_files((header_dir, target))\n return target\n\n def generate_api_func(module_name):\n def generate_api(ext, build_dir):\n script = join(codegen_dir, module_name + '.py')\n sys.path.insert(0, codegen_dir)\n try:\n m = __import__(module_name)\n log.info('executing %s', script)\n h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir))\n finally:\n del sys.path[0]\n config.add_data_files((header_dir, h_file),\n (header_dir, doc_file))\n return (h_file,)\n return generate_api\n\n generate_numpy_api = generate_api_func('generate_numpy_api')\n generate_ufunc_api = generate_api_func('generate_ufunc_api')\n\n config.add_include_dirs(join(local_dir, \"src\", \"private\"))\n config.add_include_dirs(join(local_dir, \"src\"))\n config.add_include_dirs(join(local_dir))\n\n config.add_data_files('include/numpy/*.h')\n config.add_include_dirs(join('src', 'npymath'))\n config.add_include_dirs(join('src', 'multiarray'))\n config.add_include_dirs(join('src', 'umath'))\n config.add_include_dirs(join('src', 'npysort'))\n\n config.add_define_macros([(\"HAVE_NPY_CONFIG_H\", \"1\")])\n config.add_define_macros([(\"_FILE_OFFSET_BITS\", \"64\")])\n config.add_define_macros([('_LARGEFILE_SOURCE', '1')])\n config.add_define_macros([('_LARGEFILE64_SOURCE', '1')])\n\n config.numpy_include_dirs.extend(config.paths('include'))\n\n deps = [join('src', 'npymath', '_signbit.c'),\n join('include', 'numpy', '*object.h'),\n 'include/numpy/fenv/fenv.c',\n 'include/numpy/fenv/fenv.h',\n join(codegen_dir, 'genapi.py'),\n ]\n\n # Don't install fenv unless we need them.\n if sys.platform == 'cygwin':\n config.add_data_dir('include/numpy/fenv')\n\n #######################################################################\n # dummy module #\n #######################################################################\n\n # npymath needs the config.h and numpyconfig.h files to be generated, but\n # build_clib cannot handle generate_config_h and generate_numpyconfig_h\n # (don't ask). Because clib are generated before extensions, we have to\n # explicitly add an extension which has generate_config_h and\n # generate_numpyconfig_h as sources *before* adding npymath.\n\n config.add_extension('_dummy',\n sources = [join('src', 'dummymodule.c'),\n generate_config_h,\n generate_numpyconfig_h,\n generate_numpy_api]\n )\n\n #######################################################################\n # npymath library #\n #######################################################################\n\n subst_dict = dict([(\"sep\", os.path.sep), (\"pkgname\", \"numpy.core\")])\n def get_mathlib_info(*args):\n # Another ugly hack: the mathlib info is known once build_src is run,\n # but we cannot use add_installed_pkg_config here either, so we only\n # update the substition dictionary during npymath build\n config_cmd = config.get_config_cmd()\n\n # Check that the toolchain works, to fail early if it doesn't\n # (avoid late errors with MATHLIB which are confusing if the\n # compiler does not work).\n st = config_cmd.try_link('int main(void) { return 0;}')\n if not st:\n raise RuntimeError(\"Broken toolchain: cannot link a simple C program\")\n mlibs = check_mathlib(config_cmd)\n\n posix_mlib = ' '.join(['-l%s' % l for l in mlibs])\n msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs])\n subst_dict[\"posix_mathlib\"] = posix_mlib\n subst_dict[\"msvc_mathlib\"] = msvc_mlib\n\n npymath_sources = [join('src', 'npymath', 'npy_math.c.src'),\n join('src', 'npymath', 'ieee754.c.src'),\n join('src', 'npymath', 'npy_math_complex.c.src'),\n join('src', 'npymath', 'halffloat.c')]\n config.add_installed_library('npymath',\n sources=npymath_sources + [get_mathlib_info],\n install_dir='lib')\n config.add_npy_pkg_config(\"npymath.ini.in\", \"lib/npy-pkg-config\",\n subst_dict)\n config.add_npy_pkg_config(\"mlib.ini.in\", \"lib/npy-pkg-config\",\n subst_dict)\n\n #######################################################################\n # npysort library #\n #######################################################################\n\n # This library is created for the build but it is not installed\n npysort_sources=[join('src', 'npysort', 'quicksort.c.src'),\n join('src', 'npysort', 'mergesort.c.src'),\n join('src', 'npysort', 'heapsort.c.src'),\n join('src', 'private', 'npy_partition.h.src'),\n join('src', 'npysort', 'selection.c.src'),\n join('src', 'private', 'npy_binsearch.h.src'),\n join('src', 'npysort', 'binsearch.c.src'),\n ]\n config.add_library('npysort',\n sources=npysort_sources,\n include_dirs=[])\n\n\n #######################################################################\n # multiarray module #\n #######################################################################\n\n # Multiarray version: this function is needed to build foo.c from foo.c.src\n # when foo.c is included in another file and as such not in the src\n # argument of build_ext command\n def generate_multiarray_templated_sources(ext, build_dir):\n from numpy.distutils.misc_util import get_cmd\n\n subpath = join('src', 'multiarray')\n sources = [join(local_dir, subpath, 'scalartypes.c.src'),\n join(local_dir, subpath, 'arraytypes.c.src'),\n join(local_dir, subpath, 'nditer_templ.c.src'),\n join(local_dir, subpath, 'lowlevel_strided_loops.c.src'),\n join(local_dir, subpath, 'einsum.c.src')]\n\n # numpy.distutils generate .c from .c.src in weird directories, we have\n # to add them there as they depend on the build_dir\n config.add_include_dirs(join(build_dir, subpath))\n cmd = get_cmd('build_src')\n cmd.ensure_finalized()\n cmd.template_sources(sources, ext)\n\n multiarray_deps = [\n join('src', 'multiarray', 'arrayobject.h'),\n join('src', 'multiarray', 'arraytypes.h'),\n join('src', 'multiarray', 'array_assign.h'),\n join('src', 'multiarray', 'buffer.h'),\n join('src', 'multiarray', 'calculation.h'),\n join('src', 'multiarray', 'common.h'),\n join('src', 'multiarray', 'convert_datatype.h'),\n join('src', 'multiarray', 'convert.h'),\n join('src', 'multiarray', 'conversion_utils.h'),\n join('src', 'multiarray', 'ctors.h'),\n join('src', 'multiarray', 'descriptor.h'),\n join('src', 'multiarray', 'getset.h'),\n join('src', 'multiarray', 'hashdescr.h'),\n join('src', 'multiarray', 'iterators.h'),\n join('src', 'multiarray', 'mapping.h'),\n join('src', 'multiarray', 'methods.h'),\n join('src', 'multiarray', 'multiarraymodule.h'),\n join('src', 'multiarray', 'nditer_impl.h'),\n join('src', 'multiarray', 'numpymemoryview.h'),\n join('src', 'multiarray', 'number.h'),\n join('src', 'multiarray', 'numpyos.h'),\n join('src', 'multiarray', 'refcount.h'),\n join('src', 'multiarray', 'scalartypes.h'),\n join('src', 'multiarray', 'sequence.h'),\n join('src', 'multiarray', 'shape.h'),\n join('src', 'multiarray', 'ucsnarrow.h'),\n join('src', 'multiarray', 'usertypes.h'),\n join('src', 'private', 'lowlevel_strided_loops.h'),\n join('include', 'numpy', 'arrayobject.h'),\n join('include', 'numpy', '_neighborhood_iterator_imp.h'),\n join('include', 'numpy', 'npy_endian.h'),\n join('include', 'numpy', 'arrayscalars.h'),\n join('include', 'numpy', 'noprefix.h'),\n join('include', 'numpy', 'npy_interrupt.h'),\n join('include', 'numpy', 'npy_3kcompat.h'),\n join('include', 'numpy', 'npy_math.h'),\n join('include', 'numpy', 'halffloat.h'),\n join('include', 'numpy', 'npy_common.h'),\n join('include', 'numpy', 'npy_os.h'),\n join('include', 'numpy', 'utils.h'),\n join('include', 'numpy', 'ndarrayobject.h'),\n join('include', 'numpy', 'npy_cpu.h'),\n join('include', 'numpy', 'numpyconfig.h'),\n join('include', 'numpy', 'ndarraytypes.h'),\n join('include', 'numpy', 'npy_1_7_deprecated_api.h'),\n join('include', 'numpy', '_numpyconfig.h.in'),\n # add library sources as distuils does not consider libraries\n # dependencies\n ] + npysort_sources + npymath_sources\n\n multiarray_src = [\n join('src', 'multiarray', 'alloc.c'),\n join('src', 'multiarray', 'arrayobject.c'),\n join('src', 'multiarray', 'arraytypes.c.src'),\n join('src', 'multiarray', 'array_assign.c'),\n join('src', 'multiarray', 'array_assign_scalar.c'),\n join('src', 'multiarray', 'array_assign_array.c'),\n join('src', 'multiarray', 'buffer.c'),\n join('src', 'multiarray', 'calculation.c'),\n join('src', 'multiarray', 'common.c'),\n join('src', 'multiarray', 'convert.c'),\n join('src', 'multiarray', 'convert_datatype.c'),\n join('src', 'multiarray', 'conversion_utils.c'),\n join('src', 'multiarray', 'ctors.c'),\n join('src', 'multiarray', 'datetime.c'),\n join('src', 'multiarray', 'datetime_strings.c'),\n join('src', 'multiarray', 'datetime_busday.c'),\n join('src', 'multiarray', 'datetime_busdaycal.c'),\n join('src', 'multiarray', 'descriptor.c'),\n join('src', 'multiarray', 'dtype_transfer.c'),\n join('src', 'multiarray', 'einsum.c.src'),\n join('src', 'multiarray', 'flagsobject.c'),\n join('src', 'multiarray', 'getset.c'),\n join('src', 'multiarray', 'hashdescr.c'),\n join('src', 'multiarray', 'item_selection.c'),\n join('src', 'multiarray', 'iterators.c'),\n join('src', 'multiarray', 'lowlevel_strided_loops.c.src'),\n join('src', 'multiarray', 'mapping.c'),\n join('src', 'multiarray', 'methods.c'),\n join('src', 'multiarray', 'multiarraymodule.c'),\n join('src', 'multiarray', 'nditer_templ.c.src'),\n join('src', 'multiarray', 'nditer_api.c'),\n join('src', 'multiarray', 'nditer_constr.c'),\n join('src', 'multiarray', 'nditer_pywrap.c'),\n join('src', 'multiarray', 'number.c'),\n join('src', 'multiarray', 'numpymemoryview.c'),\n join('src', 'multiarray', 'numpyos.c'),\n join('src', 'multiarray', 'refcount.c'),\n join('src', 'multiarray', 'sequence.c'),\n join('src', 'multiarray', 'shape.c'),\n join('src', 'multiarray', 'scalarapi.c'),\n join('src', 'multiarray', 'scalartypes.c.src'),\n join('src', 'multiarray', 'usertypes.c'),\n join('src', 'multiarray', 'ucsnarrow.c')]\n\n\n if not ENABLE_SEPARATE_COMPILATION:\n multiarray_deps.extend(multiarray_src)\n multiarray_src = [join('src', 'multiarray', 'multiarraymodule_onefile.c')]\n multiarray_src.append(generate_multiarray_templated_sources)\n\n config.add_extension('multiarray',\n sources = multiarray_src +\n [generate_config_h,\n generate_numpyconfig_h,\n generate_numpy_api,\n join(codegen_dir, 'generate_numpy_api.py'),\n join('*.py')],\n depends = deps + multiarray_deps,\n libraries = ['npymath', 'npysort'])\n\n #######################################################################\n # umath module #\n #######################################################################\n\n # umath version: this function is needed to build foo.c from foo.c.src\n # when foo.c is included in another file and as such not in the src\n # argument of build_ext command\n def generate_umath_templated_sources(ext, build_dir):\n from numpy.distutils.misc_util import get_cmd\n\n subpath = join('src', 'umath')\n sources = [\n join(local_dir, subpath, 'loops.h.src'),\n join(local_dir, subpath, 'loops.c.src'),\n join(local_dir, subpath, 'simd.inc.src')]\n\n # numpy.distutils generate .c from .c.src in weird directories, we have\n # to add them there as they depend on the build_dir\n config.add_include_dirs(join(build_dir, subpath))\n cmd = get_cmd('build_src')\n cmd.ensure_finalized()\n cmd.template_sources(sources, ext)\n\n\n def generate_umath_c(ext, build_dir):\n target = join(build_dir, header_dir, '__umath_generated.c')\n dir = os.path.dirname(target)\n if not os.path.exists(dir):\n os.makedirs(dir)\n script = generate_umath_py\n if newer(script, target):\n f = open(target, 'w')\n f.write(generate_umath.make_code(generate_umath.defdict,\n generate_umath.__file__))\n f.close()\n return []\n\n umath_src = [\n join('src', 'umath', 'umathmodule.c'),\n join('src', 'umath', 'reduction.c'),\n join('src', 'umath', 'funcs.inc.src'),\n join('src', 'umath', 'simd.inc.src'),\n join('src', 'umath', 'loops.h.src'),\n join('src', 'umath', 'loops.c.src'),\n join('src', 'umath', 'ufunc_object.c'),\n join('src', 'umath', 'ufunc_type_resolution.c')]\n\n umath_deps = [\n generate_umath_py,\n join('src', 'multiarray', 'common.h'),\n join('src', 'umath', 'simd.inc.src'),\n join(codegen_dir, 'generate_ufunc_api.py'),\n join('src', 'private', 'ufunc_override.h')] + npymath_sources\n\n if not ENABLE_SEPARATE_COMPILATION:\n umath_deps.extend(umath_src)\n umath_src = [join('src', 'umath', 'umathmodule_onefile.c')]\n umath_src.append(generate_umath_templated_sources)\n umath_src.append(join('src', 'umath', 'funcs.inc.src'))\n umath_src.append(join('src', 'umath', 'simd.inc.src'))\n\n config.add_extension('umath',\n sources = umath_src +\n [generate_config_h,\n generate_numpyconfig_h,\n generate_umath_c,\n generate_ufunc_api],\n depends = deps + umath_deps,\n libraries = ['npymath'],\n )\n\n #######################################################################\n # scalarmath module #\n #######################################################################\n\n config.add_extension('scalarmath',\n sources = [join('src', 'scalarmathmodule.c.src'),\n join('src', 'private', 'scalarmathmodule.h.src'),\n generate_config_h,\n generate_numpyconfig_h,\n generate_numpy_api,\n generate_ufunc_api],\n depends = deps + npymath_sources,\n libraries = ['npymath'],\n )\n\n #######################################################################\n # _dotblas module #\n #######################################################################\n\n # Configure blasdot\n blas_info = get_info('blas_opt', 0)\n #blas_info = {}\n def get_dotblas_sources(ext, build_dir):\n if blas_info:\n if ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', []):\n return None # dotblas needs ATLAS, Fortran compiled blas will not be sufficient.\n return ext.depends[:2]\n return None # no extension module will be built\n\n config.add_extension('_dotblas',\n sources = [get_dotblas_sources],\n depends = [join('blasdot', '_dotblas.c'),\n join('blasdot', 'apple_sgemv_patch.c'),\n join('blasdot', 'cblas.h'),\n ],\n include_dirs = ['blasdot'],\n extra_info = blas_info\n )\n\n #######################################################################\n # umath_tests module #\n #######################################################################\n\n config.add_extension('umath_tests',\n sources = [join('src', 'umath', 'umath_tests.c.src')])\n\n #######################################################################\n # custom rational dtype module #\n #######################################################################\n\n config.add_extension('test_rational',\n sources = [join('src', 'umath', 'test_rational.c.src')])\n\n #######################################################################\n # struct_ufunc_test module #\n #######################################################################\n\n config.add_extension('struct_ufunc_test',\n sources = [join('src', 'umath', 'struct_ufunc_test.c.src')])\n\n #######################################################################\n # multiarray_tests module #\n #######################################################################\n\n config.add_extension('multiarray_tests',\n sources = [join('src', 'multiarray', 'multiarray_tests.c.src')])\n\n #######################################################################\n # operand_flag_tests module #\n #######################################################################\n\n config.add_extension('operand_flag_tests',\n sources = [join('src', 'umath', 'operand_flag_tests.c.src')])\n\n config.add_data_dir('tests')\n config.add_data_dir('tests/data')\n\n config.make_svn_version_py()\n\n return config\n\nif __name__=='__main__':\n from numpy.distutils.core import setup\n setup(configuration=configuration)\n"
]
[
"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n\nfrom typing import Tuple, Union\n\nfrom GPyOpt.util.general import get_quantiles\nimport numpy as np\n\nfrom ...core.interfaces import IModel, IDifferentiable, IPriorHyperparameters\nfrom ...core.acquisition import Acquisition\n\n\nclass ExpectedImprovement(Acquisition):\n\n def __init__(self, model: Union[IModel, IDifferentiable], jitter: float = float(0))-> None:\n \"\"\"\n This acquisition computes for a given input the improvement over the current best observed value in\n expectation. For more information see:\n\n Efficient Global Optimization of Expensive Black-Box Functions\n Jones, Donald R. and Schonlau, Matthias and Welch, William J.\n Journal of Global Optimization\n\n :param model: model that is used to compute the improvement.\n :param jitter: parameter to encourage extra exploration.\n \"\"\"\n\n self.model = model\n self.jitter = jitter\n\n def evaluate(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes the Expected Improvement.\n\n :param x: points where the acquisition is evaluated.\n \"\"\"\n\n mean, variance = self.model.predict(x)\n standard_deviation = np.sqrt(variance)\n\n y_minimum = np.min(self.model.Y, axis=0)\n\n pdf, cdf, u = get_quantiles(self.jitter, y_minimum, mean, standard_deviation)\n\n improvement = standard_deviation * (u * cdf + pdf)\n\n return improvement\n\n def evaluate_with_gradients(self, x: np.ndarray) -> Tuple:\n \"\"\"\n Computes the Expected Improvement and its derivative.\n\n :param x: locations where the evaluation with gradients is done.\n \"\"\"\n\n mean, variance = self.model.predict(x)\n standard_deviation = np.sqrt(variance)\n\n y_minimum = np.min(self.model.Y, axis=0)\n\n dmean_dx, dvariance_dx = self.model.get_prediction_gradients(x)\n dstandard_deviation_dx = dvariance_dx / (2 * standard_deviation)\n\n pdf, cdf, u = get_quantiles(self.jitter, y_minimum, mean, standard_deviation)\n\n improvement = standard_deviation * (u * cdf + pdf)\n dimprovement_dx = dstandard_deviation_dx * pdf - cdf * dmean_dx\n\n return improvement, dimprovement_dx\n\n @property\n def has_gradients(self) -> bool:\n \"\"\"Returns that this acquisition has gradients\"\"\"\n return isinstance(self.model, IDifferentiable)\n\n\n\nclass IntegratedExpectedImprovement(Acquisition):\n\n def __init__(self, model: Union[IModel, IDifferentiable, IPriorHyperparameters], jitter: float = float(0),\n n_samples = 10) -> None:\n \"\"\"\n This acquisition computes for a given input the improvement over the current best observed value in\n expectation. This function integrates over hyper-parameters the model by computing the average of the\n expected improvements for all samples. For more information see:\n\n Efficient Global Optimization of Expensive Black-Box Functions\n Jones, Donald R. and Schonlau, Matthias and Welch, William J.\n Journal of Global Optimization\n\n :param model: model that is used to compute the improvement.\n :param jitter: parameter to encourage extra exploration.\n \"\"\"\n\n self.model = model\n self.jitter = jitter\n self.n_samples = n_samples\n self.samples = self.model.generate_hyperparameters_samples(n_samples)\n\n def evaluate(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes the integrated Expected Improvement with respect to the hyper-parameters of the model. Averages the\n improvement for all the samples.\n\n :param x: points where the acquisition is evaluated.\n :return: numpy array with the integrated expected improvement at the points x.\n \"\"\"\n\n if x.ndim == 1: x = x[None, :]\n improvement = 0\n\n for sample in self.samples:\n self.model.fix_model_hyperparameters(sample)\n acquisition = ExpectedImprovement(self.model, self.jitter)\n improvement += acquisition.evaluate(x)\n\n return improvement/self.n_samples\n\n def evaluate_with_gradients(self, x: np.ndarray) -> Tuple:\n \"\"\"\n Computes the Expected Improvement and its derivative integrating over the hyper-parameters of the model\n\n :param x: locations where the evaluation with gradients is done.\n :return: tuple containing numpy arrays with the integrated expected improvement at the points x\n and its gradient.\n \"\"\"\n\n if x.ndim == 1: x = x[None, :]\n improvement = 0\n dimprovement_dx = 0\n\n for sample in self.samples:\n self.model.fix_model_hyperparameters(sample)\n acquisition = ExpectedImprovement(self.model, self.jitter)\n improvement_sample, dimprovement_dx_sample = acquisition.evaluate_with_gradients(x)\n improvement += improvement_sample\n dimprovement_dx += dimprovement_dx_sample\n\n return improvement/self.n_samples, dimprovement_dx/self.n_samples\n\n @property\n def has_gradients(self) -> bool:\n \"\"\"Returns that this acquisition has gradients\"\"\"\n return isinstance(self.model, IDifferentiable)"
]
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2019, 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Quantum Generator.\"\"\"\n\nfrom typing import Optional, List, Union, Dict, Any\nimport warnings\nfrom copy import deepcopy\nimport numpy as np\n\nfrom qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.aqua import aqua_globals\nfrom qiskit.aqua.components.optimizers import ADAM\nfrom qiskit.aqua.components.uncertainty_models import UnivariateVariationalDistribution, \\\n MultivariateVariationalDistribution\nfrom qiskit.aqua.components.neural_networks.generative_network import GenerativeNetwork\n\n# pylint: disable=invalid-name\n\n\nclass QuantumGenerator(GenerativeNetwork):\n \"\"\"Quantum Generator.\n\n The quantum generator is a parametrized quantum circuit which can be trained with the\n :class:`~qiskit.aqua.algorithms.QGAN` algorithm\n to generate a quantum state which approximates the probability\n distribution of given training data. At the beginning of the training the parameters will\n be set randomly, thus, the output will is random. Throughout the training the quantum\n generator learns to represent the target distribution.\n Eventually, the trained generator can be used for state preparation e.g. in QAE.\n \"\"\"\n\n def __init__(self,\n bounds: np.ndarray,\n num_qubits: List[int],\n generator_circuit: Optional[Union[UnivariateVariationalDistribution,\n MultivariateVariationalDistribution,\n QuantumCircuit]] = None,\n init_params: Optional[Union[List[float], np.ndarray]] = None,\n snapshot_dir: Optional[str] = None) -> None:\n \"\"\"\n Args:\n bounds: k min/max data values [[min_1,max_1],...,[min_k,max_k]],\n given input data dim k\n num_qubits: k numbers of qubits to determine representation resolution,\n i.e. n qubits enable the representation of 2**n values [n_1,..., n_k]\n generator_circuit: a UnivariateVariationalDistribution for univariate data,\n a MultivariateVariationalDistribution for multivariate data,\n or a QuantumCircuit implementing the generator.\n init_params: 1D numpy array or list, Initialization for\n the generator's parameters.\n snapshot_dir: str or None, if not None save the optimizer's parameter after every\n update step to the given directory\n\n Raises:\n AquaError: Set multivariate variational distribution to represent multivariate data\n \"\"\"\n super().__init__()\n self._bounds = bounds\n self._num_qubits = num_qubits\n self.generator_circuit = generator_circuit\n if generator_circuit is None:\n circuit = QuantumCircuit(sum(num_qubits))\n circuit.h(circuit.qubits)\n var_form = TwoLocal(sum(num_qubits), 'ry', 'cz', reps=1, entanglement='circular')\n circuit.compose(var_form, inplace=True)\n\n # Set generator circuit\n self.generator_circuit = circuit\n\n if isinstance(generator_circuit, (UnivariateVariationalDistribution,\n MultivariateVariationalDistribution)):\n warnings.warn('Passing a UnivariateVariationalDistribution or MultivariateVariational'\n 'Distribution is as ``generator_circuit`` is deprecated as of Aqua 0.8.0 '\n 'and the support will be removed no earlier than 3 months after the '\n 'release data. You should pass as QuantumCircuit instead.',\n DeprecationWarning, stacklevel=2)\n self._free_parameters = generator_circuit._var_form_params\n self.generator_circuit = generator_circuit._var_form\n else:\n self._free_parameters = list(self.generator_circuit.parameters)\n\n if init_params is None:\n init_params = aqua_globals.random.random(self.generator_circuit.num_parameters) * 2e-2\n\n self._bound_parameters = init_params\n\n # Set optimizer for updating the generator network\n self._optimizer = ADAM(maxiter=1, tol=1e-6, lr=1e-3, beta_1=0.7,\n beta_2=0.99, noise_factor=1e-6,\n eps=1e-6, amsgrad=True, snapshot_dir=snapshot_dir)\n\n if np.ndim(self._bounds) == 1:\n bounds = np.reshape(self._bounds, (1, len(self._bounds)))\n else:\n bounds = self._bounds\n for j, prec in enumerate(self._num_qubits):\n # prepare data grid for dim j\n grid = np.linspace(bounds[j, 0], bounds[j, 1], (2 ** prec))\n if j == 0:\n if len(self._num_qubits) > 1:\n self._data_grid = [grid]\n else:\n self._data_grid = grid\n self._grid_elements = grid\n elif j == 1:\n self._data_grid.append(grid)\n temp = []\n for g_e in self._grid_elements:\n for g in grid:\n temp0 = [g_e]\n temp0.append(g)\n temp.append(temp0)\n self._grid_elements = temp\n else:\n self._data_grid.append(grid)\n temp = []\n for g_e in self._grid_elements:\n for g in grid:\n temp0 = deepcopy(g_e)\n temp0.append(g)\n temp.append(temp0)\n self._grid_elements = deepcopy(temp)\n self._data_grid = np.array(self._data_grid)\n\n self._shots = None\n self._discriminator = None\n self._ret = {} # type: Dict[str, Any]\n\n def set_seed(self, seed):\n \"\"\"\n Set seed.\n\n Args:\n seed (int): seed\n \"\"\"\n aqua_globals.random_seed = seed\n\n def set_discriminator(self, discriminator):\n \"\"\"\n Set discriminator network.\n\n Args:\n discriminator (Discriminator): Discriminator used to compute the loss function.\n \"\"\"\n self._discriminator = discriminator\n\n def construct_circuit(self, params=None):\n \"\"\"\n Construct generator circuit.\n\n Args:\n params (list | dict): parameters which should be used to run the generator.\n\n Returns:\n Instruction: construct the quantum circuit and return as gate\n \"\"\"\n if params is None:\n return self.generator_circuit\n\n if isinstance(params, (list, np.ndarray)):\n params = dict(zip(self._free_parameters, params))\n\n return self.generator_circuit.assign_parameters(params)\n # self.generator_circuit.build(qc=qc, q=q)\n # else:\n # generator_circuit_copy = deepcopy(self.generator_circuit)\n # generator_circuit_copy.params = params\n # generator_circuit_copy.build(qc=qc, q=q)\n\n # # return qc.copy(name='qc')\n # return qc.to_instruction()\n\n def get_output(self, quantum_instance, params=None, shots=None):\n \"\"\"\n Get classical data samples from the generator.\n Running the quantum generator circuit results in a quantum state.\n To train this generator with a classical discriminator, we need to sample classical outputs\n by measuring the quantum state and mapping them to feature space defined by the training\n data.\n\n Args:\n quantum_instance (QuantumInstance): Quantum Instance, used to run the generator\n circuit.\n params (numpy.ndarray): array or None, parameters which should\n be used to run the generator, if None use self._params\n shots (int): if not None use a number of shots that is different from the\n number set in quantum_instance\n\n Returns:\n list: generated samples, array: sample occurrence in percentage\n \"\"\"\n instance_shots = quantum_instance.run_config.shots\n q = QuantumRegister(sum(self._num_qubits), name='q')\n qc = QuantumCircuit(q)\n if params is None:\n params = self._bound_parameters\n qc.append(self.construct_circuit(params), q)\n if quantum_instance.is_statevector:\n pass\n else:\n c = ClassicalRegister(sum(self._num_qubits), name='c')\n qc.add_register(c)\n qc.measure(q, c)\n\n if shots is not None:\n quantum_instance.set_config(shots=shots)\n\n result = quantum_instance.execute(qc)\n\n generated_samples = []\n if quantum_instance.is_statevector:\n result = result.get_statevector(qc)\n values = np.multiply(result, np.conj(result))\n values = list(values.real)\n keys = []\n for j in range(len(values)):\n keys.append(np.binary_repr(j, int(sum(self._num_qubits))))\n else:\n result = result.get_counts(qc)\n keys = list(result)\n values = list(result.values())\n values = [float(v) / np.sum(values) for v in values]\n generated_samples_weights = values\n for i, _ in enumerate(keys):\n index = 0\n temp = []\n for k, p in enumerate(self._num_qubits):\n bin_rep = 0\n j = 0\n while j < p:\n bin_rep += int(keys[i][index]) * 2 ** (int(p) - j - 1)\n j += 1\n index += 1\n if len(self._num_qubits) > 1:\n temp.append(self._data_grid[k][int(bin_rep)])\n else:\n temp.append(self._data_grid[int(bin_rep)])\n generated_samples.append(temp)\n\n # self.generator_circuit._probabilities = generated_samples_weights\n if shots is not None:\n # Restore the initial quantum_instance configuration\n quantum_instance.set_config(shots=instance_shots)\n return generated_samples, generated_samples_weights\n\n def loss(self, x, weights): # pylint: disable=arguments-differ\n \"\"\"\n Loss function for training the generator's parameters.\n\n Args:\n x (numpy.ndarray): sample label (equivalent to discriminator output)\n weights (numpy.ndarray): probability for measuring the sample\n\n Returns:\n float: loss function\n \"\"\"\n try:\n # pylint: disable=no-member\n loss = (-1) * np.dot(np.log(x).transpose(), weights)\n except Exception: # pylint: disable=broad-except\n loss = (-1) * np.dot(np.log(x), weights)\n return loss.flatten()\n\n def _get_objective_function(self, quantum_instance, discriminator):\n \"\"\"\n Get objective function\n\n Args:\n quantum_instance (QuantumInstance): used to run the quantum circuit.\n discriminator (torch.nn.Module): discriminator network to compute the sample labels.\n\n Returns:\n objective_function: objective function for quantum generator optimization\n \"\"\"\n\n def objective_function(params):\n \"\"\"\n Objective function\n\n Args:\n params (numpy.ndarray): generator parameters\n\n Returns:\n self.loss: loss function\n \"\"\"\n generated_data, generated_prob = self.get_output(quantum_instance, params=params,\n shots=self._shots)\n prediction_generated = discriminator.get_label(generated_data, detach=True)\n return self.loss(prediction_generated, generated_prob)\n\n return objective_function\n\n def train(self, quantum_instance=None, shots=None):\n \"\"\"\n Perform one training step w.r.t to the generator's parameters\n\n Args:\n quantum_instance (QuantumInstance): used to run the generator circuit.\n shots (int): Number of shots for hardware or qasm execution.\n\n Returns:\n dict: generator loss(float) and updated parameters (array).\n \"\"\"\n\n self._shots = shots\n # Force single optimization iteration\n self._optimizer._maxiter = 1\n self._optimizer._t = 0\n objective = self._get_objective_function(quantum_instance, self._discriminator)\n self._bound_parameters, loss, _ = self._optimizer.optimize(\n num_vars=len(self._bound_parameters),\n objective_function=objective,\n initial_point=self._bound_parameters\n )\n\n self._ret['loss'] = loss\n self._ret['params'] = self._bound_parameters\n\n return self._ret\n"
]
[
"import os\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict\nfrom collections import Iterable\nimport six\nimport sys\nimport inspect\nimport numpy as np\nimport uuid\nimport codecs\n\n\n# compatible with Python 2 *and* 3:\nABC = ABCMeta('ABC', (object,), {'__slots__': ()})\n\n\n_CUSTOM_PARAMETERS = OrderedDict()\n\n\nclass _NoneTypeWrapper(object):\n \"\"\"\n A wrapper to handle cases when `None` is passed as a possible parameter\n value to the engine.\n \"\"\"\n def __init__(self):\n pass\n\n def __call__(self, *args, **kwargs):\n return args[0]\n\n\nclass AbstractHyperParameter(ABC):\n \"\"\"\n Abstract Hyper Parameter that defines the methods that all hyperparameters\n need to supply\n\n # Arguments:\n name (str): Name of the hyper parameter\n values (List, None): A list of values (must all be pickle-able and hashable)\n values or None. If None, it is assumed to be a continuous value generator.\n\n # Raises:\n ValueError: If the `name` is not specified.\n \"\"\"\n def __init__(self, name, values, seed):\n\n if name is None:\n raise ValueError(\"`name` of the hyperparameter cannot be `None`\")\n\n self.name = name\n self.num_choices = len(values) if values is not None else 0\n self.param2id = OrderedDict()\n self.id2param = OrderedDict()\n self.param2type = OrderedDict()\n self.set_seed(seed)\n\n @abstractmethod\n def sample(self):\n \"\"\"\n Abstract method that defines how parameters are sampled.\n\n # Raises:\n NotImplementedError: Must be overridden by the subclass.\n\n # Returns:\n a singular value sampled from possible values.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def encode(self, x):\n \"\"\"\n Abstract method that defines how the parameter is encoded\n so that the model can properly be trained.\n\n # Arguments:\n x (int | float | str): a single value that needs to be encoded.\n\n # Raises:\n NotImplementedError: Must be overridden by the subclass.\n\n # Returns:\n an encoded representation of the value of `x`.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def decode(self, x):\n \"\"\"\n Abstract method that defines how the parameter is decoded so\n that the model can be properly trained.\n\n # Arguments:\n x (int | float): an encoded value that needs to be decoded.\n\n # Raises:\n NotImplementedError: Must be overridden by the subclass.\n\n # Returns:\n a decoded value for the encoded input `x`.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def _cast(self, x):\n \"\"\"\n Casts the given value to its original data type.\n\n # Arguments:\n x (int | float | str): Input sample that will be cast to the\n correct data type.\n\n # Returns:\n the sample cast to the correct data type.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'name': self.name,\n 'seed': self.seed,\n }\n return config\n\n @classmethod\n def load_from_config(cls, config):\n \"\"\"\n Utilizes the provided config to instantiate a new\n instance of the class with the same arguments.\n\n # Arguments:\n config (dict): A dictionary having keys as the argument names\n and values as the values specified to the class using its\n constructor.\n\n # Returns:\n A new instance of this class with the correct arguments.\n \"\"\"\n return cls(**config)\n\n def _build_maps(self, values):\n \"\"\"\n Prepares a pair of dictionaries to manage the values provided.\n\n # Arguments:\n values (List, None): A list of values that are embedded into\n a pair of dictionaries. All values must be pickle-able and hashable.\n \"\"\"\n if values is not None:\n for i, v in enumerate(values):\n self.param2id[v] = i\n self.id2param[i] = v\n\n # prepare a type map from string to its type, for fast checks\n if v is not None:\n self.param2type[v] = type(v)\n self.param2type[str(v)] = type(v)\n else:\n self.param2type[v] = _NoneTypeWrapper()\n self.param2type[str(v)] = _NoneTypeWrapper()\n\n def set_seed(self, seed):\n \"\"\"\n Sets the random seed of the local RNG.\n\n # Arguments:\n seed (int | None): Random seed value.\n \"\"\"\n self.seed = seed\n\n if seed is None:\n if six.PY3:\n seed = int.from_bytes(os.urandom(4), byteorder='little')\n else:\n seed = int(codecs.encode(os.urandom(4), 'hex'), 16)\n\n self.random = np.random.RandomState(seed)\n\n def __repr__(self):\n s = self.name + \" : \"\n vals = list(self.param2id.keys())\n return s + str(vals)\n\n\nclass DiscreteHyperParameter(AbstractHyperParameter):\n \"\"\"\n Discrete Hyper Parameter that defines a set of discrete values that it can take.\n\n # Arguments:\n name (str): Name of the hyper parameter.\n values (list): A list of values (must all be pickle-able and hashable)\n values or None.\n\n # Raises:\n ValueError: If the values provided is `None` or length of values is 0.\n\n # Raises:\n ValueError: If the `name` is not specified.\n \"\"\"\n def __init__(self, name, values, seed=None):\n\n super(DiscreteHyperParameter, self).__init__(name, values, seed)\n\n if values is not None and len(values) != 0:\n super(DiscreteHyperParameter, self)._build_maps(values)\n else:\n raise ValueError(\"DiscreteHyperParamter must be passed at least one \"\n \"or more values\")\n\n def sample(self):\n \"\"\"\n Samples a single value from its set of discrete values.\n\n # Returns:\n a single value from its list of possible values.\n \"\"\"\n choice = self.random.randint(0, self.num_choices, size=1, dtype=np.int64)[0]\n param = self.id2param[choice]\n return param\n\n def encode(self, x):\n \"\"\"\n Encodes a single value into an integer index.\n\n # Arguments:\n x (int | float | str): A value sampled from its possible values.\n\n # Returns:\n int value representing its encoded index.\n \"\"\"\n x = self._cast(x)\n return self.param2id[x]\n\n def decode(self, x):\n \"\"\"\n Decodes a single encoded integer into its original value.\n\n # Args:\n x (int): an integer encoded value.\n\n # Returns:\n (int | float | str) representing the actual decoded value.\n \"\"\"\n param = self.id2param[x]\n return self._cast(param)\n\n def _cast(self, x):\n \"\"\"\n Casts the sample to its original data type.\n\n # Arguments:\n x (int | float | str): Input sample that will be cast to the\n correct data type.\n\n # Returns:\n the sample cast to the correct data type.\n \"\"\"\n return self.param2type[x](x)\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'values': list(self.id2param.values()),\n }\n\n base_config = super(DiscreteHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass MultiDiscreteHyperParameter(AbstractHyperParameter):\n \"\"\"\n Discrete Hyper Parameter that defines a set of discrete values that it can take,\n and acts upon a list of samples.\n\n # Arguments:\n name (str): Name of the hyper parameter.\n values (list): A list of values (must all be pickle-able and hashable)\n values or None.\n sample_count (int): Number of samples that are required from this\n hyper parameter.\n\n # Raises:\n ValueError: If the values provided is `None` or length of values is 0.\n\n # Raises:\n ValueError: If the `name` is not specified or if `sample_count` is less\n than 1.\n \"\"\"\n def __init__(self, name, values, sample_count=1, seed=None):\n\n super(MultiDiscreteHyperParameter, self).__init__(name, values, seed)\n\n if sample_count < 1:\n raise ValueError(\"`sample_count` must be greater than 0.\")\n\n self.sample_count = sample_count\n if values is not None and len(values) != 0:\n super(MultiDiscreteHyperParameter, self)._build_maps(values)\n else:\n raise ValueError(\"MultiDiscreteHyperParamter must be passed at \"\n \"least one or more values.\")\n\n def sample(self):\n \"\"\"\n Samples a number of values from its set of discrete values.\n\n # Returns:\n a list of values from its set of possible values.\n \"\"\"\n choices = self.random.randint(0, self.num_choices, size=self.sample_count,\n dtype=np.int64)\n\n param = [self.id2param[choice] for choice in choices]\n return param\n\n def encode(self, x):\n \"\"\"\n Encodes a list of values into a list of the corresponding integer index.\n\n # Arguments:\n x (int | float | str): A list of values sampled from its\n possible values.\n\n # Returns:\n list of int values representing their encoded index.\n \"\"\"\n e = [self.param2id[self._cast(v)] for v in x]\n return e\n\n def decode(self, x):\n \"\"\"\n Decodes a list of encoded integers into their original value.\n\n # Args:\n x (int): a list of integer encoded values.\n\n # Returns:\n list of (int | float | str) representing the actual decoded\n values.\n \"\"\"\n params = [self._cast(self.id2param[v]) for v in x]\n return params\n\n def _cast(self, x):\n \"\"\"\n Casts the sample to its original data type.\n\n # Arguments:\n x (int | float | str): Input sample that will be cast to the\n correct data type.\n\n # Returns:\n the sample cast to the correct data type.\n \"\"\"\n return self.param2type[x](x)\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'values': list(self.id2param.values()),\n 'sample_count': self.sample_count,\n }\n\n base_config = super(MultiDiscreteHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass AbstractContinuousHyperParameter(AbstractHyperParameter):\n \"\"\"\n An abstract hyper parameter that represents a parameter that can take a range\n of values from a certain distribution.\n\n # Arguments:\n name (str): Name of the parameter.\n val1 (float): A symbolic value that is used by subclasses.\n val2 (float): A symbolic value that is used by subclasses.\n log_encode (bool): Determines whether the encoding must be in natural\n log-space or not.\n\n # Raises:\n NotImplementedError: If `sample()` is called.\n \"\"\"\n def __init__(self, name, val1, val2, log_encode=False, seed=None):\n super(AbstractContinuousHyperParameter, self).__init__(name, None, seed)\n\n if val1 is not None and val2 is not None:\n self._val1 = float(val1)\n self._val2 = float(val2)\n else:\n raise ValueError(\"val1 and val2 must be floating point \"\n \"numbers for ContinuousHyperParameters\")\n\n self.log_encode = log_encode\n\n if log_encode:\n if val1 < 0.0:\n raise ValueError(\"When using log encoding, negative values are not allowed for parameters\")\n\n def sample(self):\n \"\"\"\n Abstract method that must be redefined by base classes.\n\n # Returns:\n a float value.\n \"\"\"\n raise NotImplementedError(\"Subclass must implement this method !\")\n\n def encode(self, x):\n \"\"\"\n Encodes the floating point value into log space if `log_space` was set in\n the constructor, else returns its original value.\n\n # Arguments:\n x (float): a single sample.\n\n # Returns:\n float.\n \"\"\"\n x = self._cast(x)\n\n if self.log_encode:\n x = self._cast(np.log(x))\n\n return x\n\n def decode(self, x):\n \"\"\"\n Decodes the floating point value into normal space if `log_space` was set in\n the constructor, else returns its original value.\n\n # Arguments:\n x (float): a single encoded sample.\n\n # Returns:\n float.\n \"\"\"\n x = self._cast(x)\n\n if self.log_encode:\n x = self._cast(np.exp(x))\n\n return x\n\n def _cast(self, x):\n \"\"\"\n Casts the sample to its original data type.\n\n # Arguments:\n x (int | float | str): Input sample that will be cast to the\n correct data type.\n\n # Returns:\n the sample cast to the correct data type.\n \"\"\"\n if isinstance(x, np.ndarray) or hasattr(x, 'dtype'):\n return x.astype(np.float64)\n else:\n return float(x)\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n base_config = super(AbstractContinuousHyperParameter, self).get_config()\n return base_config\n\n def __repr__(self):\n s = \"%s : continuous [%0.3f, %0.3f)\\n\" % (self.name, self._val1, self._val2)\n return s\n\n\nclass AbstractMultiContinuousHyperParameter(AbstractHyperParameter):\n \"\"\"\n An abstract hyper parameter that represents a parameter that can take a range\n of values from a certain distribution, sampled multiple times.\n\n # Arguments:\n name (str): Name of the parameter.\n val1 (float): A symbolic value that is used by subclasses.\n val2 (float): A symbolic value that is used by subclasses.\n log_encode (bool): Determines whether the encoding must be in natural\n log-space or not.\n sample_count (int): Number of samples that are required from this\n hyper parameter.\n\n # Raises:\n NotImplementedError: If `sample()` is called.\n ValueErroe: If sample count is less than 1.\n \"\"\"\n def __init__(self, name, val1, val2, log_encode=False, sample_count=1, seed=None):\n super(AbstractMultiContinuousHyperParameter, self).__init__(name, None, seed)\n\n if sample_count < 1:\n raise ValueError(\"`sample_count` must be greater than 0.\")\n\n if val1 is not None and val2 is not None:\n self._val1 = float(val1)\n self._val2 = float(val2)\n else:\n raise ValueError(\"val1 and val2 must be floating point \"\n \"numbers for ContinuousHyperParameters\")\n\n self.log_encode = log_encode\n self.sample_count = sample_count\n\n if log_encode:\n if val1 < 0.0 or val2 < 0.0:\n raise ValueError(\"When using log encoding, negative values are not allowed for parameters\")\n\n def sample(self):\n \"\"\"\n Abstract method that must be redefined by base classes.\n\n # Returns:\n a float value.\n \"\"\"\n raise NotImplementedError(\"Subclass must implement this method !\")\n\n def encode(self, x):\n \"\"\"\n Encodes a list of floating point values into log space if `log_space`\n was set in the constructor, else returns its original value.\n\n # Arguments:\n x (float): a list of samples.\n\n # Returns:\n list of floats.\n \"\"\"\n if self.log_encode:\n x = [self._cast(np.log(v)) for v in x]\n else:\n x = [self._cast(v) for v in x]\n\n return x\n\n def decode(self, x):\n \"\"\"\n Decodes a list of floating point values into normal space if `log_space`\n was set in the constructor, else returns its original value.\n\n # Arguments:\n x (float): a list of encoded samples.\n\n # Returns:\n list of floats.\n \"\"\"\n if self.log_encode:\n x = [self._cast(np.exp(v)) for v in x]\n else:\n x = [self._cast(v) for v in x]\n\n return x\n\n def _cast(self, x):\n \"\"\"\n Casts the sample to its original data type.\n\n # Arguments:\n x (int | float): Input sample that will be cast to the\n correct data type.\n\n # Returns:\n the sample cast to the correct data type.\n \"\"\"\n if isinstance(x, np.ndarray) or hasattr(x, 'dtype'):\n return x.astype(np.float64)\n else:\n return float(x)\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'sample_count': self.sample_count,\n }\n\n base_config = super(AbstractMultiContinuousHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def __repr__(self):\n s = \"%s : continuous [%0.3f, %0.3f)\\n\" % (self.name, self._val1, self._val2)\n return s\n\n\nclass UniformContinuousHyperParameter(AbstractContinuousHyperParameter):\n \"\"\"\n A hyper parameter that represents a parameter that can take a range\n of values from a uniform distribution.\n\n # Arguments:\n name (str): Name of the parameter.\n min_value (float): The minimum value (inclusive) that the uniform\n distribution can take.\n max_value (float): The maximum value (exclusive) that the uniform\n distribution can take.\n log_encode (bool): Determines whether the encoding must be in natural\n log-space or not.\n \"\"\"\n def __init__(self, name, min_value, max_value, log_encode=False, seed=None):\n\n super(UniformContinuousHyperParameter, self).__init__(name, min_value, max_value,\n log_encode, seed)\n\n def sample(self):\n \"\"\"\n Samples uniformly from the range [min_value, max_value).\n\n # Returns:\n float.\n \"\"\"\n value = self.random.uniform(self._val1, self._val2, size=1)[0]\n return value\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'min_value': self.min_value,\n 'max_value': self.max_value,\n 'log_encode': self.log_encode,\n }\n\n base_config = super(UniformContinuousHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @property\n def min_value(self):\n return self._val1\n\n @property\n def max_value(self):\n return self._val2\n\n\nclass MultiUniformContinuousHyperParameter(AbstractMultiContinuousHyperParameter):\n \"\"\"\n A hyper parameter that represents a parameter that can take a range\n of values from a uniform distribution, sampled multiple times.\n\n # Arguments:\n name (str): Name of the parameter.\n min_value (float): The minimum value (inclusive) that the uniform\n distribution can take.\n max_value (float): The maximum value (exclusive) that the uniform\n distribution can take.\n log_encode (bool): Determines whether the encoding must be in natural\n log-space or not.\n sample_count (int): Number of samples that are required from this\n hyper parameter.\n\n # Raises:\n ValueErroe: If sample count is less than 1.\n \"\"\"\n def __init__(self, name, min_value, max_value, log_encode=False, sample_count=1, seed=None):\n\n super(MultiUniformContinuousHyperParameter, self).__init__(name, min_value, max_value,\n log_encode, sample_count,\n seed)\n\n def sample(self):\n \"\"\"\n Samples uniformly from the range [min_value, max_value).\n\n # Returns:\n list of floats.\n \"\"\"\n value = self.random.uniform(self._val1, self._val2, size=self.sample_count).tolist()\n return value\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'min_value': self.min_value,\n 'max_value': self.max_value,\n 'log_encode': self.log_encode,\n }\n\n base_config = super(MultiUniformContinuousHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @property\n def min_value(self):\n return self._val1\n\n @property\n def max_value(self):\n return self._val2\n\n\nclass NormalContinuousHyperParameter(AbstractContinuousHyperParameter):\n \"\"\"\n A hyper parameter that represents a parameter that can take a range\n of values from a normal distribution.\n\n # Arguments:\n name (str): Name of the parameter.\n mean (float): The mean of the normal distribution.\n std (float): The standard deviation of the normal distribution.\n \"\"\"\n def __init__(self, name, mean, std, seed=None):\n super(NormalContinuousHyperParameter, self).__init__(name, mean, std, False, seed)\n\n def sample(self):\n \"\"\"\n Samples from the normal distribution with a mean and standard deviation\n as specified in the constructor.\n\n # Returns:\n float.\n \"\"\"\n value = self.random.normal(self._val1, self._val2, size=1)[0]\n return value\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'mean': self.mean,\n 'std': self.std,\n }\n\n base_config = super(NormalContinuousHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @property\n def mean(self):\n return self._val1\n\n @property\n def std(self):\n return self._val2\n\n\nclass MultiNormalContinuousHyperParameter(AbstractMultiContinuousHyperParameter):\n \"\"\"\n A hyper parameter that represents a parameter that can take a range\n of values from a normal distribution, sampled multiple times.\n\n # Arguments:\n name (str): Name of the parameter.\n mean (float): The mean of the normal distribution.\n std (float): The standard deviation of the normal distribution.\n sample_count (int): Number of samples that are required from this\n hyper parameter.\n\n # Raises:\n ValueErroe: If sample count is less than 1.\n \"\"\"\n def __init__(self, name, mean, std, sample_count=1, seed=None):\n super(MultiNormalContinuousHyperParameter, self).__init__(name, mean, std,\n False, sample_count,\n seed)\n\n def sample(self):\n \"\"\"\n Samples from the normal distribution with a mean and standard deviation\n as specified in the constructor.\n\n # Returns:\n list of float.\n \"\"\"\n value = self.random.normal(self._val1, self._val2, size=self.sample_count).tolist()\n return value\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n a dictionary with the config of the class.\n \"\"\"\n config = {\n 'mean': self.mean,\n 'std': self.std,\n }\n\n base_config = super(MultiNormalContinuousHyperParameter, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @property\n def mean(self):\n return self._val1\n\n @property\n def std(self):\n return self._val2\n\n\nclass HyperParameterList(AbstractHyperParameter):\n \"\"\"\n A composite hyper parameter, that encloses a list of hyper parameters\n (either discrete or continuous) and provides utility methods for efficient\n handling by the engine.\n\n # Arguments:\n hyper_parameter_list (list(AnstractHyperParameter) | None): A list of\n hyper parameters or None (which initializes this with 0 elements).\n \"\"\"\n def __init__(self, hyper_parameter_list=None, seed=None):\n super(HyperParameterList, self).__init__('parameter_list', None, seed)\n self.name_map = OrderedDict()\n\n self._build_maps(hyper_parameter_list)\n self.set_seed(seed)\n\n def sample(self):\n \"\"\"\n Samples all of its component parameters and returns a list of the samples.\n\n # Returns:\n list of sampled parameters.\n \"\"\"\n values = []\n for v in self.id2param.values(): # type: AbstractHyperParameter\n x = v.sample()\n\n if isinstance(x, Iterable) and not isinstance(x, six.string_types):\n values.extend(x)\n else:\n values.append(x)\n\n return values\n\n def encode(self, x):\n \"\"\"\n Encodes a list of sampled hyper parameters.\n\n # Arguments:\n x (list | np.ndarray): A python list or numpy array of samples\n from the list of hyper parameters.\n\n # Raises:\n ValueError: If a numpy array of more than 1 dimension is provided.\n\n # Returns:\n ndarray(float).\n \"\"\"\n if isinstance(x, np.ndarray):\n if x.ndim != 1:\n raise ValueError(\"When encoding a list of hyper parameters, provide a python list \"\n \"or 1-dim numpy array\")\n else:\n x = x.tolist()\n\n values = []\n index = 0\n\n for param in self.id2param.values():\n if hasattr(param, 'sample_count'):\n v = param.encode(x[index: index + param.sample_count])\n values.extend(v)\n\n index += param.sample_count\n else:\n v = param.encode(x[index])\n values.append(v)\n\n index += 1\n\n values = np.array(values)\n return values\n\n def decode(self, x):\n \"\"\"\n Decodes a list of sampled hyper parameters.\n\n # Arguments:\n x (list(int | float)): a list of encoded integer or floating point\n values that are to be decoded.\n\n # Returns:\n list of decoded samples.\n \"\"\"\n if isinstance(x, np.ndarray):\n if x.ndim != 1:\n raise ValueError(\"When encoding a list of hyper parameters, provide a python list \"\n \"or 1-dim numpy array\")\n else:\n x = x.tolist()\n\n values = []\n index = 0\n\n for param in self.id2param.values():\n if hasattr(param, 'sample_count'):\n v = param.decode(x[index: index + param.sample_count])\n values.extend(v)\n\n index += param.sample_count\n else:\n v = param._cast(param.decode(x[index]))\n values.append(v)\n\n index += 1\n\n return values\n\n def _build_maps(self, values):\n \"\"\"\n Adds the individual hyper parameters to the list.\n\n # Arguments:\n values (list(AbstractHyperParameter) | None): a list of parameters.\n \"\"\"\n if values is not None:\n for param in values: # type: AbstractHyperParameter\n self.add_hyper_parameter(param)\n\n def _cast(self, x):\n \"\"\"\n Casts all of the samples to their original data types.\n\n # Arguments:\n x (list): Input samples that will be cast to their\n correct data types.\n\n # Returns:\n the list of samples cast to their correct data types.\n \"\"\"\n if isinstance(x, np.ndarray):\n if x.ndim != 1:\n raise ValueError(\"When encoding a list of hyper parameters, provide a python list \"\n \"or 1-dim numpy array\")\n else:\n x = x.tolist()\n\n types = []\n index = 0\n\n for param in self.id2param.values():\n if hasattr(param, 'sample_count'):\n for i in range(param.sample_count):\n id = index + i\n v = param._cast(x[id])\n types.append(v)\n\n index += param.sample_count\n else:\n v = param._cast(x[index])\n types.append(v)\n\n index += 1\n\n return types\n\n def get_config(self):\n \"\"\"\n Creates the config of the class with all of its values.\n\n # Returns:\n an ordered dictionary with the config of the class.\n \"\"\"\n config = OrderedDict()\n\n for name, param in zip(self.name_map.values(), self.id2param.values()): # type: (AbstractHyperParameter)\n class_name = param.__class__.__name__\n param_config = param.get_config()\n config[name] = [class_name, param_config]\n\n return config\n\n def set_seed(self, seed):\n \"\"\"\n Sets the seed of all the parameters held by the container.\n\n # Arguments:\n seed (int | None): Seed value for the random state.\n \"\"\"\n super(HyperParameterList, self).set_seed(seed)\n\n for param in self.id2param.values(): # type: (AbstractHyperParameter)\n param.set_seed(seed)\n\n if seed is not None:\n seed += 1\n\n @classmethod\n def load_from_config(cls, config):\n params = []\n\n for name, cls_config in config.items():\n param_class_name, param_config = cls_config\n param_class = get_parameter(param_class_name)\n param = param_class(**param_config)\n\n params.append(param)\n\n return cls(params)\n\n def add_hyper_parameter(self, parameter):\n \"\"\"\n Adds a single hyper parameter (discrete or continuous) to the list\n of hyper parameters managed by this HyperParameterList.\n\n # Arguments:\n parameter (AbstractHyperParameter): a subclass of AbstractHyperParameter,\n which will be embedded into this composite class.\n\n # Raises:\n ValueError: If the passed parameter is `None`, or the name already\n exists in the list of managed parameters.\n \"\"\"\n if parameter is None:\n raise ValueError(\"When adding a hyper parameter, `None` cannot be passed\")\n\n if parameter.name in self.name_map.values():\n raise ValueError('Cannot add two hyper parameters with same name (%s)' %\n parameter.name)\n\n id = str(uuid.uuid4())\n\n self.name_map[id] = parameter.name\n self.id2param[id] = parameter\n self.param2id[parameter.name] = id\n self.num_choices += 1\n\n def remove_hyper_parameter(self, parameter):\n \"\"\"\n Removes a single hyper parameter (discrete or continuous) from the list\n of hyper parameters managed by this HyperParameterList.\n\n # Arguments:\n parameter (AbstractHyperParameter, str): A string name or a subclass\n of AbstractHyperParameter which needs to be removed.\n\n # Raises:\n ValueError: If the passed parameter is `None`.\n \"\"\"\n if parameter is None:\n raise ValueError(\"When adding a hyper parameter, `None` cannot be passed\")\n\n if isinstance(parameter, AbstractHyperParameter):\n id = self.param2id[parameter.name]\n del self.param2id[parameter.name]\n else:\n if parameter in self.param2id:\n id = self.param2id[parameter]\n del self.param2id[parameter]\n else:\n raise KeyError(\"The hyper parameter with name %s has not been added to \"\n \"this list.\" % parameter)\n\n del self.name_map[id]\n del self.id2param[id]\n self.num_choices -= 1\n\n def get_parameter_names(self):\n \"\"\"\n Gets a list of all the parameter names managed by this class.\n\n # Returns:\n a list(str) with the names of the parameters.\n \"\"\"\n name_list = []\n\n for v in self.id2param.values(): # type: AbstractHyperParameter\n if hasattr(v, 'sample_count'):\n for i in range(v.sample_count):\n name_list.append(v.name + \"_%d\" % (i + 1))\n else:\n name_list.append(v.name)\n\n return name_list\n\n def __repr__(self):\n s = \"\"\n for v in self.id2param.values(): # type: AbstractHyperParameter\n s = s + str(v) + \"\\n\"\n return s\n\n def __len__(self):\n return len(self.name_map)\n\n\ndef set_custom_parameter_class(cls):\n \"\"\"\n Utility function to dynamically add a custom hyper parameter\n to the set of available hyper parameters.\n\n # Arguments:\n cls (cls): A class which extends `AbstractHyperParameter` in some way\n and implements the abstract methods.\n \"\"\"\n global _CUSTOM_PARAMETERS\n _CUSTOM_PARAMETERS[cls.__name__] = cls\n\n\ndef get_parameter(name):\n \"\"\"\n Utility method to get the hyper parameter class by its name.\n\n # Arguments:\n name (str): Name of the class or its alias.\n\n # Raises:\n ValueError: If the class with the provided name does not exists in\n the set of available parameters.\n\n # Returns:\n The hyper parameter class.\n \"\"\"\n global _CUSTOM_PARAMETERS\n\n if name in _CUSTOM_PARAMETERS:\n return _CUSTOM_PARAMETERS[name]\n\n module_classes = inspect.getmembers(sys.modules[__name__], inspect.isclass)\n module_classes = dict(module_classes)\n\n if name in module_classes:\n return module_classes[name]\n else:\n raise ValueError('No hyper parameter class with the name %s was found in '\n 'the hyper parameters module !')\n\n\n# Aliases\nDiscreteHP = DiscreteHyperParameter\nUniformHP = UniformContinuousHyperParameter\nNormalHP = NormalContinuousHyperParameter\n\nMultiDiscreteHP = MultiDiscreteHyperParameter\nMultiUniformHP = MultiUniformContinuousHyperParameter\nMultiNormlHP = MultiNormalContinuousHyperParameter\n"
]
[
"from enum import Enum\nimport pandas as pd\nimport xlrd\nfrom pathlib import Path\nimport numpy as np\nimport csv\n\n\nclass Tag(Enum):\n NO_GO = \"no go\"\n GO = \"go\"\n S_H = \"sanity high\"\n S_L = \"sanity low\"\n NO_SHOW = \"no show\"\n\n\nclass Sort_By_BDM:\n \"\"\"\n This class reads a text file of BSM results and excel file of keys of tagging by ranking and\n creates a sorted DataFrame with the snack image name as index.\n the columns of the DataFrame are ranking (1 for the highest Bid), Bid (score by BDM),\n tag (Enum object), show (boolean) and cued (boolean)\n Other attributes: the full text file name, the full excel file name and key DataFrame with\n ranking as index, a tag column (string) and enum_col (Tags)\n \"\"\"\n def __init__(self, text_file_path, key_file_path):\n self.text_file_path = Path(text_file_path)\n self.key_file_path = Path(key_file_path)\n self.sorted_df = None\n self.key_df = None\n\n def create_full_df(self):\n self._read_BDM_results()\n self._read_keys_file()\n self._disp_changes()\n self._add_beep_and_show_cols()\n self._validate_df_is_full()\n return self.sorted_df\n\n def _read_BDM_results(self):\n \"\"\"\n reads the BDM results text file and return a DataFrame with snacks' image names as index and Bid column\n the returned DataFrame is sorted by Bid, descending values\n \"\"\"\n with open(self.text_file_path) as file:\n df = pd.read_table(file, index_col=0)\n # creating a dataframe with the stimulus name as index (image name) and sorted by ranking\n df.set_index('StimName', inplace=True)\n df.pop('RT')\n self.sorted_df = df.sort_values('Bid', ascending=0)\n\n def _read_keys_file(self):\n \"\"\"\n reads an excel keys file that contain a ranking column and tag column\n returns a DataFrame with ranking as index and a tag column\n \"\"\"\n xl = pd.ExcelFile(self.key_file_path)\n key_df = xl.parse()\n key_df.set_index('ranking', inplace=True)\n # adds a column with the Tag object to use instead of the strings\n key_df['enum_col'] = key_df.tag.apply(lambda x: Tag(x))\n self.key_df = key_df\n\n def _disp_changes(self):\n # adds a column of tag to sorted_df\n self.sorted_df['tag'] = self.key_df['enum_col'].tolist()\n # adds a column of ranking\n self.sorted_df.insert(loc=0, column='ranking', value=self.key_df.index.values)\n\n def _add_beep_and_show_cols(self):\n # adds a boolean columns that indicate if we should show a snack and if its cued\n self.sorted_df['show'] = self.sorted_df.tag.apply(lambda x: x.name != 'NO_SHOW')\n self.sorted_df['cued'] = self.sorted_df.tag.apply(lambda x: x.name == 'GO')\n\n\n def _validate_df_is_full(self):\n # verifying the dataframe has no null values\n if self.sorted_df.isnull().values.any():\n raise IndexError('The snacks of the BDM and the Excel file do not match')\n\nif __name__ == '__main__':\n # reading the results of the BDM\n p = r'C:\\Users\\wolfi\\Documents\\PythonCourse\\Final_project\\Python-Hackathon\\Only_6_snacks.txt'\n file_path = Path(p)\n\n # reading and creating a dataframe with tag for each position of the sorted ranking\n key_p = r'C:\\Users\\wolfi\\Documents\\PythonCourse\\Final_project\\Python-Hackathon\\Only_6_snacks_ladder_key.xlsx'\n key_p = Path(key_p)\n print(key_p)\n A = Sort_By_BDM(file_path, key_p)\n print(A.create_full_df())\n\n A.sorted_df.to_csv('Only_6_sorted_BDM_mock_data.csv')\n"
]
[
"# This work is licensed under the terms of the MIT license.\n# For a copy, see <https://opensource.org/licenses/MIT>.\n\n\"\"\"\nThis module provides GlobalRoutePlanner implementation.\n\"\"\"\n\nimport math\n\nimport numpy as np\nimport networkx as nx\n\nimport carla\n\nfrom sources.navigation.modified_local_planner import RoadOption\nfrom sources.navigation.misc import vector\n\n\nclass GlobalRoutePlanner(object):\n \"\"\"\n This class provides a very high level route plan.\n Instantiate the class by passing a reference to\n A GlobalRoutePlannerDAO object.\n \"\"\"\n\n def __init__(self, dao):\n \"\"\"\n Constructor\n \"\"\"\n self._dao = dao\n self._topology = None\n self._graph = None\n self._id_map = None\n self._road_id_to_edge = None\n self._intersection_end_node = -1\n self._previous_decision = RoadOption.VOID\n\n def setup(self):\n \"\"\"\n Performs initial server data lookup for detailed topology\n and builds graph representation of the world map.\n \"\"\"\n self._topology = self._dao.get_topology()\n self._graph, self._id_map, self._road_id_to_edge = self._build_graph()\n self._find_loose_ends()\n self._lane_change_link()\n\n def _build_graph(self):\n \"\"\"\n This function builds a networkx graph representation of topology.\n The topology is read from self._topology.\n graph node properties:\n vertex - (x,y,z) position in world map\n graph edge properties:\n entry_vector - unit vector along tangent at entry point\n exit_vector - unit vector along tangent at exit point\n net_vector - unit vector of the chord from entry to exit\n intersection - boolean indicating if the edge belongs to an\n intersection\n return : graph -> networkx graph representing the world map,\n id_map-> mapping from (x,y,z) to node id\n road_id_to_edge-> map from road id to edge in the graph\n \"\"\"\n graph = nx.DiGraph()\n id_map = dict() # Map with structure {(x,y,z): id, ... }\n road_id_to_edge = dict() # Map with structure {road_id: {lane_id: edge, ... }, ... }\n\n for segment in self._topology:\n\n entry_xyz, exit_xyz = segment['entryxyz'], segment['exitxyz']\n path = segment['path']\n entry_wp, exit_wp = segment['entry'], segment['exit']\n intersection = entry_wp.is_junction\n road_id, section_id, lane_id = entry_wp.road_id, entry_wp.section_id, entry_wp.lane_id\n\n for vertex in entry_xyz, exit_xyz:\n # Adding unique nodes and populating id_map\n if vertex not in id_map:\n new_id = len(id_map)\n id_map[vertex] = new_id\n graph.add_node(new_id, vertex=vertex)\n n1 = id_map[entry_xyz]\n n2 = id_map[exit_xyz]\n if road_id not in road_id_to_edge:\n road_id_to_edge[road_id] = dict()\n if section_id not in road_id_to_edge[road_id]:\n road_id_to_edge[road_id][section_id] = dict()\n road_id_to_edge[road_id][section_id][lane_id] = (n1, n2)\n\n entry_carla_vector = entry_wp.transform.rotation.get_forward_vector()\n exit_carla_vector = exit_wp.transform.rotation.get_forward_vector()\n # Adding edge with attributes\n graph.add_edge(\n n1, n2,\n length=len(path) + 1, path=path,\n entry_waypoint=entry_wp, exit_waypoint=exit_wp,\n entry_vector=np.array(\n [entry_carla_vector.x, entry_carla_vector.y, entry_carla_vector.z]),\n exit_vector=np.array(\n [exit_carla_vector.x, exit_carla_vector.y, exit_carla_vector.z]),\n net_vector=vector(entry_wp.transform.location, exit_wp.transform.location),\n intersection=intersection, type=RoadOption.LANEFOLLOW)\n\n return graph, id_map, road_id_to_edge\n\n def _find_loose_ends(self):\n \"\"\"\n This method finds road segments that have an unconnected end and\n adds them to the internal graph representation\n \"\"\"\n count_loose_ends = 0\n hop_resolution = self._dao.get_resolution()\n for segment in self._topology:\n end_wp = segment['exit']\n exit_xyz = segment['exitxyz']\n road_id, section_id, lane_id = end_wp.road_id, end_wp.section_id, end_wp.lane_id\n if road_id in self._road_id_to_edge and \\\n section_id in self._road_id_to_edge[road_id] and \\\n lane_id in self._road_id_to_edge[road_id][section_id]:\n pass\n else:\n count_loose_ends += 1\n if road_id not in self._road_id_to_edge:\n self._road_id_to_edge[road_id] = dict()\n if section_id not in self._road_id_to_edge[road_id]:\n self._road_id_to_edge[road_id][section_id] = dict()\n n1 = self._id_map[exit_xyz]\n n2 = -1*count_loose_ends\n self._road_id_to_edge[road_id][section_id][lane_id] = (n1, n2)\n next_wp = end_wp.next(hop_resolution)\n path = []\n while next_wp is not None and next_wp and \\\n next_wp[0].road_id == road_id and \\\n next_wp[0].section_id == section_id and \\\n next_wp[0].lane_id == lane_id:\n path.append(next_wp[0])\n next_wp = next_wp[0].next(hop_resolution)\n if path:\n n2_xyz = (path[-1].transform.location.x,\n path[-1].transform.location.y,\n path[-1].transform.location.z)\n self._graph.add_node(n2, vertex=n2_xyz)\n self._graph.add_edge(\n n1, n2,\n length=len(path) + 1, path=path,\n entry_waypoint=end_wp, exit_waypoint=path[-1],\n entry_vector=None, exit_vector=None, net_vector=None,\n intersection=end_wp.is_intersection, type=RoadOption.LANEFOLLOW)\n\n def _localize(self, location):\n \"\"\"\n This function finds the road segment closest to given location\n location : carla.Location to be localized in the graph\n return : pair node ids representing an edge in the graph\n \"\"\"\n waypoint = self._dao.get_waypoint(location)\n edge = None\n try:\n edge = self._road_id_to_edge[waypoint.road_id][waypoint.section_id][waypoint.lane_id]\n except KeyError:\n print(\n \"Failed to localize! : \",\n \"Road id : \", waypoint.road_id,\n \"Section id : \", waypoint.section_id,\n \"Lane id : \", waypoint.lane_id,\n \"Location : \", waypoint.transform.location.x,\n waypoint.transform.location.y)\n return edge\n\n def _lane_change_link(self):\n \"\"\"\n This method places zero cost links in the topology graph\n representing availability of lane changes.\n \"\"\"\n\n for segment in self._topology:\n left_found, right_found = False, False\n\n for waypoint in segment['path']:\n if not segment['entry'].is_junction:\n next_waypoint, next_road_option, next_segment = None, None, None\n\n if bool(waypoint.lane_change & carla.LaneChange.Right) and not right_found:\n next_waypoint = waypoint.get_right_lane()\n if next_waypoint is not None and \\\n next_waypoint.lane_type == carla.LaneType.Driving and \\\n waypoint.road_id == next_waypoint.road_id:\n next_road_option = RoadOption.CHANGELANERIGHT\n next_segment = self._localize(next_waypoint.transform.location)\n if next_segment is not None:\n self._graph.add_edge(\n self._id_map[segment['entryxyz']], next_segment[0], entry_waypoint=segment['entry'],\n exit_waypoint=self._graph.edges[next_segment[0], next_segment[1]]['entry_waypoint'],\n path=[], length=0, type=next_road_option, change_waypoint = waypoint)\n right_found = True\n\n if bool(waypoint.lane_change & carla.LaneChange.Left) and not left_found:\n next_waypoint = waypoint.get_left_lane()\n if next_waypoint is not None and next_waypoint.lane_type == carla.LaneType.Driving and \\\n waypoint.road_id == next_waypoint.road_id:\n next_road_option = RoadOption.CHANGELANELEFT\n next_segment = self._localize(next_waypoint.transform.location)\n if next_segment is not None:\n self._graph.add_edge(\n self._id_map[segment['entryxyz']], next_segment[0], entry_waypoint=segment['entry'],\n exit_waypoint=self._graph.edges[next_segment[0], next_segment[1]]['entry_waypoint'],\n path=[], length=0, type=next_road_option, change_waypoint = waypoint)\n left_found = True\n\n if left_found and right_found:\n break\n\n def _distance_heuristic(self, n1, n2):\n \"\"\"\n Distance heuristic calculator for path searching\n in self._graph\n \"\"\"\n l1 = np.array(self._graph.nodes[n1]['vertex'])\n l2 = np.array(self._graph.nodes[n2]['vertex'])\n return np.linalg.norm(l1-l2)\n\n def _path_search(self, origin, destination):\n \"\"\"\n This function finds the shortest path connecting origin and destination\n using A* search with distance heuristic.\n origin : carla.Location object of start position\n destination : carla.Location object of of end position\n return : path as list of node ids (as int) of the graph self._graph\n connecting origin and destination\n \"\"\"\n\n start, end = self._localize(origin), self._localize(destination)\n\n route = nx.astar_path(\n self._graph, source=start[0], target=end[0],\n heuristic=self._distance_heuristic, weight='length')\n route.append(end[1])\n return route\n\n def _successive_last_intersection_edge(self, index, route):\n \"\"\"\n This method returns the last successive intersection edge\n from a starting index on the route.\n\n This helps moving past tiny intersection edges to calculate\n proper turn decisions.\n \"\"\"\n\n last_intersection_edge = None\n last_node = None\n for node1, node2 in [(route[i], route[i+1]) for i in range(index, len(route)-1)]:\n candidate_edge = self._graph.edges[node1, node2]\n if node1 == route[index]:\n last_intersection_edge = candidate_edge\n if candidate_edge['type'] == RoadOption.LANEFOLLOW and \\\n candidate_edge['intersection']:\n last_intersection_edge = candidate_edge\n last_node = node2\n else:\n break\n\n return last_node, last_intersection_edge\n\n def _turn_decision(self, index, route, threshold=math.radians(5)):\n \"\"\"\n This method returns the turn decision (RoadOption) for pair of edges\n around current index of route list\n \"\"\"\n\n decision = None\n previous_node = route[index-1]\n current_node = route[index]\n next_node = route[index+1]\n next_edge = self._graph.edges[current_node, next_node]\n if index > 0:\n if self._previous_decision != RoadOption.VOID and \\\n self._intersection_end_node > 0 and \\\n self._intersection_end_node != previous_node and \\\n next_edge['type'] == RoadOption.LANEFOLLOW and \\\n next_edge['intersection']:\n decision = self._previous_decision\n else:\n self._intersection_end_node = -1\n current_edge = self._graph.edges[previous_node, current_node]\n calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \\\n not current_edge['intersection'] and \\\n next_edge['type'].value == RoadOption.LANEFOLLOW.value and \\\n next_edge['intersection']\n if calculate_turn:\n last_node, tail_edge = self._successive_last_intersection_edge(index, route)\n self._intersection_end_node = last_node\n if tail_edge is not None:\n next_edge = tail_edge\n cv, nv = current_edge['exit_vector'], next_edge['net_vector']\n cross_list = []\n for neighbor in self._graph.successors(current_node):\n select_edge = self._graph.edges[current_node, neighbor]\n if select_edge['type'].value == RoadOption.LANEFOLLOW.value:\n if neighbor != route[index+1]:\n sv = select_edge['net_vector']\n cross_list.append(np.cross(cv, sv)[2])\n next_cross = np.cross(cv, nv)[2]\n deviation = math.acos(np.clip(\n np.dot(cv, nv)/(np.linalg.norm(cv)*np.linalg.norm(nv)), -1.0, 1.0))\n if not cross_list:\n cross_list.append(0)\n if deviation < threshold:\n decision = RoadOption.STRAIGHT\n elif cross_list and next_cross < min(cross_list):\n decision = RoadOption.LEFT\n elif cross_list and next_cross > max(cross_list):\n decision = RoadOption.RIGHT\n elif next_cross < 0:\n decision = RoadOption.LEFT\n elif next_cross > 0:\n decision = RoadOption.RIGHT\n else:\n decision = next_edge['type']\n else:\n decision = next_edge['type']\n self._previous_decision = decision\n\n return decision\n\n def abstract_route_plan(self, origin, destination):\n \"\"\"\n The following function generates the route plan based on\n origin : carla.Location object of the route's start position\n destination : carla.Location object of the route's end position\n return : list of turn by turn navigation decisions as\n agents.navigation.local_planner.RoadOption elements\n Possible values are STRAIGHT, LEFT, RIGHT, LANEFOLLOW, VOID\n CHANGELANELEFT, CHANGELANERIGHT\n \"\"\"\n\n route = self._path_search(origin, destination)\n plan = []\n\n for i in range(len(route) - 1):\n road_option = self._turn_decision(i, route)\n plan.append(road_option)\n\n return plan\n\n def _find_closest_in_list(self, current_waypoint, waypoint_list):\n min_distance = float('inf')\n closest_index = -1\n for i, waypoint in enumerate(waypoint_list):\n distance = waypoint.transform.location.distance(\n current_waypoint.transform.location)\n if distance < min_distance:\n min_distance = distance\n closest_index = i\n\n return closest_index\n\n def trace_route(self, origin, destination):\n \"\"\"\n This method returns list of (carla.Waypoint, RoadOption)\n from origin (carla.Location) to destination (carla.Location)\n \"\"\"\n\n route_trace = []\n route = self._path_search(origin, destination)\n current_waypoint = self._dao.get_waypoint(origin)\n destination_waypoint = self._dao.get_waypoint(destination)\n resolution = self._dao.get_resolution()\n\n for i in range(len(route) - 1):\n road_option = self._turn_decision(i, route)\n edge = self._graph.edges[route[i], route[i+1]]\n path = []\n\n if edge['type'].value != RoadOption.LANEFOLLOW.value and \\\n edge['type'].value != RoadOption.VOID.value:\n route_trace.append((current_waypoint, road_option))\n exit_wp = edge['exit_waypoint']\n n1, n2 = self._road_id_to_edge[exit_wp.road_id][exit_wp.section_id][exit_wp.lane_id]\n next_edge = self._graph.edges[n1, n2]\n if next_edge['path']:\n closest_index = self._find_closest_in_list(current_waypoint, next_edge['path'])\n closest_index = min(len(next_edge['path'])-1, closest_index+5)\n current_waypoint = next_edge['path'][closest_index]\n else:\n current_waypoint = next_edge['exit_waypoint']\n route_trace.append((current_waypoint, road_option))\n\n else:\n path = path + [edge['entry_waypoint']] + edge['path'] + [edge['exit_waypoint']]\n closest_index = self._find_closest_in_list(current_waypoint, path)\n for waypoint in path[closest_index:]:\n current_waypoint = waypoint\n route_trace.append((current_waypoint, road_option))\n if len(route)-i <= 2 and \\\n waypoint.transform.location.distance(destination) < 2*resolution:\n break\n elif len(route)-i <= 2 and \\\n current_waypoint.road_id == destination_waypoint.road_id and \\\n current_waypoint.section_id == destination_waypoint.section_id and \\\n current_waypoint.lane_id == destination_waypoint.lane_id:\n destination_index = self._find_closest_in_list(destination_waypoint, path)\n if closest_index > destination_index:\n break\n\n return route_trace\n"
]
[
"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torch.optim import lr_scheduler\nimport math\nimport numbers\nfrom torch.nn import functional as F\n\n\n###############################################################################\n# Helper Functions\n###############################################################################\n\n\nclass Identity(nn.Module):\n def forward(self, x):\n return x\n\n\ndef get_norm_layer(norm_type='instance'):\n \"\"\"Return a normalization layer\n\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.\n \"\"\"\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n elif norm_type == 'none':\n norm_layer = lambda x: Identity()\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n \"\"\"Return a learning rate scheduler\n\n Parameters:\n optimizer -- the optimizer of the network\n opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions. \n opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine\n\n For 'linear', we keep the same learning rate for the first <opt.niter> epochs\n and linearly decay the rate to zero over the next <opt.niter_decay> epochs.\n For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.\n See https://pytorch.org/docs/stable/optim.html for more details.\n \"\"\"\n if opt.lr_policy == 'linear':\n def lambda_rule(epoch):\n lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n elif opt.lr_policy == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)\n elif opt.lr_policy == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)\n elif opt.lr_policy == 'cosine':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.niter, eta_min=0)\n else:\n return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)\n return scheduler\n\n\ndef init_weights(net, init_type='normal', init_gain=0.02):\n \"\"\"Initialize network weights.\n\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n\n We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might\n work better for some applications. Feel free to try yourself.\n \"\"\"\n def init_func(m): # define the initialization function\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n init.normal_(m.weight.data, 0.0, init_gain)\n elif init_type == 'xavier':\n init.xavier_normal_(m.weight.data, gain=init_gain)\n elif init_type == 'kaiming':\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n init.orthogonal_(m.weight.data, gain=init_gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n init.normal_(m.weight.data, 1.0, init_gain)\n init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func) # apply the initialization function <init_func>\n\n\ndef init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights\n Parameters:\n net (network) -- the network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Return an initialized network.\n \"\"\"\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n net.to(gpu_ids[0])\n net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs\n init_weights(net, init_type, init_gain=init_gain)\n return net\n\n\ndef define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Create a generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128\n norm (str) -- the name of normalization layers used in the network: batch | instance | none\n use_dropout (bool) -- if use dropout layers.\n init_type (str) -- the name of our initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a generator\n\n Our current implementation provides two types of generators:\n U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)\n The original U-Net paper: https://arxiv.org/abs/1505.04597\n\n Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)\n Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.\n We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).\n\n\n The generator has been initialized by <init_net>. It uses RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netG == 'resnet_9blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n elif netG == 'resnet_6blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)\n elif netG == 'unet_128':\n net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n elif netG == 'unet_256':\n net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n else:\n raise NotImplementedError('Generator model name [%s] is not recognized' % netG)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\ndef define_Gated_G(input_nc, input_nclass, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[], n_content=None):\n \"\"\"Create a generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128\n norm (str) -- the name of normalization layers used in the network: batch | instance | none\n use_dropout (bool) -- if use dropout layers.\n init_type (str) -- the name of our initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a generator\n\n Our current implementation provides two types of generators:\n U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)\n The original U-Net paper: https://arxiv.org/abs/1505.04597\n\n Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)\n Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.\n We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).\n\n\n The generator has been initialized by <init_net>. It uses RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n if netG == 'gated_resnet_6blocks':\n net = GatedResnetGenerator(input_nc, input_nclass, n_content, output_nc, ngf, False)\n elif netG == 'auto_gated_resnet_6blocks':\n net = GatedResnetGenerator(input_nc, input_nclass, n_content, output_nc, ngf, True)\n else:\n raise NotImplementedError('Generator model name [%s] is not recognized' % netG)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\ndef define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[], input_nclass=None, input_ncontent=None):\n \"\"\"Create a discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the first conv layer\n netD (str) -- the architecture's name: basic | n_layers | pixel\n n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'\n norm (str) -- the type of normalization layers used in the network.\n init_type (str) -- the name of the initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a discriminator\n\n Our current implementation provides three types of discriminators:\n [basic]: 'PatchGAN' classifier described in the original pix2pix paper.\n It can classify whether 70×70 overlapping patches are real or fake.\n Such a patch-level discriminator architecture has fewer parameters\n than a full-image discriminator and can work on arbitrarily-sized images\n in a fully convolutional fashion.\n\n [n_layers]: With this mode, you cna specify the number of conv layers in the discriminator\n with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)\n\n [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.\n It encourages greater color diversity but has no effect on spatial statistics.\n\n The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netD == 'basic': # default PatchGAN classifier\n net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, input_nclass=input_nclass, input_ncontent=input_ncontent)\n elif netD == 'n_layers': # more options\n net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, input_nclass=input_nclass, input_ncontent=input_ncontent)\n elif netD == 'pixel': # classify if each pixel is real or fake\n net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)\n else:\n raise NotImplementedError('Discriminator model name [%s] is not recognized' % net)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\n##############################################################################\n# Classes\n##############################################################################\nclass GANLoss(nn.Module):\n \"\"\"Define different GAN objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n \"\"\"\n\n def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n \"\"\" Initialize the GANLoss class.\n\n Parameters:\n gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.gan_mode = gan_mode\n if gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLoss()\n elif gan_mode in ['wgangp']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % gan_mode)\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n return target_tensor.expand_as(prediction)\n\n def __call__(self, prediction, target_is_real):\n \"\"\"Calculate loss given Discriminator's output and grount truth labels.\n\n Parameters:\n prediction (tensor) - - tpyically the prediction output from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n\n Returns:\n the calculated loss.\n \"\"\"\n if self.gan_mode in ['lsgan', 'vanilla']:\n target_tensor = self.get_target_tensor(prediction, target_is_real)\n loss = self.loss(prediction, target_tensor)\n elif self.gan_mode == 'wgangp':\n if target_is_real:\n loss = -prediction.mean()\n else:\n loss = prediction.mean()\n return loss\n\n\ndef cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):\n \"\"\"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n\n Arguments:\n netD (network) -- discriminator network\n real_data (tensor array) -- real images\n fake_data (tensor array) -- generated images from the generator\n device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')\n type (str) -- if we mix real and fake data or not [real | fake | mixed].\n constant (float) -- the constant used in formula ( | |gradient||_2 - constant)^2\n lambda_gp (float) -- weight for this loss\n\n Returns the gradient penalty loss\n \"\"\"\n if lambda_gp > 0.0:\n if type == 'real': # either use real images, fake images, or a linear interpolation of two.\n interpolatesv = real_data\n elif type == 'fake':\n interpolatesv = fake_data\n elif type == 'mixed':\n alpha = torch.rand(real_data.shape[0], 1)\n alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)\n alpha = alpha.to(device)\n interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)\n else:\n raise NotImplementedError('{} not implemented'.format(type))\n interpolatesv.requires_grad_(True)\n disc_interpolates = netD(interpolatesv)\n gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv,\n grad_outputs=torch.ones(disc_interpolates.size()).to(device),\n create_graph=True, retain_graph=True, only_inputs=True)\n gradients = gradients[0].view(real_data.size(0), -1) # flat the data\n gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps\n return gradient_penalty, gradients\n else:\n return 0.0, None\n\nclass GatedResnetGenerator(nn.Module):\n \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n \"\"\"\n\n def __init__(self, input_nc, input_nclass, n_content, output_nc, ngf=64, use_identity=False, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=5, padding_type='reflect'):\n \"\"\"Construct a Resnet-based generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers\n n_blocks (int) -- the number of ResNet blocks\n padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero\n \"\"\"\n assert(n_blocks >= 0)\n super(GatedResnetGenerator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n encoder = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n self.n_style = input_nclass + (1 if use_identity else 0)\n self.n_content = n_content\n\n n_downsampling = 2\n for i in range(n_downsampling): # add downsampling layers\n mult = 2 ** i\n encoder += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n if n_content:\n if use_identity:\n self.n_content += 1\n n_blocks -= 1\n content_transformers = [ResnetBlock(ngf * mult * 2, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)\n for i in range(n_content)]\n if use_identity:\n content_transformers.append(nn.Identity())\n self.content_transformers = nn.ModuleList(content_transformers)\n \n # add transformer\n style_transformers = [ResnetBlock(ngf * mult * 2, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)\n for i in range(input_nclass)]\n if use_identity:\n style_transformers.append(nn.Identity())\n self.transformers = nn.ModuleList(style_transformers)\n\n decoder = []\n mult = 2 ** n_downsampling\n for i in range(n_blocks): # add ResNet blocks\n decoder += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n \n for i in range(n_downsampling): # add upsampling layers\n mult = 2 ** (n_downsampling - i)\n decoder += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n decoder += [nn.ReflectionPad2d(3)]\n decoder += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n decoder += [nn.Tanh()]\n\n self.encoder = nn.Sequential(*encoder)\n self.decoder = nn.Sequential(*decoder)\n\n def forward(self, input, style_label, auto=False, content_label=None):\n # input (N, C, H, W)\n # style_label (N, class)\n # return value: (N, whatever output shape)\n \"\"\"Standard forward\"\"\"\n encoded = self.encoder(input)\n batch_size, C, H, W = encoded.shape\n transformed = encoded\n if self.n_content:\n transformed = torch.stack([trans(transformed) for trans in self.content_transformers])\n transformed = torch.matmul(content_label.float().unsqueeze(1), transformed.view(self.n_content, batch_size, -1).transpose(0, 1)).squeeze(1).view(-1, C, H, W)\n transformed = torch.stack([trans(transformed) for trans in self.transformers])\n transformed = torch.matmul(style_label.float().unsqueeze(1), transformed.view(self.n_style, batch_size, -1).transpose(0, 1)).squeeze(1).view(-1, C, H, W)\n# if auto:\n# assert torch.equal(encoded, transformed)\n return self.decoder(transformed)\n\nclass ResnetGenerator(nn.Module):\n \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n \"\"\"\n\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):\n \"\"\"Construct a Resnet-based generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers\n n_blocks (int) -- the number of ResNet blocks\n padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero\n \"\"\"\n assert(n_blocks >= 0)\n super(ResnetGenerator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling): # add downsampling layers\n mult = 2 ** i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2 ** n_downsampling\n for i in range(n_blocks): # add ResNet blocks\n\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n for i in range(n_downsampling): # add upsampling layers\n mult = 2 ** (n_downsampling - i)\n model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n model += [nn.Tanh()]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n return self.model(input)\n\n\nclass ResnetBlock(nn.Module):\n \"\"\"Define a Resnet block\"\"\"\n\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n \"\"\"Initialize the Resnet block\n\n A resnet block is a conv block with skip connections\n We construct a conv block with build_conv_block function,\n and implement skip connections in <forward> function.\n Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf\n \"\"\"\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n \"\"\"Construct a convolutional block.\n\n Parameters:\n dim (int) -- the number of channels in the conv layer.\n padding_type (str) -- the name of padding layer: reflect | replicate | zero\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers.\n use_bias (bool) -- if the conv layer uses bias or not\n\n Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))\n \"\"\"\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n \"\"\"Forward function (with skip connections)\"\"\"\n out = x + self.conv_block(x) # add skip connections\n return out\n\n\nclass UnetGenerator(nn.Module):\n \"\"\"Create a Unet-based generator\"\"\"\n\n def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,\n image of size 128x128 will become of size 1x1 # at the bottleneck\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n\n We construct the U-Net from the innermost layer to the outermost layer.\n It is a recursive process.\n \"\"\"\n super(UnetGenerator, self).__init__()\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n # gradually reduce the number of filters from ngf * 8 to ngf\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n return self.model(input)\n\n\nclass UnetSkipConnectionBlock(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetSkipConnectionBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down + [submodule] + up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else: # add skip connections\n return torch.cat([x, self.model(x)], 1)\n\n\nclass NLayerDiscriminator(nn.Module):\n \"\"\"Defines a PatchGAN discriminator\"\"\"\n\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, input_nclass=None, input_ncontent=None):\n \"\"\"Construct a PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n n_layers (int) -- the number of conv layers in the discriminator\n norm_layer -- normalization layer\n \"\"\"\n super(NLayerDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func != nn.BatchNorm2d\n else:\n use_bias = norm_layer != nn.BatchNorm2d\n\n kw = 4\n padw = 1\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers): # gradually increase the number of filters\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n self.nclass= input_nclass\n self.ncontent = input_ncontent\n self.model = nn.Sequential(*sequence)\n self.prediction = nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw) # output 1 channel prediction map\n if input_nclass:\n self.classifier = nn.Conv2d(ndf * nf_mult, input_nclass + 1, kernel_size=kw, stride=1, padding=padw) # output n class channel prediction map\n if input_ncontent:\n self.content_classifier = nn.Conv2d(ndf * nf_mult, input_ncontent + 1, kernel_size=kw, stride=1, padding=padw) # output n content class channel prediction map\n\n def forward(self, input):\n \"\"\"Standard forward.\"\"\"\n final_layer = self.model(input)\n if self.nclass and self.ncontent:\n return self.prediction(final_layer), self.classifier(final_layer), self.content_classifier(final_layer)\n elif self.nclass:\n return self.prediction(final_layer), self.classifier(final_layer)\n else:\n return self.prediction(final_layer)\n\n\nclass PixelDiscriminator(nn.Module):\n \"\"\"Defines a 1x1 PatchGAN discriminator (pixelGAN)\"\"\"\n\n def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):\n \"\"\"Construct a 1x1 PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n \"\"\"\n super(PixelDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func != nn.InstanceNorm2d\n else:\n use_bias = norm_layer != nn.InstanceNorm2d\n\n self.net = [\n nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),\n norm_layer(ndf * 2),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]\n\n self.net = nn.Sequential(*self.net)\n\n def forward(self, input):\n \"\"\"Standard forward.\"\"\"\n return self.net(input)\n\n#https://discuss.pytorch.org/t/is-there-anyway-to-do-gaussian-filtering-for-an-image-2d-3d-in-pytorch/12351/10\nclass GaussianSmoothing(nn.Module):\n \"\"\"\n Apply gaussian smoothing on a\n 1d, 2d or 3d tensor. Filtering is performed seperately for each channel\n in the input using a depthwise convolution.\n Arguments:\n channels (int, sequence): Number of channels of the input tensors. Output will\n have this number of channels as well.\n kernel_size (int, sequence): Size of the gaussian kernel.\n sigma (float, sequence): Standard deviation of the gaussian kernel.\n dim (int, optional): The number of dimensions of the data.\n Default value is 2 (spatial).\n \"\"\"\n def __init__(self, channels, kernel_size, sigma, dim=2):\n super(GaussianSmoothing, self).__init__()\n if isinstance(kernel_size, numbers.Number):\n kernel_size = [kernel_size] * dim\n if isinstance(sigma, numbers.Number):\n sigma = [sigma] * dim\n\n # The gaussian kernel is the product of the\n # gaussian function of each dimension.\n kernel = 1\n meshgrids = torch.meshgrid(\n [\n torch.arange(size, dtype=torch.float32)\n for size in kernel_size\n ]\n )\n for size, std, mgrid in zip(kernel_size, sigma, meshgrids):\n mean = (size - 1) / 2\n kernel *= 1 / (std * math.sqrt(2 * math.pi)) * \\\n torch.exp(-((mgrid - mean) / std) ** 2 / 2)\n\n # Make sure sum of values in gaussian kernel equals 1.\n kernel = kernel / torch.sum(kernel)\n\n # Reshape to depthwise convolutional weight\n kernel = kernel.view(1, 1, *kernel.size())\n kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))\n\n self.register_buffer('weight', kernel)\n self.groups = channels\n\n if dim == 1:\n self.conv = F.conv1d\n elif dim == 2:\n self.conv = F.conv2d\n elif dim == 3:\n self.conv = F.conv3d\n else:\n raise RuntimeError(\n 'Only 1, 2 and 3 dimensions are supported. Received {}.'.format(dim)\n )\n\n def forward(self, input):\n \"\"\"\n Apply gaussian filter to input.\n Arguments:\n input (torch.Tensor): Input to apply gaussian filter on.\n Returns:\n filtered (torch.Tensor): Filtered output.\n \"\"\"\n return self.conv(input, weight=self.weight, groups=self.groups, padding=2)\n"
]
[
"#!/usr/bin/env python\nfrom __future__ import division\nimport numpy\nimport itertools\nfrom cogent.core.tree import TreeBuilder\nfrom cogent.phylo.tree_collection import ScoredTreeCollection\nfrom cogent.util import parallel, checkpointing, progress_display as UI\n\n__author__ = \"Peter Maxwell\"\n__copyright__ = \"Copyright 2007-2012, The Cogent Project\"\n__credits__ = [\"Peter Maxwell\"]\n__license__ = \"GPL\"\n__version__ = \"1.5.3\"\n__maintainer__ = \"Peter Maxwell\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n\n\ndef ismallest(data, size):\n \"\"\"There are many ways to get the k smallest items from an N sequence, and\n which one performs best depends on k, N and k/N. This algorithm appears to\n beat anything heapq can do, and stays with a factor of 2 of sort() and\n min(). Is uses memory O(2*k) and so is particularly suitable for lazy \n application to large N. It returns the smallest k sorted too.\"\"\"\n limit = 2 * size\n data = iter(data)\n best = list(itertools.islice(data, limit))\n while True:\n best.sort()\n if len(best) <= size:\n break\n del best[size:]\n worst_of_best = best[-1]\n for item in data:\n if item < worst_of_best:\n best.append(item)\n if len(best) > limit:\n break\n return best\n\n# Trees are represented as \"ancestry\" matricies in which A[i,j] iff j is an\n# ancestor of i. For LS calculations the ancestry matrix is converted\n# to a \"paths\" matrix or \"split metric\" in which S[p,j] iff the path between\n# the pth pair of tips passes through edge j. For ML calculations the\n# ancestry matrix is converted back into an ordinary cogent tree object.\n\ndef tree2ancestry(tree, order=None):\n nodes = tree.unrooted().getEdgeVector()[:-1]\n if order is not None:\n lookup = dict([(k,i) for (i,k) in enumerate(order)])\n def _ordered_tips_first(n):\n if n.Children:\n return len(order)\n else:\n return lookup[n.Name]\n nodes.sort(key=_ordered_tips_first)\n\n n = len(nodes)\n A = numpy.zeros([n, n], int)\n seen = {}\n for (i, node) in enumerate(nodes):\n A[i, i] = 1\n seen[id(node)] = i\n for c in node.Children:\n A[:,i] |= A[:,seen[id(c)]]\n names = [n.Name for n in nodes if not n.Children]\n lengths = [n.Length for n in nodes]\n return (A, names, lengths)\n\ndef ancestry2tree(A, lengths, tip_names):\n \"\"\"Convert edge x edge ancestry matrix to a cogent Tree object\"\"\"\n tips = {}\n tip = 0\n for i in range(len(A)):\n if numpy.sum(A[:,i]) == 1:\n tips[i] = tip_names[tip]\n tip += 1\n assert tip == len(tip_names)\n \n constructor = TreeBuilder().createEdge\n free = {}\n for i in numpy.argsort(numpy.sum(A, axis=0)):\n children = [j for j in range(len(A)) if A[j, i] and j != i]\n child_nodes = [free.pop(j) for j in children if j in free]\n if child_nodes:\n name = None\n else:\n name = tips[i]\n if lengths is None:\n params = {}\n else:\n params = {'length':lengths[i]}\n node = constructor(child_nodes, name, params)\n free[i] = node\n return constructor(free.values(), 'root', {})\n\ndef grown(B, split_edge):\n \"\"\"Ancestry matrix 'B' with one extra leaf added at 'split_edge'.\n Row/column order within the matrix is independent of the topology it \n represents. The added leaf will be the last one in the matrix, which keeps \n the leaf node order the same as the order in which they are added, which is \n what is assumed by ancestry2tree and ancestry2paths\"\"\"\n n = len(B)\n A = numpy.zeros([n+2, n+2], int)\n A[:n, :n] = B\n (sibling, parent) = (n, n + 1)\n A[sibling] = A[parent] = A[split_edge]\n A[:,parent] = A[:,split_edge]\n A[sibling,split_edge] = 0\n A[parent, split_edge] = 0\n A[sibling,sibling] = 1\n A[parent,parent] = 1\n A[sibling,parent] = 1\n A[split_edge,parent] = 1\n return A\n\nclass TreeEvaluator(object):\n \"\"\"Subclass must provide makeTreeScorer and result2output\"\"\"\n \n def results2output(self, results):\n return ScoredTreeCollection(results)\n \n def evaluateTopology(self, tree):\n \"\"\"Optimal (score, tree) for the one topology 'tree'\"\"\"\n (ancestry, names, lengths) = tree2ancestry(tree)\n evaluate = self.makeTreeScorer(names)\n (err, lengths) = evaluate(ancestry)\n return self.result2output(err, ancestry, lengths, names)\n \n def evaluateTree(self, tree):\n \"\"\"score for 'tree' with lengths as-is\"\"\"\n (ancestry, names, lengths) = tree2ancestry(tree)\n evaluate = self.makeTreeScorer(names)\n (err, result) = evaluate(ancestry, lengths=lengths)\n return err\n \n def _consistentNameOrder(self, fixed_names, ordered_names=None):\n \"\"\"fixed_names followed by ordered_names without duplicates\"\"\"\n all_names = set(self.names)\n\n fixed_names_set = set(fixed_names)\n assert fixed_names_set.issubset(all_names)\n\n if ordered_names:\n assert set(ordered_names).issubset(all_names)\n else:\n ordered_names = self.names\n names = list(fixed_names) + [n for n in ordered_names \n if n not in fixed_names_set]\n return names\n \n @UI.display_wrap\n def trex(self, a=8, k=1000, start=None, order=None, return_all=False, \n filename=None, interval=None, ui=None):\n \"\"\"TrexML policy for tree sampling - all trees up to size 'a' and\n then keep no more than 'k' best trees at each tree size.\n 'order' is an optional list of tip names. \n 'start' is an optional list of initial trees. Each of the trees must\n contain the same tips.\n 'filename' and 'interval' control checkpointing.\n \n Advanced step-wise addition algorithm\n M. J. Wolf, S. Easteal, M. Kahn, B. D. McKay, and L. S. Jermiin.\n Trexml: a maximum-likelihood approach for extensive tree-space\n exploration.\n Bioinformatics, 16(4):383 94, 2000.\"\"\"\n \n checkpointer = checkpointing.Checkpointer(filename, interval)\n if checkpointer.available():\n (init_tree_size, fixed_names, trees) = checkpointer.load()\n names = self._consistentNameOrder(fixed_names, order)\n elif start is not None:\n if not isinstance(start, list):\n start = [start]\n fixed_names = start[0].getTipNames()\n names = self._consistentNameOrder(fixed_names, order)\n trees = []\n for tree in start:\n # check the start tree represents a subset of tips\n assert set(tree.getTipNames()) < set(self.names), \\\n \"Starting tree names not a subset of the sequence names\"\n \n (ancestry, fixed_names2, lengths) = tree2ancestry(\n tree, order=fixed_names)\n assert fixed_names2 == fixed_names\n trees.append((None, None, ancestry))\n init_tree_size = len(fixed_names)\n else:\n trees = [(None, None, numpy.identity(3, int))]\n names = self._consistentNameOrder([], order)\n init_tree_size = 3\n \n tree_size = len(names)\n assert tree_size > 3\n if a > tree_size:\n a = tree_size\n if a < 4:\n a = 4\n\n # All trees of size a-1, no need to compare them\n for n in range(init_tree_size+1, a):\n trees2 = []\n for (err2, lengths2, ancestry) in trees:\n for split_edge in range(len(ancestry)):\n ancestry2 = grown(ancestry, split_edge)\n trees2.append((None, None, ancestry2))\n trees = trees2\n init_tree_size = n\n \n # Pre calculate how much work is to be done, for progress display\n tree_count = len(trees)\n total_work = 0\n work_done = [0] * (init_tree_size+1)\n for n in range(init_tree_size+1, tree_size+1):\n evals = tree_count * (n*2-5)\n total_work += evals * n\n tree_count = min(k, evals)\n work_done.append(total_work)\n \n # For each tree size, grow at each edge of each tree. Keep best k.\n for n in range(init_tree_size+1, tree_size+1):\n evaluate = self.makeTreeScorer(names[:n]) \n\n def grown_tree(spec):\n (tree_ordinal, tree, split_edge) = spec\n (old_err, old_lengths, old_ancestry) = tree\n ancestry = grown(old_ancestry, split_edge)\n (err, lengths) = evaluate(ancestry)\n return (err, tree_ordinal, split_edge, lengths, ancestry)\n \n specs = [(i, tree, edge) \n for (i,tree) in enumerate(trees) \n for edge in range(n*2-5)]\n\n candidates = ui.imap(grown_tree, specs, noun=('%s leaf tree' % n),\n start=work_done[n-1]/total_work, end=work_done[n]/total_work)\n \n best = ismallest(candidates, k)\n \n trees = [(err, lengths, ancestry) for (err, parent_ordinal, \n split_edge, lengths, ancestry) in best]\n \n checkpointer.record((n, names[:n], trees))\n \n results = (self.result2output(err, ancestry, lengths, names)\n for (err, lengths, ancestry) in trees)\n if return_all:\n result = self.results2output(results)\n else:\n result = results.next()\n return result\n \n"
]
[
"\"\"\"Conversion of the .npy weights into the .ckpt ones.\n\nThis script converts the weights of the DeepLab-ResNet model\nfrom the numpy format into the TensorFlow one.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport os\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom deeplab_resnet import DeepLabResNetModelOri50gcn\n\nSAVE_DIR = './'\n\n\ndef get_arguments():\n \"\"\"Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"NPY to CKPT converter.\")\n parser.add_argument(\"npy_path\", type=str,\n help=\"Path to the .npy file, which contains the weights.\")\n parser.add_argument(\"--save-dir\", type=str, default=SAVE_DIR,\n help=\"Where to save the converted .ckpt file.\")\n return parser.parse_args()\n\n\ndef save(saver, sess, logdir):\n model_name = 'init50gcn.ckpt'\n checkpoint_path = os.path.join(logdir, model_name)\n\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n\n saver.save(sess, checkpoint_path, write_meta_graph=False)\n print('The weights have been converted to {}.'.format(checkpoint_path))\n\n\ndef main():\n \"\"\"Create the model and start the training.\"\"\"\n args = get_arguments()\n\n # Default image.\n image_batch = tf.constant(0, tf.float32, shape=[1, 321, 321, 3])\n # Create network.\n net = DeepLabResNetModelOri50gcn({'data': image_batch})\n var_list = tf.global_variables()\n\n # Set up tf session and initialize variables.\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n with tf.Session(config=config) as sess:\n init = tf.global_variables_initializer()\n sess.run(init)\n\n # Loading .npy weights.\n with tf.variable_scope(tf.get_variable_scope(), reuse=None):\n net.load(args.npy_path, sess)\n\n # Saver for converting the loaded weights into .ckpt.\n saver = tf.train.Saver(var_list=var_list, write_version=1)\n save(saver, sess, args.save_dir)\n\n\nif __name__ == '__main__':\n main()\n"
]
[
"import numpy as np\nimport h5py as h5\n\n\ndef load_data_and_create_features( inputFile ):\n \"\"\"Function for loading the data for the galaxies and their satellite systems used to constrain the mass of the Milky Way by training various ML algorithms. This function also manipulates some of the feature by transforming them to log-space.\n \n INPUT:\n inputFile - the name of the data input file\n \n OUTPUT:\n data_input - a (N x m) numpy array giving the input 'm' features for the 'N' \n entries in the file\n data_output - a (N x 1) numpy array giving the target output for each entry\n name_input - the list of names for each feature in the input data\n name_output - the name of the output variable\n \"\"\"\n with h5.File( inputFile, 'r' ) as hf:\n mw_Mhalo = np.array( hf[\"M_halo\"] )\n mw_Mstar = np.array( hf[\"M_star\"] )\n mw_lum_func = np.array( hf[\"luminosity_function\"] )\n mw_vel_dis = np.array( hf[\"velocity_dispersion\"] )\n mw_vel_rad = np.array( hf[\"velocity_dispersion_radial\"] )\n mw_ang_mom = np.array( hf[\"mean_angular_momentum\"] )\n mw_dis = np.array( hf[\"mean_distance\"] )\n\n num_systems = mw_Mhalo.shape[0]\n num_features = 1 + mw_lum_func.shape[1] + 1*4\n\n print( \"The '%s' input file contains:\" % inputFile )\n print( \"MW-analogues: %i\" % mw_Mhalo.shape[0] )\n\n\n # transform the masses, velocity dispersion and angular momentum to log values\n mw_Mhalo = np.log10(mw_Mhalo)\n \n mw_Mstar = np.log10(mw_Mstar)\n mw_Mstar[mw_Mstar<8.] = 8. # get rid of the tail -- very few entries have these values\n \n # calculate the PDF of the luminosity function\n # (the file contains the CDF)\n for i in range(mw_lum_func.shape[1]-1):\n mw_lum_func[:,i] -= mw_lum_func[:,i+1]\n \n # calculate the tangetial velocity dispersion\n mw_vel_dis -= mw_vel_rad\n \n sel = mw_vel_dis > 100. # all the systems with valid values\n mw_vel_dis[ sel] = np.log10(mw_vel_dis[sel])\n mw_vel_dis[~sel] = np.log10(100.)\n\n sel = mw_vel_rad > 100. # all the systems with valid values\n mw_vel_rad[ sel] = np.log10(mw_vel_rad[sel])\n mw_vel_rad[~sel] = np.log10(100.)\n\n sel = mw_ang_mom > 1 # all the systems with valid values\n mw_ang_mom[ sel] = np.log10(mw_ang_mom[sel])\n mw_ang_mom[~sel] = 0.\n\n\n # define lists storing the name of each feature\n name_input = [ \"M_star\", \"N_sat 1.e6\", \"N_sat 1.e7\", \"N_sat 1.e8\", \"N_sat 1.e9\", \"N_sat 1.e10\", \n \"vel. tan.\", \"vel. radial\", \"mean L\", \"mean d\"\n ]\n name_output = [ \"M_halo\" ]\n\n # merge the input and output features in two different array\n data_input = np.column_stack( ( mw_Mstar,mw_lum_func, mw_vel_dis, mw_vel_rad, mw_ang_mom, mw_dis) )\n data_output= mw_Mhalo.reshape(-1,1)\n \n return data_input, data_output, name_input, name_output "
]
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# pylint: disable=protected-access\n\"\"\"Contains the base Layer class, from which all layers inherit.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport functools\nimport itertools\nimport threading\nimport weakref\n\nimport numpy as np\nimport six\nfrom six.moves import zip # pylint: disable=redefined-builtin\n\nfrom google.protobuf import json_format\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.python import tf2\nfrom tensorflow.python.autograph.core import ag_ctx\nfrom tensorflow.python.autograph.impl import api as autograph\nfrom tensorflow.python.distribute import distribution_strategy_context as ds_context\nfrom tensorflow.python.distribute import sharded_variable\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import execute\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.eager import monitoring\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import func_graph\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras import constraints\nfrom tensorflow.python.keras import initializers\nfrom tensorflow.python.keras import regularizers\nfrom tensorflow.python.keras.engine import base_layer_utils\nfrom tensorflow.python.keras.engine import input_spec\nfrom tensorflow.python.keras.engine import keras_tensor\nfrom tensorflow.python.keras.engine import node as node_module\nfrom tensorflow.python.keras.mixed_precision.experimental import autocast_variable\nfrom tensorflow.python.keras.mixed_precision.experimental import loss_scale_optimizer\nfrom tensorflow.python.keras.mixed_precision.experimental import policy\nfrom tensorflow.python.keras.saving.saved_model import layer_serialization\nfrom tensorflow.python.keras.utils import generic_utils\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.keras.utils import version_utils\n# A module that only depends on `keras.layers` import these from here.\nfrom tensorflow.python.keras.utils.generic_utils import to_snake_case # pylint: disable=unused-import\nfrom tensorflow.python.keras.utils.tf_utils import is_tensor_or_tensor_list # pylint: disable=unused-import\nfrom tensorflow.python.module import module\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables as tf_variables\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.platform import tf_logging\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.training.tracking import data_structures\nfrom tensorflow.python.training.tracking import layer_utils as trackable_layer_utils\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import object_identity\nfrom tensorflow.python.util import tf_inspect\nfrom tensorflow.python.util.tf_export import keras_export\nfrom tensorflow.tools.docs import doc_controls\n\n# Prefix that is added to the TF op layer names.\n_TF_OP_LAYER_NAME_PREFIX = 'tf_op_layer_'\n\n# TODO(mdan): Should we have a single generic type for types that can be passed\n# to tf.cast?\n_AUTOCAST_TYPES = (ops.Tensor, sparse_tensor.SparseTensor,\n ragged_tensor.RaggedTensor)\n\n_keras_layers_gauge = monitoring.BoolGauge('/tensorflow/api/keras/layers',\n 'keras layers usage', 'method')\n_keras_model_gauge = monitoring.BoolGauge(\n '/tensorflow/api/keras/premade_models', 'premade keras model usage', 'type')\n\n\n@keras_export('keras.layers.Layer')\nclass Layer(module.Module, version_utils.LayerVersionSelector):\n \"\"\"This is the class from which all layers inherit.\n\n A layer is a callable object that takes as input one or more tensors and\n that outputs one or more tensors. It involves *computation*, defined\n in the `call()` method, and a *state* (weight variables), defined\n either in the constructor `__init__()` or in the `build()` method.\n\n Users will just instantiate a layer and then treat it as a callable.\n\n Arguments:\n trainable: Boolean, whether the layer's variables should be trainable.\n name: String name of the layer.\n dtype: The dtype of the layer's computations and weights (default of\n `None` means use `tf.keras.backend.floatx` in TensorFlow 2, or the type\n of the first input in TensorFlow 1).\n dynamic: Set this to `True` if your layer should only be run eagerly, and\n should not be used to generate a static computation graph.\n This would be the case for a Tree-RNN or a recursive network,\n for example, or generally for any layer that manipulates tensors\n using Python control flow. If `False`, we assume that the layer can\n safely be used to generate a static computation graph.\n\n Attributes:\n name: The name of the layer (string).\n dtype: The dtype of the layer's computations and weights. If mixed\n precision is used with a `tf.keras.mixed_precision.experimental.Policy`,\n this is instead just the dtype of the layer's weights, as the computations\n are done in a different dtype.\n trainable_weights: List of variables to be included in backprop.\n non_trainable_weights: List of variables that should not be\n included in backprop.\n weights: The concatenation of the lists trainable_weights and\n non_trainable_weights (in this order).\n trainable: Whether the layer should be trained (boolean), i.e. whether\n its potentially-trainable weights should be returned as part of\n `layer.trainable_weights`.\n input_spec: Optional (list of) `InputSpec` object(s) specifying the\n constraints on inputs that can be accepted by the layer.\n\n We recommend that descendants of `Layer` implement the following methods:\n\n * `__init__()`: Defines custom layer attributes, and creates layer state\n variables that do not depend on input shapes, using `add_weight()`.\n * `build(self, input_shape)`: This method can be used to create weights that\n depend on the shape(s) of the input(s), using `add_weight()`. `__call__()`\n will automatically build the layer (if it has not been built yet) by\n calling `build()`.\n * `call(self, *args, **kwargs)`: Called in `__call__` after making sure\n `build()` has been called. `call()` performs the logic of applying the\n layer to the input tensors (which should be passed in as argument).\n Two reserved keyword arguments you can optionally use in `call()` are:\n - `training` (boolean, whether the call is in\n inference mode or training mode)\n - `mask` (boolean tensor encoding masked timesteps in the input, used\n in RNN layers)\n * `get_config(self)`: Returns a dictionary containing the configuration used\n to initialize this layer. If the keys differ from the arguments\n in `__init__`, then override `from_config(self)` as well.\n This method is used when saving\n the layer or a model that contains this layer.\n\n Examples:\n\n Here's a basic example: a layer with two variables, `w` and `b`,\n that returns `y = w . x + b`.\n It shows how to implement `build()` and `call()`.\n Variables set as attributes of a layer are tracked as weights\n of the layers (in `layer.weights`).\n\n ```python\n class SimpleDense(Layer):\n\n def __init__(self, units=32):\n super(SimpleDense, self).__init__()\n self.units = units\n\n def build(self, input_shape): # Create the state of the layer (weights)\n w_init = tf.random_normal_initializer()\n self.w = tf.Variable(\n initial_value=w_init(shape=(input_shape[-1], self.units),\n dtype='float32'),\n trainable=True)\n b_init = tf.zeros_initializer()\n self.b = tf.Variable(\n initial_value=b_init(shape=(self.units,), dtype='float32'),\n trainable=True)\n\n def call(self, inputs): # Defines the computation from inputs to outputs\n return tf.matmul(inputs, self.w) + self.b\n\n # Instantiates the layer.\n linear_layer = SimpleDense(4)\n\n # This will also call `build(input_shape)` and create the weights.\n y = linear_layer(tf.ones((2, 2)))\n assert len(linear_layer.weights) == 2\n\n # These weights are trainable, so they're listed in `trainable_weights`:\n assert len(linear_layer.trainable_weights) == 2\n ```\n\n Note that the method `add_weight()` offers a shortcut to create weights:\n\n ```python\n class SimpleDense(Layer):\n\n def __init__(self, units=32):\n super(SimpleDense, self).__init__()\n self.units = units\n\n def build(self, input_shape):\n self.w = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='random_normal',\n trainable=True)\n self.b = self.add_weight(shape=(self.units,),\n initializer='random_normal',\n trainable=True)\n\n def call(self, inputs):\n return tf.matmul(inputs, self.w) + self.b\n ```\n\n Besides trainable weights, updated via backpropagation during training,\n layers can also have non-trainable weights. These weights are meant to\n be updated manually during `call()`. Here's a example layer that computes\n the running sum of its inputs:\n\n ```python\n class ComputeSum(Layer):\n\n def __init__(self, input_dim):\n super(ComputeSum, self).__init__()\n # Create a non-trainable weight.\n self.total = tf.Variable(initial_value=tf.zeros((input_dim,)),\n trainable=False)\n\n def call(self, inputs):\n self.total.assign_add(tf.reduce_sum(inputs, axis=0))\n return self.total\n\n my_sum = ComputeSum(2)\n x = tf.ones((2, 2))\n\n y = my_sum(x)\n print(y.numpy()) # [2. 2.]\n\n y = my_sum(x)\n print(y.numpy()) # [4. 4.]\n\n assert my_sum.weights == [my_sum.total]\n assert my_sum.non_trainable_weights == [my_sum.total]\n assert my_sum.trainable_weights == []\n ```\n\n For more information about creating layers, see the guide\n [Writing custom layers and models with Keras](\n https://www.tensorflow.org/guide/keras/custom_layers_and_models)\n\n About the layer's `dtype` attribute:\n\n Each layer has a dtype, which is typically the dtype of the layer's\n computations and variables. A layer's dtype can be queried via the\n `Layer.dtype` property. The dtype is specified with the `dtype` constructor\n argument. In TensorFlow 2, the dtype defaults to `tf.keras.backend.floatx()`\n if no dtype is passed. `floatx()` itself defaults to \"float32\". Additionally,\n layers will cast their inputs to the layer's dtype in TensorFlow 2. When mixed\n precision is used, layers may have different computation and variable dtypes.\n See `tf.keras.mixed_precision.experimental.Policy` for details on layer\n dtypes.\n \"\"\"\n\n # See tf.Module for the usage of this property.\n # The key for _obj_reference_counts_dict is a Trackable, which could be a\n # variable or layer etc. tf.Module._flatten will fail to flatten the key\n # since it is trying to convert Trackable to a string. This attribute can be\n # ignored even after the fix of nest lib, since the trackable object should\n # already been available as individual attributes. _obj_reference_counts_dict\n # just contains a copy of them.\n _TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain(\n ('_obj_reference_counts_dict',),\n module.Module._TF_MODULE_IGNORED_PROPERTIES\n ))\n\n # When loading from a SavedModel, Layers typically can be revived into a\n # generic Layer wrapper. Sometimes, however, layers may implement methods\n # that go beyond this wrapper, as in the case of PreprocessingLayers'\n # `adapt` method. When this is the case, layer implementers can override\n # must_restore_from_config to return True; layers with this property must\n # be restored into their actual objects (and will fail if the object is\n # not available to the restoration code).\n _must_restore_from_config = False\n\n @trackable.no_automatic_dependency_tracking\n def __init__(self,\n trainable=True,\n name=None,\n dtype=None,\n dynamic=False,\n **kwargs):\n # These properties should be set by the user via keyword arguments.\n # note that 'dtype', 'input_shape' and 'batch_input_shape'\n # are only applicable to input layers: do not pass these keywords\n # to non-input layers.\n allowed_kwargs = {\n 'input_dim',\n 'input_shape',\n 'batch_input_shape',\n 'batch_size',\n 'weights',\n 'activity_regularizer',\n 'autocast',\n }\n # Validate optional keyword arguments.\n generic_utils.validate_kwargs(kwargs, allowed_kwargs)\n\n # Mutable properties\n # Indicates whether the layer's weights are updated during training\n # and whether the layer's updates are run during training.\n self._trainable = trainable\n # A stateful layer is a layer whose updates are run during inference too,\n # for instance stateful RNNs.\n self._stateful = False\n # Indicates whether `build` needs to be called upon layer call, to create\n # the layer's weights.\n self.built = False\n # Record the build input shape for loading purposes.\n # TODO(kathywu): Move this to Layer._set_save_spec once cl/290121460 is\n # submitted.\n self._build_input_shape = None\n self._saved_model_inputs_spec = None\n # Provides information about which inputs are compatible with the layer.\n self._input_spec = None\n\n # `Layer.compute_mask` will be called at the end of `Layer.__call__` if\n # `Layer.compute_mask` is overridden, or if the `Layer` subclass sets\n # `self.supports_masking=True`.\n self._supports_masking = not generic_utils.is_default(self.compute_mask)\n\n self._init_set_name(name)\n self._activity_regularizer = regularizers.get(\n kwargs.pop('activity_regularizer', None))\n self._maybe_create_attribute('_trainable_weights', [])\n self._maybe_create_attribute('_non_trainable_weights', [])\n self._updates = []\n # Object to store all thread local layer properties.\n self._thread_local = threading.local()\n # A list of zero-argument lambdas which return Tensors, used for variable\n # regularizers.\n self._callable_losses = []\n # A list of symbolic Tensors containing activity regularizers and losses\n # manually added through `add_loss` in graph-building mode.\n self._losses = []\n # A list of metric instances corresponding to the symbolic metric tensors\n # added using the `add_metric` API.\n self._metrics = []\n # Ensures the same metric is not added multiple times in `MirroredStrategy`.\n self._metrics_lock = threading.Lock()\n\n # Both graph and subclassed networks have a dtype policy. For graph\n # networks, the policy's compute and variable dtypes are ignored, but other\n # fields, like the loss scale, are used by Models. For subclassed networks,\n # the compute and variable dtypes are used as like any ordinary layer.\n self._set_dtype_policy(dtype)\n # Boolean indicating whether the layer automatically casts its inputs to the\n # layer's compute_dtype.\n self._autocast = kwargs.get('autocast',\n base_layer_utils.v2_dtype_behavior_enabled())\n\n # Dependencies tracked via attribute assignment.\n # All layers in order of horizontal graph traversal.\n # Entries are unique. For models includes input and output layers.\n self._maybe_create_attribute('_layers', [])\n\n # These lists will be filled via successive calls\n # to self._add_inbound_node().\n # Used in symbolic mode only, only in conjunction with graph-networks\n self._inbound_nodes = []\n self._outbound_nodes = []\n\n self._init_call_fn_args()\n\n # Whether the `call` method can be used to build a TF graph without issues.\n # This attribute has no effect if the model is created using the Functional\n # API. Instead, `model.dynamic` is determined based on the internal layers.\n self._dynamic = dynamic\n\n # Manage input shape information if passed.\n if 'input_dim' in kwargs and 'input_shape' not in kwargs:\n # Backwards compatibility: alias 'input_dim' to 'input_shape'.\n kwargs['input_shape'] = (kwargs['input_dim'],)\n if 'input_shape' in kwargs or 'batch_input_shape' in kwargs:\n # In this case we will later create an input layer\n # to insert before the current layer\n if 'batch_input_shape' in kwargs:\n batch_input_shape = tuple(kwargs['batch_input_shape'])\n elif 'input_shape' in kwargs:\n if 'batch_size' in kwargs:\n batch_size = kwargs['batch_size']\n else:\n batch_size = None\n batch_input_shape = (batch_size,) + tuple(kwargs['input_shape'])\n self._batch_input_shape = batch_input_shape\n\n # Manage initial weight values if passed.\n self._initial_weights = kwargs.get('weights', None)\n\n # Whether the layer will track any layers that is set as attribute on itself\n # as sub-layers, the weights from the sub-layers will be included in the\n # parent layer's variables() as well.\n # Default to True, which means auto tracking is turned on. Certain subclass\n # might want to turn it off, like Sequential model.\n self._auto_track_sub_layers = True\n\n @trackable.no_automatic_dependency_tracking\n @generic_utils.default\n def build(self, input_shape):\n \"\"\"Creates the variables of the layer (optional, for subclass implementers).\n\n This is a method that implementers of subclasses of `Layer` or `Model`\n can override if they need a state-creation step in-between\n layer instantiation and layer call.\n\n This is typically used to create the weights of `Layer` subclasses.\n\n Arguments:\n input_shape: Instance of `TensorShape`, or list of instances of\n `TensorShape` if the layer expects a list of inputs\n (one instance per input).\n \"\"\"\n # Only record the build input shapes of overridden build methods.\n if not hasattr(self.build, '_is_default'):\n self._build_input_shape = input_shape\n self.built = True\n\n @doc_controls.for_subclass_implementers\n def call(self, inputs, **kwargs): # pylint: disable=unused-argument\n \"\"\"This is where the layer's logic lives.\n\n Note here that `call()` method in `tf.keras` is little bit different\n from `keras` API. In `keras` API, you can pass support masking for\n layers as additional arguments. Whereas `tf.keras` has `compute_mask()`\n method to support masking.\n\n Arguments:\n inputs: Input tensor, or list/tuple of input tensors.\n **kwargs: Additional keyword arguments. Currently unused.\n\n Returns:\n A tensor or list/tuple of tensors.\n \"\"\"\n return inputs\n\n @doc_controls.for_subclass_implementers\n def _add_trackable(self, trackable_object, trainable):\n \"\"\"Adds a Trackable object to this layer's state.\n\n Arguments:\n trackable_object: The tf.tracking.Trackable object to add.\n trainable: Boolean, whether the variable should be part of the layer's\n \"trainable_variables\" (e.g. variables, biases) or\n \"non_trainable_variables\" (e.g. BatchNorm mean and variance).\n\n Returns:\n The TrackableWeightHandler used to track this object.\n \"\"\"\n handler = base_layer_utils.TrackableWeightHandler(trackable_object)\n if trainable:\n self._trainable_weights.append(handler)\n else:\n self._non_trainable_weights.append(handler)\n return handler\n\n @doc_controls.for_subclass_implementers\n def add_weight(self,\n name=None,\n shape=None,\n dtype=None,\n initializer=None,\n regularizer=None,\n trainable=None,\n constraint=None,\n partitioner=None,\n use_resource=None,\n synchronization=tf_variables.VariableSynchronization.AUTO,\n aggregation=tf_variables.VariableAggregation.NONE,\n **kwargs):\n \"\"\"Adds a new variable to the layer.\n\n Arguments:\n name: Variable name.\n shape: Variable shape. Defaults to scalar if unspecified.\n dtype: The type of the variable. Defaults to `self.dtype` or `float32`.\n initializer: Initializer instance (callable).\n regularizer: Regularizer instance (callable).\n trainable: Boolean, whether the variable should be part of the layer's\n \"trainable_variables\" (e.g. variables, biases)\n or \"non_trainable_variables\" (e.g. BatchNorm mean and variance).\n Note that `trainable` cannot be `True` if `synchronization`\n is set to `ON_READ`.\n constraint: Constraint instance (callable).\n partitioner: Partitioner to be passed to the `Trackable` API.\n use_resource: Whether to use `ResourceVariable`.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses\n when to synchronize. If `synchronization` is set to `ON_READ`,\n `trainable` must not be set to `True`.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n **kwargs: Additional keyword arguments. Accepted values are `getter`,\n `collections`, `experimental_autocast` and `caching_device`.\n\n Returns:\n The created variable. Usually either a `Variable` or `ResourceVariable`\n instance. If `partitioner` is not `None`, a `PartitionedVariable`\n instance is returned.\n\n Raises:\n RuntimeError: If called with partitioned variable regularization and\n eager execution is enabled.\n ValueError: When giving unsupported dtype and no initializer or when\n trainable has been set to True with synchronization set as `ON_READ`.\n \"\"\"\n if shape is None:\n shape = ()\n # Validate optional keyword arguments.\n for kwarg in kwargs:\n if kwarg not in ['getter', 'collections', 'experimental_autocast',\n 'caching_device']:\n raise TypeError('Unknown keyword argument:', kwarg)\n getter = kwargs.pop('getter', base_layer_utils.make_variable)\n collections_arg = kwargs.pop('collections', None)\n # 'experimental_autocast' can be set to False by the caller to indicate an\n # AutoCastVariable should never be created.\n autocast = kwargs.pop('experimental_autocast', True)\n # See the docstring for tf.Variable about the details for caching_device.\n caching_device = kwargs.pop('caching_device', None)\n\n if dtype is None:\n dtype = self.dtype or backend.floatx()\n dtype = dtypes.as_dtype(dtype)\n if self._dtype_policy.variable_dtype is None:\n # The policy is \"_infer\", so we infer the policy from the variable dtype.\n self._set_dtype_policy(policy.Policy(dtype.base_dtype.name))\n initializer = initializers.get(initializer)\n regularizer = regularizers.get(regularizer)\n constraint = constraints.get(constraint)\n\n if synchronization == tf_variables.VariableSynchronization.ON_READ:\n if trainable:\n raise ValueError(\n 'Synchronization value can be set to '\n 'VariableSynchronization.ON_READ only for non-trainable variables. '\n 'You have specified trainable=True and '\n 'synchronization=VariableSynchronization.ON_READ.')\n else:\n # Set trainable to be false when variable is to be synced on read.\n trainable = False\n elif trainable is None:\n trainable = True\n\n # Initialize variable when no initializer provided\n if initializer is None:\n # If dtype is DT_FLOAT, provide a uniform unit scaling initializer\n if dtype.is_floating:\n initializer = initializers.get('glorot_uniform')\n # If dtype is DT_INT/DT_UINT, provide a default value `zero`\n # If dtype is DT_BOOL, provide a default value `FALSE`\n elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool:\n initializer = initializers.get('zeros')\n # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here?\n else:\n raise ValueError('An initializer for variable %s of type %s is required'\n ' for layer %s' % (name, dtype.base_dtype, self.name))\n\n if (autocast and self._dtype_policy.should_cast_variables and\n dtype.is_floating):\n # Wrap 'getter' with a version that returns an AutoCastVariable.\n old_getter = getter\n def getter(*args, **kwargs): # pylint: disable=function-redefined\n variable = old_getter(*args, **kwargs)\n return autocast_variable.create_autocast_variable(variable)\n # Also the caching_device does not work with the mixed precision API,\n # disable it if it is specified.\n # TODO(b/142020079): Reenable it once the bug is fixed.\n if caching_device is not None:\n tf_logging.warn('`caching_device` does not work with mixed precision '\n 'API. Ignoring user specified `caching_device`.')\n caching_device = None\n\n variable = self._add_variable_with_custom_getter(\n name=name,\n shape=shape,\n # TODO(allenl): a `make_variable` equivalent should be added as a\n # `Trackable` method.\n getter=getter,\n # Manage errors in Layer rather than Trackable.\n overwrite=True,\n initializer=initializer,\n dtype=dtype,\n constraint=constraint,\n trainable=trainable,\n partitioner=partitioner,\n use_resource=use_resource,\n collections=collections_arg,\n synchronization=synchronization,\n aggregation=aggregation,\n caching_device=caching_device)\n if regularizer is not None:\n # TODO(fchollet): in the future, this should be handled at the\n # level of variable creation, and weight regularization losses\n # should be variable attributes.\n name_in_scope = variable.name[:variable.name.find(':')]\n self._handle_weight_regularization(name_in_scope,\n variable,\n regularizer)\n if isinstance(\n variable,\n (tf_variables.PartitionedVariable, sharded_variable.ShardedVariable)):\n for v in variable:\n backend.track_variable(v)\n if trainable:\n self._trainable_weights.append(v)\n else:\n self._non_trainable_weights.append(v)\n else:\n backend.track_variable(variable)\n if trainable:\n self._trainable_weights.append(variable)\n else:\n self._non_trainable_weights.append(variable)\n return variable\n\n @generic_utils.default\n def get_config(self):\n \"\"\"Returns the config of the layer.\n\n A layer config is a Python dictionary (serializable)\n containing the configuration of a layer.\n The same layer can be reinstantiated later\n (without its trained weights) from this configuration.\n\n The config of a layer does not include connectivity\n information, nor the layer class name. These are handled\n by `Network` (one layer of abstraction above).\n\n Returns:\n Python dictionary.\n \"\"\"\n all_args = tf_inspect.getfullargspec(self.__init__).args\n config = {\n 'name': self.name,\n 'trainable': self.trainable,\n }\n if hasattr(self, '_batch_input_shape'):\n config['batch_input_shape'] = self._batch_input_shape\n config['dtype'] = policy.serialize(self._dtype_policy)\n if hasattr(self, 'dynamic'):\n # Only include `dynamic` in the `config` if it is `True`\n if self.dynamic:\n config['dynamic'] = self.dynamic\n elif 'dynamic' in all_args:\n all_args.remove('dynamic')\n expected_args = config.keys()\n # Finds all arguments in the `__init__` that are not in the config:\n extra_args = [arg for arg in all_args if arg not in expected_args]\n # Check that either the only argument in the `__init__` is `self`,\n # or that `get_config` has been overridden:\n if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'):\n raise NotImplementedError('Layer %s has arguments in `__init__` and '\n 'therefore must override `get_config`.' %\n self.__class__.__name__)\n return config\n\n @classmethod\n def from_config(cls, config):\n \"\"\"Creates a layer from its config.\n\n This method is the reverse of `get_config`,\n capable of instantiating the same layer from the config\n dictionary. It does not handle layer connectivity\n (handled by Network), nor weights (handled by `set_weights`).\n\n Arguments:\n config: A Python dictionary, typically the\n output of get_config.\n\n Returns:\n A layer instance.\n \"\"\"\n return cls(**config)\n\n def compute_output_shape(self, input_shape):\n \"\"\"Computes the output shape of the layer.\n\n If the layer has not been built, this method will call `build` on the\n layer. This assumes that the layer will later be used with inputs that\n match the input shape provided here.\n\n Arguments:\n input_shape: Shape tuple (tuple of integers)\n or list of shape tuples (one per output tensor of the layer).\n Shape tuples can include None for free dimensions,\n instead of an integer.\n\n Returns:\n An input shape tuple.\n \"\"\"\n if context.executing_eagerly():\n # In this case we build the model first in order to do shape inference.\n # This is acceptable because the framework only calls\n # `compute_output_shape` on shape values that the layer would later be\n # built for. It would however cause issues in case a user attempts to\n # use `compute_output_shape` manually with shapes that are incompatible\n # with the shape the Layer will be called on (these users will have to\n # implement `compute_output_shape` themselves).\n self._maybe_build(input_shape)\n with func_graph.FuncGraph(str(self.name) + '_scratch_graph').as_default():\n input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False)\n def _make_placeholder_like(shape):\n ph = backend.placeholder(shape=shape, dtype=self.dtype)\n ph._keras_mask = None\n return ph\n inputs = nest.map_structure(_make_placeholder_like, input_shape)\n try:\n outputs = self(inputs, training=False)\n except TypeError as e:\n six.raise_from(\n NotImplementedError(\n 'We could not automatically infer the static shape of the '\n 'layer\\'s output. Please implement the '\n '`compute_output_shape` method on your layer (%s).' %\n self.__class__.__name__), e)\n return nest.map_structure(lambda t: t.shape, outputs)\n raise NotImplementedError\n\n @doc_controls.for_subclass_implementers\n def compute_output_signature(self, input_signature):\n \"\"\"Compute the output tensor signature of the layer based on the inputs.\n\n Unlike a TensorShape object, a TensorSpec object contains both shape\n and dtype information for a tensor. This method allows layers to provide\n output dtype information if it is different from the input dtype.\n For any layer that doesn't implement this function,\n the framework will fall back to use `compute_output_shape`, and will\n assume that the output dtype matches the input dtype.\n\n Args:\n input_signature: Single TensorSpec or nested structure of TensorSpec\n objects, describing a candidate input for the layer.\n\n Returns:\n Single TensorSpec or nested structure of TensorSpec objects, describing\n how the layer would transform the provided input.\n\n Raises:\n TypeError: If input_signature contains a non-TensorSpec object.\n \"\"\"\n def check_type_return_shape(s):\n if not isinstance(s, tensor_spec.TensorSpec):\n raise TypeError(\n 'Only TensorSpec signature types are supported, '\n 'but saw signature signature entry: {}.'.format(s))\n return s.shape\n input_shape = nest.map_structure(check_type_return_shape, input_signature)\n output_shape = self.compute_output_shape(input_shape)\n dtype = self._compute_dtype\n if dtype is None:\n input_dtypes = [s.dtype for s in nest.flatten(input_signature)]\n # Default behavior when self.dtype is None, is to use the first input's\n # dtype.\n dtype = input_dtypes[0]\n return nest.map_structure(\n lambda s: tensor_spec.TensorSpec(dtype=dtype, shape=s),\n output_shape)\n\n def _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs):\n if self.dynamic:\n # We will use static shape inference to return symbolic tensors\n # matching the specifications of the layer outputs.\n # Since `self.dynamic` is True, we will never attempt to\n # run the underlying TF graph (which is disconnected).\n # TODO(fchollet): consider py_func as an alternative, which\n # would enable us to run the underlying graph if needed.\n input_signature = nest.map_structure(\n lambda x: tensor_spec.TensorSpec(shape=x.shape, dtype=x.dtype),\n inputs)\n output_signature = self.compute_output_signature(input_signature)\n return nest.map_structure(keras_tensor.KerasTensor, output_signature)\n else:\n return self._infer_output_signature(inputs, args, kwargs, input_masks)\n\n def _infer_output_signature(self, inputs, args, kwargs, input_masks):\n \"\"\"TODO(kaftan): Docstring.\"\"\"\n\n call_fn = self.call\n # Wrapping `call` function in autograph to allow for dynamic control\n # flow and control dependencies in call. We are limiting this to\n # subclassed layers as autograph is strictly needed only for\n # subclassed layers and models.\n # tf_convert will respect the value of autograph setting in the\n # enclosing tf.function, if any.\n if (base_layer_utils.is_subclassed(self) and\n not base_layer_utils.from_saved_model(self)):\n call_fn = autograph.tf_convert(self.call, ag_ctx.control_status_ctx())\n\n # We enter a scratch graph and build placeholder inputs inside of it that\n # match the input args.\n # We then call the layer inside of the scratch graph to identify the\n # output signatures, then we build KerasTensors corresponding to those\n # outputs.\n scratch_graph = func_graph.FuncGraph(str(self.name) + '_scratch_graph')\n with scratch_graph.as_default():\n inputs = nest.map_structure(\n keras_tensor.keras_tensor_to_placeholder, inputs)\n args = nest.map_structure(\n keras_tensor.keras_tensor_to_placeholder, args)\n kwargs = nest.map_structure(\n keras_tensor.keras_tensor_to_placeholder, kwargs)\n input_masks = nest.map_structure(\n keras_tensor.keras_tensor_to_placeholder, input_masks)\n\n inputs = self._maybe_cast_inputs(inputs)\n\n # try:\n with backend.name_scope(self._name_scope()):\n with ops.enable_auto_cast_variables(self._compute_dtype_object):\n # Build layer if applicable (if the `build` method has been\n # overridden).\n # TODO(kaftan): do we maybe_build here, or have we already done it?\n self._maybe_build(inputs)\n outputs = call_fn(inputs, *args, **kwargs)\n\n self._handle_activity_regularization(inputs, outputs)\n self._set_mask_metadata(inputs, outputs, input_masks,\n build_graph=False)\n\n outputs = nest.map_structure(keras_tensor.keras_tensor_from_tensor, outputs)\n if hasattr(self, '_set_inputs') and not self.inputs:\n # TODO(kaftan): figure out if we ned to do this at all\n # Subclassed network: explicitly set metadata normally set by\n # a call to self._set_inputs().\n self._set_inputs(inputs, outputs)\n del scratch_graph\n return outputs\n\n @generic_utils.default\n def compute_mask(self, inputs, mask=None): # pylint: disable=unused-argument\n \"\"\"Computes an output mask tensor.\n\n Arguments:\n inputs: Tensor or list of tensors.\n mask: Tensor or list of tensors.\n\n Returns:\n None or a tensor (or list of tensors,\n one per output tensor of the layer).\n \"\"\"\n if not self._supports_masking:\n if any(m is not None for m in nest.flatten(mask)):\n raise TypeError('Layer ' + self.name + ' does not support masking, '\n 'but was passed an input_mask: ' + str(mask))\n # masking not explicitly supported: return None as mask.\n return None\n # if masking is explicitly supported, by default\n # carry over the input mask\n return mask\n\n def __call__(self, *args, **kwargs):\n \"\"\"Wraps `call`, applying pre- and post-processing steps.\n\n Arguments:\n *args: Positional arguments to be passed to `self.call`.\n **kwargs: Keyword arguments to be passed to `self.call`.\n\n Returns:\n Output tensor(s).\n\n Note:\n - The following optional keyword arguments are reserved for specific uses:\n * `training`: Boolean scalar tensor of Python boolean indicating\n whether the `call` is meant for training or inference.\n * `mask`: Boolean input mask.\n - If the layer's `call` method takes a `mask` argument (as some Keras\n layers do), its default value will be set to the mask generated\n for `inputs` by the previous layer (if `input` did come from\n a layer that generated a corresponding mask, i.e. if it came from\n a Keras layer with masking support.\n\n Raises:\n ValueError: if the layer's `call` method returns None (an invalid value).\n RuntimeError: if `super().__init__()` was not called in the constructor.\n \"\"\"\n if not hasattr(self, '_thread_local'):\n raise RuntimeError(\n 'You must call `super().__init__()` in the layer constructor.')\n\n # `inputs` (the first arg in the method spec) is special cased in\n # layer call due to historical reasons.\n # This special casing currently takes the form of:\n # - 'inputs' must be explicitly passed. A layer cannot have zero arguments,\n # and inputs cannot have been provided via the default value of a kwarg.\n # - numpy/scalar values in `inputs` get converted to tensors\n # - implicit masks / mask metadata are only collected from 'inputs`\n # - Layers are built using shape info from 'inputs' only\n # - input_spec compatibility is only checked against `inputs`\n # - mixed precision casting (autocast) is only applied to `inputs`,\n # not to any other argument.\n # - setting the SavedModel saving spec.\n inputs, args, kwargs = self._split_out_first_arg(args, kwargs)\n input_list = nest.flatten(inputs)\n\n # Functional Model construction mode is invoked when `Layer`s are called on\n # symbolic `KerasTensor`s, i.e.:\n # >> inputs = tf.keras.Input(10)\n # >> outputs = MyLayer()(inputs) # Functional construction mode.\n # >> model = tf.keras.Model(inputs, outputs)\n if _in_functional_construction_mode(inputs, args, kwargs, input_list):\n return self._functional_construction_call(inputs, args, kwargs,\n input_list)\n\n # Maintains info about the `Layer.call` stack.\n call_context = base_layer_utils.call_context()\n\n # Accept NumPy and scalar inputs by converting to Tensors.\n if any(isinstance(x, (np.ndarray, float, int)) for x in input_list):\n inputs = nest.map_structure(_convert_numpy_or_python_types, inputs)\n input_list = nest.flatten(inputs)\n\n # Handle `mask` propagation from previous layer to current layer. Masks can\n # be propagated explicitly via the `mask` argument, or implicitly via\n # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed\n # explicitly take priority.\n input_masks, mask_is_implicit = self._get_input_masks(\n inputs, input_list, args, kwargs)\n if self._expects_mask_arg and mask_is_implicit:\n kwargs['mask'] = input_masks\n\n # Training mode for `Layer.call` is set via (in order of priority):\n # (1) The `training` argument passed to this `Layer.call`, if it is not None\n # (2) The training mode of an outer `Layer.call`.\n # (3) The default mode set by `tf.keras.backend.set_learning_phase` (if set)\n # (4) Any non-None default value for `training` specified in the call\n # signature\n # (5) False (treating the layer as if it's in inference)\n args, kwargs, training_mode = self._set_training_mode(\n args, kwargs, call_context)\n\n # Losses are cleared for all sublayers on the outermost `Layer.call`.\n # Losses are not cleared on inner `Layer.call`s, because sublayers can be\n # called multiple times.\n if not call_context.in_call:\n self._clear_losses()\n\n eager = context.executing_eagerly()\n with call_context.enter(\n layer=self,\n inputs=inputs,\n build_graph=not eager,\n training=training_mode):\n\n if self._autocast:\n inputs = self._maybe_cast_inputs(inputs, input_list)\n\n if eager:\n call_fn = self.call\n name_scope = self._name\n else:\n input_spec.assert_input_compatibility(self.input_spec, inputs,\n self.name)\n name_scope = self._name_scope() # Avoid autoincrementing.\n call_fn = self._autographed_call()\n\n with ops.name_scope_v2(name_scope):\n if not self.built:\n self._maybe_build(inputs)\n\n with ops.enable_auto_cast_variables(self._compute_dtype_object):\n outputs = call_fn(inputs, *args, **kwargs)\n\n if self._activity_regularizer:\n self._handle_activity_regularization(inputs, outputs)\n if self._supports_masking:\n self._set_mask_metadata(inputs, outputs, input_masks, not eager)\n if self._saved_model_inputs_spec is None:\n self._set_save_spec(inputs)\n\n return outputs\n\n def _functional_construction_call(self, inputs, args, kwargs, input_list):\n call_context = base_layer_utils.call_context()\n\n # Accept NumPy and scalar inputs by converting to Tensors.\n if any(isinstance(x, (np.ndarray, float, int)) for x in input_list):\n\n def _convert_non_tensor(x):\n # Don't call `ops.convert_to_tensor_v2` on all `inputs` because\n # `SparseTensors` can't be converted to `Tensor`.\n if isinstance(x, (np.ndarray, float, int)):\n return ops.convert_to_tensor_v2(x)\n return x\n\n inputs = nest.map_structure(_convert_non_tensor, inputs)\n input_list = nest.flatten(inputs)\n\n # Handle `mask` propagation from previous layer to current layer. Masks can\n # be propagated explicitly via the `mask` argument, or implicitly via\n # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed\n # explicitly take priority.\n mask_arg_passed_by_framework = False\n input_masks, mask_is_implicit = self._get_input_masks(\n inputs, input_list, args, kwargs)\n if self._expects_mask_arg and mask_is_implicit:\n kwargs['mask'] = input_masks\n mask_arg_passed_by_framework = True\n\n # If `training` argument is None or not explicitly passed,\n # propagate `training` value from this layer's calling layer.\n training_value = None\n training_arg_passed_by_framework = False\n # Priority 1: `training` was explicitly passed a non-None value.\n if self._call_arg_was_passed('training', args, kwargs):\n training_value = self._get_call_arg_value('training', args, kwargs)\n if not self._expects_training_arg:\n kwargs.pop('training')\n\n if training_value is None:\n # Priority 2: `training` was passed to a parent layer.\n if call_context.training is not None:\n training_value = call_context.training\n # Priority 3: `learning_phase()` has been set.\n elif backend.global_learning_phase_is_set():\n training_value = backend.learning_phase()\n # Force the training_value to be bool type which matches to the contract\n # for layer/model call args.\n if tensor_util.is_tensor(training_value):\n training_value = math_ops.cast(training_value, dtypes.bool)\n else:\n training_value = bool(training_value)\n # Priority 4: trace layer with the default training argument specified\n # in the `call` signature (or in inference mode if the `call` signature\n # specifies no non-None default).\n else:\n training_value = self._default_training_arg\n # In cases (2), (3), (4) the training argument is passed automatically\n # by the framework, and will not be hard-coded into the model.\n if self._expects_training_arg:\n args, kwargs = self._set_call_arg_value('training', training_value,\n args, kwargs)\n training_arg_passed_by_framework = True\n\n if keras_tensor.keras_tensors_enabled():\n with call_context.enter(\n layer=self, inputs=inputs, build_graph=True, training=training_value):\n # Check input assumptions set after layer building, e.g. input shape.\n outputs = self._keras_tensor_symbolic_call(\n inputs, input_masks, args, kwargs)\n\n if outputs is None:\n raise ValueError('A layer\\'s `call` method should return a '\n 'Tensor or a list of Tensors, not None '\n '(layer: ' + self.name + ').')\n if training_arg_passed_by_framework:\n args, kwargs = self._set_call_arg_value(\n 'training', None, args, kwargs, pop_kwarg_if_none=True)\n if mask_arg_passed_by_framework:\n kwargs.pop('mask')\n # Node connectivity does not special-case the first argument.\n outputs = self._set_connectivity_metadata((inputs,) + args, kwargs,\n outputs)\n return outputs\n\n # Only create Keras history if at least one tensor originates from a\n # `keras.Input`. Otherwise this Layer may be being used outside the Keras\n # framework.\n # TODO(kaftan): make this not special case inputs\n if base_layer_utils.needs_keras_history(inputs):\n base_layer_utils.create_keras_history(inputs)\n\n with call_context.enter(\n layer=self, inputs=inputs, build_graph=True, training=training_value):\n # Symbolic execution on symbolic tensors. We will attempt to build\n # the corresponding TF subgraph inside `backend.get_graph()`\n # TODO(reedwm): We should assert input compatibility after the inputs\n # are casted, not before.\n input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)\n graph = backend.get_graph()\n # Use `self._name_scope()` to avoid auto-incrementing the name.\n with graph.as_default(), backend.name_scope(self._name_scope()):\n # Build layer if applicable (if the `build` method has been\n # overridden).\n self._maybe_build(inputs)\n cast_inputs = self._maybe_cast_inputs(inputs, input_list)\n\n if not self.dynamic:\n # Wrapping `call` function in autograph to allow for dynamic control\n # flow and control dependencies in call. We are limiting this to\n # subclassed layers as autograph is strictly needed only for\n # subclassed layers and models.\n # tf_convert will respect the value of autograph setting in the\n # enclosing tf.function, if any.\n if (base_layer_utils.is_subclassed(self) and\n not base_layer_utils.from_saved_model(self)):\n call_fn = autograph.tf_convert(self.call,\n ag_ctx.control_status_ctx())\n else:\n call_fn = self.call\n\n try:\n with ops.enable_auto_cast_variables(self._compute_dtype_object):\n outputs = call_fn(cast_inputs, *args, **kwargs)\n\n except errors.OperatorNotAllowedInGraphError as e:\n raise TypeError('You are attempting to use Python control '\n 'flow in a layer that was not declared to be '\n 'dynamic. Pass `dynamic=True` to the class '\n 'constructor.\\nEncountered error:\\n\"\"\"\\n' + str(e) +\n '\\n\"\"\"')\n else:\n # We will use static shape inference to return symbolic tensors\n # matching the specifications of the layer outputs.\n # Since `self.dynamic` is True, we will never attempt to\n # run the underlying TF graph (which is disconnected).\n # TODO(fchollet): consider py_func as an alternative, which\n # would enable us to run the underlying graph if needed.\n outputs = self._symbolic_call(inputs)\n\n if outputs is None:\n raise ValueError('A layer\\'s `call` method should return a '\n 'Tensor or a list of Tensors, not None '\n '(layer: ' + self.name + ').')\n # TODO(kaftan): This should be 'any' and check all args\n if base_layer_utils.have_all_keras_metadata(inputs):\n if training_arg_passed_by_framework:\n args, kwargs = self._set_call_arg_value(\n 'training', None, args, kwargs, pop_kwarg_if_none=True)\n if mask_arg_passed_by_framework:\n kwargs.pop('mask')\n # Node connectivity does not special-case the first argument.\n outputs = self._set_connectivity_metadata((inputs,) + args, kwargs,\n outputs)\n self._handle_activity_regularization(inputs, outputs)\n self._set_mask_metadata(inputs, outputs, input_masks, True)\n if hasattr(self, '_set_inputs') and not self.inputs:\n # Subclassed network: explicitly set metadata normally set by\n # a call to self._set_inputs().\n self._set_inputs(cast_inputs, outputs)\n\n return outputs\n\n def _set_training_mode(self, args, kwargs, call_context):\n training_mode = None\n if self._expects_training_arg:\n # (1) `training` was passed to this `Layer.call`.\n if self._call_arg_was_passed('training', args, kwargs):\n training_mode = self._get_call_arg_value('training', args, kwargs)\n # If no `training` arg was passed, or `None` was explicitly passed,\n # the framework will make a decision about the training mode is.\n if training_mode is None:\n call_ctx_training = call_context.training\n # (2) `training` mode is inferred from an outer `Layer.call`.\n if call_ctx_training is not None:\n training_mode = call_ctx_training\n # (3) User set `tf.keras.backend.set_learning_phase`.\n elif backend.global_learning_phase_is_set():\n training_mode = backend.learning_phase()\n # Ensure value is a `bool` or `tf.bool`.\n if isinstance(training_mode, bool):\n pass\n elif tensor_util.is_tensor(training_mode):\n training_mode = math_ops.cast(training_mode, dtypes.bool)\n else:\n training_mode = bool(training_mode)\n # (4) We default to using `call`'s default value for `training`,\n # or treating the layer as if it is in inference if no non-None default\n # is specified in the `call` signature.\n else:\n training_mode = self._default_training_arg\n\n # For case (2), (3), (4) `training` arg is passed by framework.\n args, kwargs = self._set_call_arg_value('training', training_mode, args,\n kwargs)\n else:\n if 'training' in kwargs:\n # `training` was passed to this `Layer` but is not needed for\n # `Layer.call`. It will set the default mode for inner `Layer.call`s.\n training_mode = kwargs.pop('training')\n else:\n # Grab the current `training` mode from any outer `Layer.call`.\n training_mode = call_context.training\n\n return args, kwargs, training_mode\n\n def _autographed_call(self):\n # Wrapping `call` function in autograph to allow for dynamic control\n # flow and control dependencies in call. We are limiting this to\n # subclassed layers as autograph is strictly needed only for\n # subclassed layers and models.\n # tf_convert will respect the value of autograph setting in the\n # enclosing tf.function, if any.\n if (base_layer_utils.is_subclassed(self) and\n not base_layer_utils.from_saved_model(self)):\n return autograph.tf_convert(self.call, ag_ctx.control_status_ctx())\n else:\n return self.call\n\n @property\n def dtype(self):\n \"\"\"Dtype used by the weights of the layer, set in the constructor.\"\"\"\n return self._dtype_policy.variable_dtype\n\n @property\n def name(self):\n \"\"\"Name of the layer (string), set in the constructor.\"\"\"\n return self._name\n\n @property\n def supports_masking(self):\n \"\"\"Whether this layer supports computing a mask using `compute_mask`.\"\"\"\n return self._supports_masking\n\n @supports_masking.setter\n def supports_masking(self, value):\n self._supports_masking = value\n\n @property\n def dynamic(self):\n \"\"\"Whether the layer is dynamic (eager-only); set in the constructor.\"\"\"\n return any(layer._dynamic for layer in self._flatten_layers())\n\n @property\n @doc_controls.do_not_doc_inheritable\n def stateful(self):\n return any(layer._stateful for layer in self._flatten_layers())\n\n @stateful.setter\n def stateful(self, value):\n self._stateful = value\n\n @property\n def trainable(self):\n return self._trainable\n\n @trainable.setter\n def trainable(self, value):\n for layer in self._flatten_layers():\n layer._trainable = value\n\n @property\n def activity_regularizer(self):\n \"\"\"Optional regularizer function for the output of this layer.\"\"\"\n return self._activity_regularizer\n\n @activity_regularizer.setter\n def activity_regularizer(self, regularizer):\n \"\"\"Optional regularizer function for the output of this layer.\"\"\"\n self._activity_regularizer = regularizer\n\n @property\n def input_spec(self):\n \"\"\"`InputSpec` instance(s) describing the input format for this layer.\n\n When you create a layer subclass, you can set `self.input_spec` to enable\n the layer to run input compatibility checks when it is called.\n Consider a `Conv2D` layer: it can only be called on a single input tensor\n of rank 4. As such, you can set, in `__init__()`:\n\n ```python\n self.input_spec = tf.keras.layers.InputSpec(ndim=4)\n ```\n\n Now, if you try to call the layer on an input that isn't rank 4\n (for instance, an input of shape `(2,)`, it will raise a nicely-formatted\n error:\n\n ```\n ValueError: Input 0 of layer conv2d is incompatible with the layer:\n expected ndim=4, found ndim=1. Full shape received: [2]\n ```\n\n Input checks that can be specified via `input_spec` include:\n - Structure (e.g. a single input, a list of 2 inputs, etc)\n - Shape\n - Rank (ndim)\n - Dtype\n\n For more information, see `tf.keras.layers.InputSpec`.\n\n Returns:\n A `tf.keras.layers.InputSpec` instance, or nested structure thereof.\n \"\"\"\n return self._input_spec\n\n @input_spec.setter\n # Must be decorated to prevent tracking, since the input_spec can be nested\n # InputSpec objects.\n @trackable.no_automatic_dependency_tracking\n def input_spec(self, value):\n for v in nest.flatten(value):\n if v is not None and not isinstance(v, InputSpec):\n raise TypeError('Layer input_spec must be an instance of InputSpec. '\n 'Got: {}'.format(v))\n self._input_spec = value\n\n @property\n def trainable_weights(self):\n \"\"\"List of all trainable weights tracked by this layer.\n\n Trainable weights are updated via gradient descent during training.\n\n Returns:\n A list of trainable variables.\n \"\"\"\n if self.trainable:\n children_weights = self._gather_children_attribute('trainable_weights')\n return self._dedup_weights(self._trainable_weights + children_weights)\n else:\n return []\n\n @property\n def non_trainable_weights(self):\n \"\"\"List of all non-trainable weights tracked by this layer.\n\n Non-trainable weights are *not* updated during training. They are expected\n to be updated manually in `call()`.\n\n Returns:\n A list of non-trainable variables.\n \"\"\"\n if self.trainable:\n children_weights = self._gather_children_attribute(\n 'non_trainable_weights')\n non_trainable_weights = self._non_trainable_weights + children_weights\n else:\n children_weights = self._gather_children_attribute('weights')\n non_trainable_weights = (\n self._trainable_weights + self._non_trainable_weights +\n children_weights)\n return self._dedup_weights(non_trainable_weights)\n\n @property\n def weights(self):\n \"\"\"Returns the list of all layer variables/weights.\n\n Returns:\n A list of variables.\n \"\"\"\n return self.trainable_weights + self.non_trainable_weights\n\n @property\n @deprecation.deprecated(\n date=None,\n instructions='This property should not be used in TensorFlow 2.0, '\n 'as updates are applied automatically.')\n @doc_controls.do_not_generate_docs\n def updates(self):\n if keras_tensor.keras_tensors_enabled():\n return []\n\n collected_updates = []\n all_layers = self._flatten_layers()\n with backend.get_graph().as_default():\n for layer in all_layers:\n if not layer.trainable and not layer.stateful:\n continue\n for u in layer._updates:\n if callable(u):\n u = u()\n collected_updates.append(u)\n return collected_updates\n\n @property\n def losses(self):\n \"\"\"List of losses added using the `add_loss()` API.\n\n Variable regularization tensors are created when this property is accessed,\n so it is eager safe: accessing `losses` under a `tf.GradientTape` will\n propagate gradients back to the corresponding variables.\n\n Examples:\n\n >>> class MyLayer(tf.keras.layers.Layer):\n ... def call(self, inputs):\n ... self.add_loss(tf.abs(tf.reduce_mean(inputs)))\n ... return inputs\n >>> l = MyLayer()\n >>> l(np.ones((10, 1)))\n >>> l.losses\n [1.0]\n\n >>> inputs = tf.keras.Input(shape=(10,))\n >>> x = tf.keras.layers.Dense(10)(inputs)\n >>> outputs = tf.keras.layers.Dense(1)(x)\n >>> model = tf.keras.Model(inputs, outputs)\n >>> # Activity regularization.\n >>> model.add_loss(tf.abs(tf.reduce_mean(x)))\n >>> model.losses\n [<tf.Tensor 'Abs:0' shape=() dtype=float32>]\n\n >>> inputs = tf.keras.Input(shape=(10,))\n >>> d = tf.keras.layers.Dense(10, kernel_initializer='ones')\n >>> x = d(inputs)\n >>> outputs = tf.keras.layers.Dense(1)(x)\n >>> model = tf.keras.Model(inputs, outputs)\n >>> # Weight regularization.\n >>> model.add_loss(lambda: tf.reduce_mean(d.kernel))\n >>> model.losses\n [<tf.Tensor: shape=(), dtype=float32, numpy=1.0>]\n\n Returns:\n A list of tensors.\n \"\"\"\n collected_losses = []\n for layer in self._flatten_layers():\n # If any eager losses are present, we assume the model to be part of an\n # eager training loop (either a custom one or the one used when\n # `run_eagerly=True`) and so we always return just the eager losses.\n if layer._eager_losses:\n # Filter placeholder losses that may have been added by revived layers.\n # (see base_layer_utils for details).\n if (layer._eager_losses[0] is\n not base_layer_utils.REVIVED_LOSS_PLACEHOLDER):\n collected_losses.extend(layer._eager_losses)\n else:\n collected_losses.extend(layer._losses)\n for regularizer in layer._callable_losses:\n loss_tensor = regularizer()\n if loss_tensor is not None:\n collected_losses.append(loss_tensor)\n return collected_losses\n\n def add_loss(self, losses, **kwargs):\n \"\"\"Add loss tensor(s), potentially dependent on layer inputs.\n\n Some losses (for instance, activity regularization losses) may be dependent\n on the inputs passed when calling a layer. Hence, when reusing the same\n layer on different inputs `a` and `b`, some entries in `layer.losses` may\n be dependent on `a` and some on `b`. This method automatically keeps track\n of dependencies.\n\n This method can be used inside a subclassed layer or model's `call`\n function, in which case `losses` should be a Tensor or list of Tensors.\n\n Example:\n\n ```python\n class MyLayer(tf.keras.layers.Layer):\n def call(self, inputs):\n self.add_loss(tf.abs(tf.reduce_mean(inputs)))\n return inputs\n ```\n\n This method can also be called directly on a Functional Model during\n construction. In this case, any loss Tensors passed to this Model must\n be symbolic and be able to be traced back to the model's `Input`s. These\n losses become part of the model's topology and are tracked in `get_config`.\n\n Example:\n\n ```python\n inputs = tf.keras.Input(shape=(10,))\n x = tf.keras.layers.Dense(10)(inputs)\n outputs = tf.keras.layers.Dense(1)(x)\n model = tf.keras.Model(inputs, outputs)\n # Activity regularization.\n model.add_loss(tf.abs(tf.reduce_mean(x)))\n ```\n\n If this is not the case for your loss (if, for example, your loss references\n a `Variable` of one of the model's layers), you can wrap your loss in a\n zero-argument lambda. These losses are not tracked as part of the model's\n topology since they can't be serialized.\n\n Example:\n\n ```python\n inputs = tf.keras.Input(shape=(10,))\n d = tf.keras.layers.Dense(10)\n x = d(inputs)\n outputs = tf.keras.layers.Dense(1)(x)\n model = tf.keras.Model(inputs, outputs)\n # Weight regularization.\n model.add_loss(lambda: tf.reduce_mean(d.kernel))\n ```\n\n Arguments:\n losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses\n may also be zero-argument callables which create a loss tensor.\n **kwargs: Additional keyword arguments for backward compatibility.\n Accepted values:\n inputs - Deprecated, will be automatically inferred.\n \"\"\"\n kwargs.pop('inputs', None)\n if kwargs:\n raise TypeError('Unknown keyword arguments: %s' % (kwargs.keys(),))\n\n def _tag_callable(loss):\n \"\"\"Tags callable loss tensor as `_unconditional_loss`.\"\"\"\n if callable(loss):\n # We run the loss without autocasting, as regularizers are often\n # numerically unstable in float16.\n with ops.enable_auto_cast_variables(None):\n loss = loss()\n if loss is None:\n return None # Will be filtered out when computing the .losses property\n if not tensor_util.is_tensor(loss):\n loss = ops.convert_to_tensor_v2(loss, dtype=backend.floatx())\n loss._unconditional_loss = True # pylint: disable=protected-access\n return loss\n\n losses = nest.flatten(losses)\n\n callable_losses = []\n eager_losses = []\n symbolic_losses = []\n for loss in losses:\n if callable(loss):\n callable_losses.append(functools.partial(_tag_callable, loss))\n continue\n if loss is None:\n continue\n if not tensor_util.is_tensor(loss) and not isinstance(\n loss, keras_tensor.KerasTensor):\n loss = ops.convert_to_tensor_v2(loss, dtype=backend.floatx())\n # TF Functions should take the eager path.\n if ((tf_utils.is_symbolic_tensor(loss) or\n isinstance(loss, keras_tensor.KerasTensor)) and\n not base_layer_utils.is_in_tf_function()):\n symbolic_losses.append(loss)\n elif tensor_util.is_tensor(loss):\n eager_losses.append(loss)\n\n self._callable_losses.extend(callable_losses)\n\n in_call_context = base_layer_utils.call_context().in_call\n if eager_losses and not in_call_context:\n raise ValueError(\n 'Expected a symbolic Tensors or a callable for the loss value. '\n 'Please wrap your loss computation in a zero argument `lambda`.')\n\n self._eager_losses.extend(eager_losses)\n\n if in_call_context and not keras_tensor.keras_tensors_enabled():\n for symbolic_loss in symbolic_losses:\n self._losses.append(symbolic_loss)\n else:\n for symbolic_loss in symbolic_losses:\n if getattr(self, '_is_graph_network', False):\n self._graph_network_add_loss(symbolic_loss)\n else:\n # Possible a loss was added in a Layer's `build`.\n self._losses.append(symbolic_loss)\n\n def _clear_losses(self):\n \"\"\"Used every step in eager to reset losses.\"\"\"\n # Set to thread local directly to avoid Layer.__setattr__ overhead.\n if not getattr(self, '_layers', None): # Fast path for single Layer.\n self._thread_local._eager_losses = []\n else:\n for layer in self._flatten_layers():\n layer._thread_local._eager_losses = []\n\n @property\n def metrics(self):\n \"\"\"List of metrics added using the `add_metric()` API.\n\n Example:\n\n >>> input = tf.keras.layers.Input(shape=(3,))\n >>> d = tf.keras.layers.Dense(2)\n >>> output = d(input)\n >>> d.add_metric(tf.reduce_max(output), name='max')\n >>> d.add_metric(tf.reduce_min(output), name='min')\n >>> [m.name for m in d.metrics]\n ['max', 'min']\n\n Returns:\n A list of tensors.\n \"\"\"\n collected_metrics = []\n for layer in self._flatten_layers():\n with layer._metrics_lock:\n collected_metrics.extend(layer._metrics)\n return collected_metrics\n\n def add_metric(self, value, name=None, **kwargs):\n \"\"\"Adds metric tensor to the layer.\n\n This method can be used inside the `call()` method of a subclassed layer\n or model.\n\n ```python\n class MyMetricLayer(tf.keras.layers.Layer):\n def __init__(self):\n super(MyMetricLayer, self).__init__(name='my_metric_layer')\n self.mean = metrics_module.Mean(name='metric_1')\n\n def call(self, inputs):\n self.add_metric(self.mean(x))\n self.add_metric(math_ops.reduce_sum(x), name='metric_2')\n return inputs\n ```\n\n This method can also be called directly on a Functional Model during\n construction. In this case, any tensor passed to this Model must\n be symbolic and be able to be traced back to the model's `Input`s. These\n metrics become part of the model's topology and are tracked when you\n save the model via `save()`.\n\n ```python\n inputs = tf.keras.Input(shape=(10,))\n x = tf.keras.layers.Dense(10)(inputs)\n outputs = tf.keras.layers.Dense(1)(x)\n model = tf.keras.Model(inputs, outputs)\n model.add_metric(math_ops.reduce_sum(x), name='metric_1')\n ```\n\n Note: Calling `add_metric()` with the result of a metric object on a\n Functional Model, as shown in the example below, is not supported. This is\n because we cannot trace the metric result tensor back to the model's inputs.\n\n ```python\n inputs = tf.keras.Input(shape=(10,))\n x = tf.keras.layers.Dense(10)(inputs)\n outputs = tf.keras.layers.Dense(1)(x)\n model = tf.keras.Model(inputs, outputs)\n model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1')\n ```\n\n Args:\n value: Metric tensor.\n name: String metric name.\n **kwargs: Additional keyword arguments for backward compatibility.\n Accepted values:\n `aggregation` - When the `value` tensor provided is not the result of\n calling a `keras.Metric` instance, it will be aggregated by default\n using a `keras.Metric.Mean`.\n \"\"\"\n kwargs_keys = list(kwargs.keys())\n if (len(kwargs_keys) > 1 or\n (len(kwargs_keys) == 1 and kwargs_keys[0] != 'aggregation')):\n raise TypeError('Unknown keyword arguments: ', str(kwargs.keys()))\n\n from_metric_obj = hasattr(value, '_metric_obj')\n if keras_tensor.keras_tensors_enabled():\n is_symbolic = isinstance(value, keras_tensor.KerasTensor)\n else:\n is_symbolic = tf_utils.is_symbolic_tensor(value)\n in_call_context = base_layer_utils.call_context().in_call\n\n if name is None and not from_metric_obj:\n # Eg. `self.add_metric(math_ops.reduce_sum(x))`\n # In eager mode, we use metric name to lookup a metric. Without a name,\n # a new Mean metric wrapper will be created on every model/layer call.\n # So, we raise an error when no name is provided.\n # We will do the same for symbolic mode for consistency although a name\n # will be generated if no name is provided.\n\n # We will not raise this error in the foll use case for the sake of\n # consistency as name in provided in the metric constructor.\n # mean = metrics.Mean(name='my_metric')\n # model.add_metric(mean(outputs))\n raise ValueError('Please provide a name for your metric like '\n '`self.add_metric(tf.reduce_sum(inputs), '\n 'name=\\'mean_activation\\')`')\n elif from_metric_obj:\n name = value._metric_obj.name\n\n if not in_call_context and not is_symbolic:\n raise ValueError('Expected a symbolic Tensor for the metric value, '\n 'received: ' + str(value))\n\n # If a metric was added in a Layer's `call` or `build`.\n if in_call_context or not getattr(self, '_is_graph_network', False):\n # TF Function path should take the eager path.\n\n # If the given metric is available in `metrics` list we just update state\n # on it, otherwise we create a new metric instance and\n # add it to the `metrics` list.\n metric_obj = getattr(value, '_metric_obj', None)\n # Tensors that come from a Metric object already updated the Metric state.\n should_update_state = not metric_obj\n name = metric_obj.name if metric_obj else name\n\n with self._metrics_lock:\n match = self._get_existing_metric(name)\n if match:\n metric_obj = match\n elif metric_obj:\n self._metrics.append(metric_obj)\n else:\n from tensorflow.python.keras import metrics as metrics_mod # pylint:disable=g-import-not-at-top\n # Build the metric object with the value's dtype if it defines one\n metric_obj = metrics_mod.Mean(\n name=name, dtype=getattr(value, 'dtype', None))\n self._metrics.append(metric_obj)\n\n if should_update_state:\n metric_obj(value)\n else:\n if from_metric_obj:\n raise ValueError('Using the result of calling a `Metric` object '\n 'when calling `add_metric` on a Functional '\n 'Model is not supported. Please pass the '\n 'Tensor to monitor directly.')\n\n # Insert layers into the Keras Graph Network.\n aggregation = None if from_metric_obj else 'mean'\n self._graph_network_add_metric(value, aggregation, name)\n\n @deprecation.deprecated_args(None, '`inputs` is now automatically inferred',\n 'inputs')\n @doc_controls.do_not_doc_inheritable\n def add_update(self, updates, inputs=None):\n \"\"\"Add update op(s), potentially dependent on layer inputs.\n\n Weight updates (for instance, the updates of the moving mean and variance\n in a BatchNormalization layer) may be dependent on the inputs passed\n when calling a layer. Hence, when reusing the same layer on\n different inputs `a` and `b`, some entries in `layer.updates` may be\n dependent on `a` and some on `b`. This method automatically keeps track\n of dependencies.\n\n This call is ignored when eager execution is enabled (in that case, variable\n updates are run on the fly and thus do not need to be tracked for later\n execution).\n\n Arguments:\n updates: Update op, or list/tuple of update ops, or zero-arg callable\n that returns an update op. A zero-arg callable should be passed in\n order to disable running the updates by setting `trainable=False`\n on this Layer, when executing in Eager mode.\n inputs: Deprecated, will be automatically inferred.\n \"\"\"\n call_context = base_layer_utils.call_context()\n # No need to run updates during Functional API construction.\n if call_context.in_keras_graph:\n return\n\n # Callable updates are disabled by setting `trainable=False`.\n if not call_context.frozen:\n for update in nest.flatten(updates):\n if callable(update):\n update()\n\n def set_weights(self, weights):\n \"\"\"Sets the weights of the layer, from Numpy arrays.\n\n The weights of a layer represent the state of the layer. This function\n sets the weight values from numpy arrays. The weight values should be\n passed in the order they are created by the layer. Note that the layer's\n weights must be instantiated before calling this function by calling\n the layer.\n\n For example, a Dense layer returns a list of two values-- per-output\n weights and the bias value. These can be used to set the weights of another\n Dense layer:\n\n >>> a = tf.keras.layers.Dense(1,\n ... kernel_initializer=tf.constant_initializer(1.))\n >>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))\n >>> a.get_weights()\n [array([[1.],\n [1.],\n [1.]], dtype=float32), array([0.], dtype=float32)]\n >>> b = tf.keras.layers.Dense(1,\n ... kernel_initializer=tf.constant_initializer(2.))\n >>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))\n >>> b.get_weights()\n [array([[2.],\n [2.],\n [2.]], dtype=float32), array([0.], dtype=float32)]\n >>> b.set_weights(a.get_weights())\n >>> b.get_weights()\n [array([[1.],\n [1.],\n [1.]], dtype=float32), array([0.], dtype=float32)]\n\n Arguments:\n weights: a list of Numpy arrays. The number\n of arrays and their shape must match\n number of the dimensions of the weights\n of the layer (i.e. it should match the\n output of `get_weights`).\n\n Raises:\n ValueError: If the provided weights list does not match the\n layer's specifications.\n \"\"\"\n params = self.weights\n\n expected_num_weights = 0\n for param in params:\n if isinstance(param, base_layer_utils.TrackableWeightHandler):\n expected_num_weights += param.num_tensors\n else:\n expected_num_weights += 1\n\n if expected_num_weights != len(weights):\n raise ValueError(\n 'You called `set_weights(weights)` on layer \"%s\" '\n 'with a weight list of length %s, but the layer was '\n 'expecting %s weights. Provided weights: %s...' %\n (self.name, len(weights), expected_num_weights, str(weights)[:50]))\n\n weight_index = 0\n weight_value_tuples = []\n for param in params:\n if isinstance(param, base_layer_utils.TrackableWeightHandler):\n num_tensors = param.num_tensors\n tensors = weights[weight_index:weight_index + num_tensors]\n param.set_weights(tensors)\n weight_index += num_tensors\n else:\n weight = weights[weight_index]\n ref_shape = param.shape\n if not ref_shape.is_compatible_with(weight.shape):\n raise ValueError(\n 'Layer weight shape %s not compatible with provided weight '\n 'shape %s' % (ref_shape, weight.shape))\n weight_value_tuples.append((param, weight))\n weight_index += 1\n\n backend.batch_set_value(weight_value_tuples)\n\n def get_weights(self):\n \"\"\"Returns the current weights of the layer.\n\n The weights of a layer represent the state of the layer. This function\n returns both trainable and non-trainable weight values associated with this\n layer as a list of Numpy arrays, which can in turn be used to load state\n into similarly parameterized layers.\n\n For example, a Dense layer returns a list of two values-- per-output\n weights and the bias value. These can be used to set the weights of another\n Dense layer:\n\n >>> a = tf.keras.layers.Dense(1,\n ... kernel_initializer=tf.constant_initializer(1.))\n >>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))\n >>> a.get_weights()\n [array([[1.],\n [1.],\n [1.]], dtype=float32), array([0.], dtype=float32)]\n >>> b = tf.keras.layers.Dense(1,\n ... kernel_initializer=tf.constant_initializer(2.))\n >>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))\n >>> b.get_weights()\n [array([[2.],\n [2.],\n [2.]], dtype=float32), array([0.], dtype=float32)]\n >>> b.set_weights(a.get_weights())\n >>> b.get_weights()\n [array([[1.],\n [1.],\n [1.]], dtype=float32), array([0.], dtype=float32)]\n\n Returns:\n Weights values as a list of numpy arrays.\n \"\"\"\n weights = self.weights\n output_weights = []\n for weight in weights:\n if isinstance(weight, base_layer_utils.TrackableWeightHandler):\n output_weights.extend(weight.get_tensors())\n else:\n output_weights.append(weight)\n return backend.batch_get_value(output_weights)\n\n @deprecation.deprecated(\n date=None, instructions='Please use `layer.updates` instead.')\n @doc_controls.do_not_generate_docs\n def get_updates_for(self, inputs):\n \"\"\"Deprecated, do NOT use!\n\n Retrieves updates relevant to a specific set of inputs.\n\n Arguments:\n inputs: Input tensor or list/tuple of input tensors.\n\n Returns:\n List of update ops of the layer that depend on `inputs`.\n \"\"\"\n return self.updates\n\n @deprecation.deprecated(\n date=None, instructions='Please use `layer.losses` instead.')\n @doc_controls.do_not_generate_docs\n def get_losses_for(self, inputs):\n \"\"\"Deprecated, do NOT use!\n\n Retrieves losses relevant to a specific set of inputs.\n\n Arguments:\n inputs: Input tensor or list/tuple of input tensors.\n\n Returns:\n List of loss tensors of the layer that depend on `inputs`.\n \"\"\"\n return self.losses\n\n @doc_controls.do_not_doc_inheritable\n def get_input_mask_at(self, node_index):\n \"\"\"Retrieves the input mask tensor(s) of a layer at a given node.\n\n Arguments:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\n Returns:\n A mask tensor\n (or list of tensors if the layer has multiple inputs).\n \"\"\"\n inputs = self.get_input_at(node_index)\n if isinstance(inputs, list):\n return [getattr(x, '_keras_mask', None) for x in inputs]\n else:\n return getattr(inputs, '_keras_mask', None)\n\n @doc_controls.do_not_doc_inheritable\n def get_output_mask_at(self, node_index):\n \"\"\"Retrieves the output mask tensor(s) of a layer at a given node.\n\n Arguments:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\n Returns:\n A mask tensor\n (or list of tensors if the layer has multiple outputs).\n \"\"\"\n output = self.get_output_at(node_index)\n if isinstance(output, list):\n return [getattr(x, '_keras_mask', None) for x in output]\n else:\n return getattr(output, '_keras_mask', None)\n\n @property\n @doc_controls.do_not_doc_inheritable\n def input_mask(self):\n \"\"\"Retrieves the input mask tensor(s) of a layer.\n\n Only applicable if the layer has exactly one inbound node,\n i.e. if it is connected to one incoming layer.\n\n Returns:\n Input mask tensor (potentially None) or list of input\n mask tensors.\n\n Raises:\n AttributeError: if the layer is connected to\n more than one incoming layers.\n \"\"\"\n inputs = self.input\n if isinstance(inputs, list):\n return [getattr(x, '_keras_mask', None) for x in inputs]\n else:\n return getattr(inputs, '_keras_mask', None)\n\n @property\n @doc_controls.do_not_doc_inheritable\n def output_mask(self):\n \"\"\"Retrieves the output mask tensor(s) of a layer.\n\n Only applicable if the layer has exactly one inbound node,\n i.e. if it is connected to one incoming layer.\n\n Returns:\n Output mask tensor (potentially None) or list of output\n mask tensors.\n\n Raises:\n AttributeError: if the layer is connected to\n more than one incoming layers.\n \"\"\"\n output = self.output\n if isinstance(output, list):\n return [getattr(x, '_keras_mask', None) for x in output]\n else:\n return getattr(output, '_keras_mask', None)\n\n @doc_controls.do_not_doc_inheritable\n def get_input_shape_at(self, node_index):\n \"\"\"Retrieves the input shape(s) of a layer at a given node.\n\n Arguments:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\n Returns:\n A shape tuple\n (or list of shape tuples if the layer has multiple inputs).\n\n Raises:\n RuntimeError: If called in Eager mode.\n \"\"\"\n return self._get_node_attribute_at_index(node_index, 'input_shapes',\n 'input shape')\n\n @doc_controls.do_not_doc_inheritable\n def get_output_shape_at(self, node_index):\n \"\"\"Retrieves the output shape(s) of a layer at a given node.\n\n Arguments:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\n Returns:\n A shape tuple\n (or list of shape tuples if the layer has multiple outputs).\n\n Raises:\n RuntimeError: If called in Eager mode.\n \"\"\"\n return self._get_node_attribute_at_index(node_index, 'output_shapes',\n 'output shape')\n\n @doc_controls.do_not_doc_inheritable\n def get_input_at(self, node_index):\n \"\"\"Retrieves the input tensor(s) of a layer at a given node.\n\n Arguments:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\n Returns:\n A tensor (or list of tensors if the layer has multiple inputs).\n\n Raises:\n RuntimeError: If called in Eager mode.\n \"\"\"\n return self._get_node_attribute_at_index(node_index, 'input_tensors',\n 'input')\n\n @doc_controls.do_not_doc_inheritable\n def get_output_at(self, node_index):\n \"\"\"Retrieves the output tensor(s) of a layer at a given node.\n\n Arguments:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\n Returns:\n A tensor (or list of tensors if the layer has multiple outputs).\n\n Raises:\n RuntimeError: If called in Eager mode.\n \"\"\"\n return self._get_node_attribute_at_index(node_index, 'output_tensors',\n 'output')\n\n @property\n def input(self):\n \"\"\"Retrieves the input tensor(s) of a layer.\n\n Only applicable if the layer has exactly one input,\n i.e. if it is connected to one incoming layer.\n\n Returns:\n Input tensor or list of input tensors.\n\n Raises:\n RuntimeError: If called in Eager mode.\n AttributeError: If no inbound nodes are found.\n \"\"\"\n if not self._inbound_nodes:\n raise AttributeError('Layer ' + self.name +\n ' is not connected, no input to return.')\n return self._get_node_attribute_at_index(0, 'input_tensors', 'input')\n\n @property\n def output(self):\n \"\"\"Retrieves the output tensor(s) of a layer.\n\n Only applicable if the layer has exactly one output,\n i.e. if it is connected to one incoming layer.\n\n Returns:\n Output tensor or list of output tensors.\n\n Raises:\n AttributeError: if the layer is connected to more than one incoming\n layers.\n RuntimeError: if called in Eager mode.\n \"\"\"\n if not self._inbound_nodes:\n raise AttributeError('Layer ' + self.name + ' has no inbound nodes.')\n return self._get_node_attribute_at_index(0, 'output_tensors', 'output')\n\n @property\n @doc_controls.do_not_doc_inheritable\n def input_shape(self):\n \"\"\"Retrieves the input shape(s) of a layer.\n\n Only applicable if the layer has exactly one input,\n i.e. if it is connected to one incoming layer, or if all inputs\n have the same shape.\n\n Returns:\n Input shape, as an integer shape tuple\n (or list of shape tuples, one tuple per input tensor).\n\n Raises:\n AttributeError: if the layer has no defined input_shape.\n RuntimeError: if called in Eager mode.\n \"\"\"\n if not self._inbound_nodes:\n raise AttributeError('The layer has never been called '\n 'and thus has no defined input shape.')\n all_input_shapes = set(\n [str(node.input_shapes) for node in self._inbound_nodes])\n if len(all_input_shapes) == 1:\n return self._inbound_nodes[0].input_shapes\n else:\n raise AttributeError('The layer \"' + str(self.name) +\n ' has multiple inbound nodes, '\n 'with different input shapes. Hence '\n 'the notion of \"input shape\" is '\n 'ill-defined for the layer. '\n 'Use `get_input_shape_at(node_index)` '\n 'instead.')\n\n def count_params(self):\n \"\"\"Count the total number of scalars composing the weights.\n\n Returns:\n An integer count.\n\n Raises:\n ValueError: if the layer isn't yet built\n (in which case its weights aren't yet defined).\n \"\"\"\n if not self.built:\n if getattr(self, '_is_graph_network', False):\n with tf_utils.maybe_init_scope(self):\n self._maybe_build(self.inputs)\n else:\n raise ValueError('You tried to call `count_params` on ' + self.name +\n ', but the layer isn\\'t built. '\n 'You can build it manually via: `' + self.name +\n '.build(batch_input_shape)`.')\n return layer_utils.count_params(self.weights)\n\n @property\n @doc_controls.do_not_doc_inheritable\n def output_shape(self):\n \"\"\"Retrieves the output shape(s) of a layer.\n\n Only applicable if the layer has one output,\n or if all outputs have the same shape.\n\n Returns:\n Output shape, as an integer shape tuple\n (or list of shape tuples, one tuple per output tensor).\n\n Raises:\n AttributeError: if the layer has no defined output shape.\n RuntimeError: if called in Eager mode.\n \"\"\"\n if not self._inbound_nodes:\n raise AttributeError('The layer has never been called '\n 'and thus has no defined output shape.')\n all_output_shapes = set(\n [str(node.output_shapes) for node in self._inbound_nodes])\n if len(all_output_shapes) == 1:\n return self._inbound_nodes[0].output_shapes\n else:\n raise AttributeError('The layer \"%s\"'\n ' has multiple inbound nodes, '\n 'with different output shapes. Hence '\n 'the notion of \"output shape\" is '\n 'ill-defined for the layer. '\n 'Use `get_output_shape_at(node_index)` '\n 'instead.' % self.name)\n\n @property\n @doc_controls.do_not_doc_inheritable\n def inbound_nodes(self):\n \"\"\"Deprecated, do NOT use! Only for compatibility with external Keras.\"\"\"\n return self._inbound_nodes\n\n @property\n @doc_controls.do_not_doc_inheritable\n def outbound_nodes(self):\n \"\"\"Deprecated, do NOT use! Only for compatibility with external Keras.\"\"\"\n return self._outbound_nodes\n\n ##############################################################################\n # Methods & attributes below are public aliases of other methods. #\n ##############################################################################\n\n @deprecation.deprecated(\n date=None, instructions='Please use `layer.__call__` method instead.')\n @doc_controls.do_not_doc_inheritable\n def apply(self, inputs, *args, **kwargs):\n \"\"\"Deprecated, do NOT use!\n\n This is an alias of `self.__call__`.\n\n Arguments:\n inputs: Input tensor(s).\n *args: additional positional arguments to be passed to `self.call`.\n **kwargs: additional keyword arguments to be passed to `self.call`.\n\n Returns:\n Output tensor(s).\n \"\"\"\n return self.__call__(inputs, *args, **kwargs)\n\n @deprecation.deprecated(\n date=None, instructions='Please use `layer.add_weight` method instead.')\n @doc_controls.do_not_doc_inheritable\n def add_variable(self, *args, **kwargs):\n \"\"\"Deprecated, do NOT use! Alias for `add_weight`.\"\"\"\n return self.add_weight(*args, **kwargs)\n\n @property\n @doc_controls.do_not_generate_docs\n def variables(self):\n \"\"\"Returns the list of all layer variables/weights.\n\n Alias of `self.weights`.\n\n Returns:\n A list of variables.\n \"\"\"\n return self.weights\n\n @property\n @doc_controls.do_not_generate_docs\n def trainable_variables(self):\n return self.trainable_weights\n\n @property\n @doc_controls.do_not_generate_docs\n def non_trainable_variables(self):\n return self.non_trainable_weights\n\n ##############################################################################\n # Methods & attributes below are all private and only used by the framework. #\n ##############################################################################\n\n def _set_dtype_policy(self, dtype):\n \"\"\"Sets self._dtype_policy.\"\"\"\n if isinstance(dtype, policy.Policy):\n self._dtype_policy = dtype\n elif isinstance(dtype, dict):\n self._dtype_policy = policy.deserialize(dtype)\n elif dtype:\n self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name)\n else:\n self._dtype_policy = policy.global_policy()\n if (self._dtype_policy.name == 'mixed_float16' and\n not loss_scale_optimizer.strategy_supports_loss_scaling()):\n # Although only loss scaling doesn't support certain strategies, to avoid\n # confusion, we disallow the 'mixed_float16' policy with unsupported\n # strategies. This is because 'mixed_float16' requires loss scaling for\n # numeric stability.\n strategy = ds_context.get_strategy()\n raise ValueError('Mixed precision is not supported with the '\n 'tf.distribute.Strategy: %s. Either stop using mixed '\n 'precision by removing the use of the \"%s\" policy or '\n 'use a different Strategy, e.g. a MirroredStrategy.' %\n (strategy.__class__.__name__, self._dtype_policy.name))\n\n # This has no impact on the layer behavior, and is only used for printing\n # warnings.\n self._dtype_defaulted_to_floatx = (not dtype and\n policy.policy_defaults_to_floatx())\n\n # Performance optimization: cache the compute dtype as a Dtype object or\n # None, so that str to Dtype conversion doesn't happen in Layer.__call__.\n # TODO(b/157486353): Investigate returning DTypes in Policy.\n if self._dtype_policy.compute_dtype:\n self._compute_dtype_object = dtypes.as_dtype(\n self._dtype_policy.compute_dtype)\n else:\n self._compute_dtype_object = None\n\n # TODO(reedwm): Expose this property?\n @property\n def _compute_dtype(self):\n \"\"\"The layer's compute dtype.\n\n Unless mixed-precision is used, this is the same as `Layer.dtype`.\n\n If self._autocast is True, layer's will cast floating-point inputs to this.\n\n Returns:\n The layer's compute dtype.\n \"\"\"\n return self._dtype_policy.compute_dtype\n\n def _maybe_cast_inputs(self, inputs, input_list=None):\n \"\"\"Maybe casts the inputs to the compute dtype.\n\n If self._compute_dtype is floating-point, and self_autocast is True,\n floating-point inputs are casted to self._compute_dtype.\n\n Args:\n inputs: Input tensor, or structure of input tensors.\n input_list: Flat list of input tensors.\n\n Returns:\n `inputs`, but tensors may have been casted to self._compute_dtype\n \"\"\"\n if not input_list:\n input_list = nest.flatten(inputs)\n\n compute_dtype_object = self._compute_dtype_object\n should_autocast = (\n self._autocast and compute_dtype_object and\n compute_dtype_object.is_floating)\n\n if (should_autocast and\n any(map(self._should_cast_single_input, input_list))):\n # Only perform expensive `nest` operation when needed.\n return nest.map_structure(self._cast_single_input, inputs)\n else:\n return inputs\n\n def _should_cast_single_input(self, x):\n if isinstance(x, _AUTOCAST_TYPES):\n return (self._compute_dtype_object and\n x.dtype != self._compute_dtype_object and x.dtype.is_floating)\n return False\n\n def _cast_single_input(self, x):\n \"\"\"Cast a single Tensor or TensorSpec to the compute dtype.\"\"\"\n if self._should_cast_single_input(x):\n if self._dtype_defaulted_to_floatx:\n self._warn_about_input_casting(x.dtype.base_dtype)\n return math_ops.cast(x, self._compute_dtype_object)\n else:\n return x\n\n def _warn_about_input_casting(self, input_dtype):\n # self._already_warned_about_input_casting is only retrieved or set in this\n # function.\n already_warned = getattr(self, '_already_warned_about_input_casting', False)\n if not already_warned:\n tf_logging.warn(\n \"Layer {self.name} is casting an input tensor from dtype \"\n \"{input_dtype} to the layer's dtype of {layer_dtype}, which is new \"\n \"behavior in TensorFlow 2. The layer has dtype {layer_dtype} \"\n 'because its dtype defaults to floatx.\\n\\n'\n \"\"\n \"If you intended to run this layer in {layer_dtype}, you can safely \"\n \"ignore this warning. If in doubt, this warning is likely only an \"\n \"issue if you are porting a TensorFlow 1.X model to TensorFlow 2.\\n\\n\"\n \"\"\n \"To change all layers to have dtype {input_dtype} by default, call \"\n \"`tf.keras.backend.set_floatx('{input_dtype}')`. To change just this \"\n \"layer, pass dtype='{input_dtype}' to the layer constructor. If you \"\n \"are the author of this layer, you can disable autocasting by \"\n \"passing autocast=False to the base Layer constructor.\\n\".format(\n self=self,\n input_dtype=input_dtype.name,\n layer_dtype=self._compute_dtype))\n self._already_warned_about_input_casting = True\n\n # _dtype used to be an attribute set in the constructor. We still expose it\n # because some clients still use it.\n # TODO(reedwm): Deprecate, then remove the _dtype property.\n @property\n def _dtype(self):\n # This is equivalent to returning self.dtype . We do not return self.dtype\n # as it would cause infinite recursion in a few subclasses, which override\n # \"dtype\" to return self._dtype.\n return self._dtype_policy.variable_dtype\n\n @_dtype.setter\n def _dtype(self, value):\n value = dtypes.as_dtype(value).name\n self._set_dtype_policy(policy.Policy(value))\n\n def _name_scope(self):\n if not tf2.enabled():\n return self.name\n name_scope = self.name\n current_name_scope = ops.get_name_scope()\n if current_name_scope:\n name_scope = current_name_scope + '/' + name_scope\n if name_scope:\n # Note that the trailing `/` prevents autogenerated\n # numerical suffixes to get appended. It will also fully reset\n # nested name scope (i.e. the outer name scope has no effect).\n name_scope += '/'\n return name_scope\n\n def _init_set_name(self, name, zero_based=True):\n if not name:\n self._name = backend.unique_object_name(\n generic_utils.to_snake_case(self.__class__.__name__),\n zero_based=zero_based)\n else:\n self._name = name\n\n def _get_existing_metric(self, name=None):\n match = [m for m in self._metrics if m.name == name]\n if not match:\n return\n if len(match) > 1:\n raise ValueError(\n 'Please provide different names for the metrics you have added. '\n 'We found {} metrics with the name: \"{}\"'.format(len(match), name))\n return match[0]\n\n def _handle_weight_regularization(self, name, variable, regularizer):\n \"\"\"Create lambdas which compute regularization losses.\"\"\"\n\n def _loss_for_variable(v):\n \"\"\"Creates a regularization loss `Tensor` for variable `v`.\"\"\"\n with backend.name_scope(name + '/Regularizer'):\n regularization = regularizer(v)\n return regularization\n\n if isinstance(variable, tf_variables.PartitionedVariable):\n for v in variable:\n self.add_loss(functools.partial(_loss_for_variable, v))\n else:\n self.add_loss(functools.partial(_loss_for_variable, variable))\n\n def _handle_activity_regularization(self, inputs, outputs):\n # Apply activity regularization.\n # Note that it should be applied every time the layer creates a new\n # output, since it is output-specific.\n if self._activity_regularizer:\n output_list = nest.flatten(outputs)\n with backend.name_scope('ActivityRegularizer'):\n for output in output_list:\n activity_loss = self._activity_regularizer(output)\n batch_size = math_ops.cast(\n array_ops.shape(output)[0], activity_loss.dtype)\n # Make activity regularization strength batch-agnostic.\n mean_activity_loss = activity_loss / batch_size\n self.add_loss(mean_activity_loss)\n\n def _set_mask_metadata(self, inputs, outputs, previous_mask, build_graph):\n # Many `Layer`s don't need to call `compute_mask`.\n # This method is optimized to do as little work as needed for the common\n # case.\n if not self._supports_masking:\n return\n\n flat_outputs = nest.flatten(outputs)\n\n mask_already_computed = (\n getattr(self, '_compute_output_and_mask_jointly', False) or\n all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs))\n if mask_already_computed:\n if build_graph:\n self._set_mask_keras_history_checked(flat_outputs)\n return\n\n output_masks = self.compute_mask(inputs, previous_mask)\n if output_masks is None:\n return\n\n flat_masks = nest.flatten(output_masks)\n for tensor, mask in zip(flat_outputs, flat_masks):\n try:\n tensor._keras_mask = mask\n except AttributeError:\n # C Type such as np.ndarray.\n pass\n\n if build_graph:\n self._set_mask_keras_history_checked(flat_outputs)\n\n def _set_mask_keras_history_checked(self, flat_outputs):\n for output in flat_outputs:\n if getattr(output, '_keras_mask', None) is not None:\n # Do not track masks for `TensorFlowOpLayer` construction.\n output._keras_mask._keras_history_checked = True\n\n def _get_input_masks(self, inputs, input_list, args, kwargs):\n if not self._supports_masking and not self._expects_mask_arg:\n # Input masks only need to be retrieved if they are needed for `call`\n # or `compute_mask`.\n input_masks = None\n implicit_mask = False\n elif self._call_arg_was_passed('mask', args, kwargs):\n input_masks = self._get_call_arg_value('mask', args, kwargs)\n implicit_mask = False\n else:\n input_masks = [getattr(t, '_keras_mask', None) for t in input_list]\n if all(mask is None for mask in input_masks):\n input_masks = None\n implicit_mask = False\n else:\n # Only do expensive `nest` op when masking is actually being used.\n input_masks = nest.pack_sequence_as(inputs, input_masks)\n implicit_mask = True\n return input_masks, implicit_mask\n\n def _call_arg_was_passed(self, arg_name, args, kwargs, inputs_in_args=False):\n # Performance optimization: do no work in most common case.\n if not args and not kwargs:\n return False\n\n if arg_name in kwargs:\n return True\n call_fn_args = self._call_fn_args\n if not inputs_in_args:\n # Ignore `inputs` arg.\n call_fn_args = call_fn_args[1:]\n return arg_name in dict(zip(call_fn_args, args))\n\n def _get_call_arg_value(self, arg_name, args, kwargs, inputs_in_args=False):\n if arg_name in kwargs:\n return kwargs[arg_name]\n call_fn_args = self._call_fn_args\n if not inputs_in_args:\n # Ignore `inputs` arg.\n call_fn_args = call_fn_args[1:]\n args_dict = dict(zip(call_fn_args, args))\n return args_dict[arg_name]\n\n def _set_call_arg_value(\n self, arg_name, new_value, args,\n kwargs, inputs_in_args=False, pop_kwarg_if_none=False):\n arg_pos = self._call_fn_arg_positions.get(arg_name, None)\n if arg_pos is not None:\n if not inputs_in_args:\n # Ignore `inputs` arg.\n arg_pos = arg_pos - 1\n if len(args) > arg_pos:\n args = list(args)\n args[arg_pos] = new_value\n return tuple(args), kwargs\n if new_value is None and pop_kwarg_if_none:\n kwargs.pop(arg_name, None)\n else:\n kwargs[arg_name] = new_value\n return args, kwargs\n\n def _set_connectivity_metadata(self, args, kwargs, outputs):\n # If the layer returns tensors from its inputs unmodified,\n # we copy them to avoid loss of KerasHistory metadata.\n flat_outputs = nest.flatten(outputs)\n flat_inputs = nest.flatten((args, kwargs))\n inputs_set = object_identity.ObjectIdentitySet(flat_inputs)\n outputs_copy = []\n for x in flat_outputs:\n if x in inputs_set:\n with backend.name_scope(self.name):\n x = array_ops.identity(x)\n outputs_copy.append(x)\n outputs = nest.pack_sequence_as(outputs, outputs_copy)\n\n # Create node, Node wires itself to inbound and outbound layers.\n # The Node constructor actually updates this layer's self._inbound_nodes,\n # sets _keras_history on the outputs, and adds itself to the\n # `_outbound_nodes` of the layers that produced the inputs to this\n # layer call.\n node_module.Node(self, call_args=args, call_kwargs=kwargs, outputs=outputs)\n return outputs\n\n def _get_node_attribute_at_index(self, node_index, attr, attr_name):\n \"\"\"Private utility to retrieves an attribute (e.g. inputs) from a node.\n\n This is used to implement the methods:\n - get_input_shape_at\n - get_output_shape_at\n - get_input_at\n etc...\n\n Arguments:\n node_index: Integer index of the node from which\n to retrieve the attribute.\n attr: Exact node attribute name.\n attr_name: Human-readable attribute name, for error messages.\n\n Returns:\n The layer's attribute `attr` at the node of index `node_index`.\n\n Raises:\n RuntimeError: If the layer has no inbound nodes, or if called in Eager\n mode.\n ValueError: If the index provided does not match any node.\n \"\"\"\n if not self._inbound_nodes:\n raise RuntimeError('The layer has never been called '\n 'and thus has no defined ' + attr_name + '.')\n if not len(self._inbound_nodes) > node_index:\n raise ValueError('Asked to get ' + attr_name + ' at node ' +\n str(node_index) + ', but the layer has only ' +\n str(len(self._inbound_nodes)) + ' inbound nodes.')\n values = getattr(self._inbound_nodes[node_index], attr)\n if isinstance(values, list) and len(values) == 1:\n return values[0]\n else:\n return values\n\n def _maybe_build(self, inputs):\n # Check input assumptions set before layer building, e.g. input rank.\n if not self.built:\n input_spec.assert_input_compatibility(\n self.input_spec, inputs, self.name)\n input_list = nest.flatten(inputs)\n if input_list and self._dtype_policy.compute_dtype is None:\n try:\n dtype = input_list[0].dtype.base_dtype.name\n except AttributeError:\n pass\n else:\n self._set_dtype_policy(policy.Policy(dtype))\n input_shapes = None\n # Converts Tensors / CompositeTensors to TensorShapes.\n if all(hasattr(x, 'shape') for x in input_list):\n input_shapes = tf_utils.get_shapes(inputs)\n else:\n # Converts input shape to TensorShapes.\n try:\n input_shapes = tf_utils.convert_shapes(inputs, to_tuples=False)\n except ValueError:\n pass\n # Only call `build` if the user has manually overridden the build method.\n if not hasattr(self.build, '_is_default'):\n # Any setup work performed only once should happen in an `init_scope`\n # to avoid creating symbolic Tensors that will later pollute any eager\n # operations.\n with tf_utils.maybe_init_scope(self):\n self.build(input_shapes) # pylint:disable=not-callable\n # We must set also ensure that the layer is marked as built, and the build\n # shape is stored since user defined build functions may not be calling\n # `super.build()`\n Layer.build(self, input_shapes)\n\n # Optionally load weight values specified at layer instantiation.\n if self._initial_weights is not None:\n if ops.executing_eagerly_outside_functions():\n with ops.init_scope():\n # Using `init_scope` since we want variable assignment in\n # `set_weights` to be treated like variable initialization.\n self.set_weights(self._initial_weights)\n else:\n self.set_weights(self._initial_weights)\n self._initial_weights = None\n\n def _symbolic_call(self, inputs):\n input_shapes = nest.map_structure(lambda x: x.shape, inputs)\n output_shapes = self.compute_output_shape(input_shapes)\n # Convert to TensorShape so that nest.map_structure will not map into\n # individual dim of the shape.\n output_shapes = tf_utils.convert_shapes(output_shapes, to_tuples=False)\n\n def _make_placeholder_like(shape):\n ph = backend.placeholder(shape=shape, dtype=self.dtype)\n ph._keras_mask = None\n return ph\n return nest.map_structure(_make_placeholder_like, output_shapes)\n\n def _get_trainable_state(self):\n \"\"\"Get the `trainable` state of each sublayer.\n\n Returns:\n A dict mapping all sublayers to their `trainable` value.\n \"\"\"\n trainable_state = weakref.WeakKeyDictionary()\n for layer in self._flatten_layers():\n trainable_state[layer] = layer.trainable\n return trainable_state\n\n def _set_trainable_state(self, trainable_state):\n \"\"\"Set `trainable` state for each sublayer.\"\"\"\n for layer in self._flatten_layers():\n if layer in trainable_state:\n layer.trainable = trainable_state[layer]\n\n @property\n def _obj_reference_counts(self):\n \"\"\"A dictionary counting the number of attributes referencing an object.\"\"\"\n self._maybe_create_attribute('_obj_reference_counts_dict',\n object_identity.ObjectIdentityDictionary())\n return self._obj_reference_counts_dict\n\n @trackable.no_automatic_dependency_tracking\n def _maybe_create_attribute(self, name, default_value):\n \"\"\"Create the attribute with the default value if it hasn't been created.\n\n This is useful for fields that is used for tracking purpose,\n _trainable_weights, or _layers. Note that user could create a layer subclass\n and assign an internal field before invoking the Layer.__init__(), the\n __setattr__() need to create the tracking fields and __init__() need to not\n override them.\n\n Args:\n name: String, the name of the attribute.\n default_value: Object, the default value of the attribute.\n \"\"\"\n if not hasattr(self, name):\n super(Layer, self).__setattr__(name, default_value)\n\n def __delattr__(self, name):\n # For any super.__delattr__() call, we will directly use the implementation\n # in Trackable and skip the behavior in AutoTrackable. The Layer was\n # originally use Trackable as base class, the change of using Module as base\n # class forced us to have AutoTrackable in the class hierarchy. Skipping\n # the __delattr__ and __setattr__ in AutoTrackable will keep the status quo.\n existing_value = getattr(self, name, None)\n\n # If this value is replacing an existing object assigned to an attribute, we\n # should clean it out to avoid leaking memory. First we check if there are\n # other attributes referencing it.\n reference_counts = self._obj_reference_counts\n if existing_value not in reference_counts:\n super(tracking.AutoTrackable, self).__delattr__(name)\n return\n\n reference_count = reference_counts[existing_value]\n if reference_count > 1:\n # There are other remaining references. We can't remove this object from\n # _layers etc.\n reference_counts[existing_value] = reference_count - 1\n super(tracking.AutoTrackable, self).__delattr__(name)\n return\n else:\n # This is the last remaining reference.\n del reference_counts[existing_value]\n\n super(tracking.AutoTrackable, self).__delattr__(name)\n\n if (isinstance(existing_value, Layer)\n or trackable_layer_utils.has_weights(existing_value)):\n super(tracking.AutoTrackable, self).__setattr__(\n '_layers',\n [l for l in self._layers if l is not existing_value])\n if isinstance(existing_value, tf_variables.Variable):\n super(tracking.AutoTrackable, self).__setattr__(\n '_trainable_weights',\n [w for w in self._trainable_weights if w is not existing_value])\n super(tracking.AutoTrackable, self).__setattr__(\n '_non_trainable_weights',\n [w for w in self._non_trainable_weights if w is not existing_value])\n\n def __setattr__(self, name, value):\n if (name == '_self_setattr_tracking' or\n not getattr(self, '_self_setattr_tracking', True) or\n # Exclude @property.setters from tracking\n hasattr(self.__class__, name)):\n try:\n super(tracking.AutoTrackable, self).__setattr__(name, value)\n except AttributeError:\n raise AttributeError(\n ('Can\\'t set the attribute \"{}\", likely because it conflicts with '\n 'an existing read-only @property of the object. Please choose a '\n 'different name.').format(name))\n return\n\n # Keep track of trackable objects, for the needs of `Network.save_weights`.\n value = data_structures.sticky_attribute_assignment(\n trackable=self, value=value, name=name)\n\n reference_counts = self._obj_reference_counts\n reference_counts[value] = reference_counts.get(value, 0) + 1\n\n # Clean out the old attribute, which clears _layers and _trainable_weights\n # if necessary.\n try:\n self.__delattr__(name)\n except AttributeError:\n pass\n\n # Keep track of metric instance created in subclassed layer.\n from tensorflow.python.keras import metrics as metrics_module # pylint: disable=g-import-not-at-top\n for val in nest.flatten(value):\n if isinstance(val, metrics_module.Metric) and hasattr(self, '_metrics'):\n self._metrics.append(val)\n\n # TODO(scottzhu): Need to track Module object as well for weight tracking.\n # Be careful about metric if it becomes a Module in future.\n # Append value to self._layers if relevant\n if (getattr(self, '_auto_track_sub_layers', True) and\n (isinstance(value, Layer) or trackable_layer_utils.has_weights(value))):\n self._maybe_create_attribute('_layers', [])\n # We need to check object identity to avoid de-duplicating empty\n # container types which compare equal.\n if not any((layer is value for layer in self._layers)):\n self._layers.append(value)\n if hasattr(value, '_use_resource_variables'):\n # Legacy layers (V1 tf.layers) must always use\n # resource variables.\n value._use_resource_variables = True\n\n # Append value to list of trainable / non-trainable weights if relevant\n # TODO(b/125122625): This won't pick up on any variables added to a\n # list/dict after creation.\n for val in nest.flatten(value):\n # TODO(b/126450014): Remove `_UnreadVariable` check here when assign ops\n # no longer return True for isinstance Variable checks.\n if not isinstance(val, tf_variables.Variable):\n continue\n if isinstance(val, resource_variable_ops._UnreadVariable): # pylint: disable=protected-access\n continue\n\n # Users may add extra weights/variables\n # simply by assigning them to attributes (invalid for graph networks)\n self._maybe_create_attribute('_trainable_weights', [])\n self._maybe_create_attribute('_non_trainable_weights', [])\n if val.trainable:\n if any(val is w for w in self._trainable_weights):\n continue\n self._trainable_weights.append(val)\n else:\n if any(val is w for w in self._non_trainable_weights):\n continue\n self._non_trainable_weights.append(val)\n\n backend.track_variable(val)\n\n # Skip the auto trackable from tf.Module to keep status quo. See the comment\n # at __delattr__.\n super(tracking.AutoTrackable, self).__setattr__(name, value)\n\n def _gather_children_attribute(self, attribute):\n assert attribute in {\n 'weights', 'trainable_weights', 'non_trainable_weights'\n }\n if hasattr(self, '_layers'):\n nested_layers = trackable_layer_utils.filter_empty_layer_containers(\n self._layers)\n return list(\n itertools.chain.from_iterable(\n getattr(layer, attribute) for layer in nested_layers))\n return []\n\n def _flatten_layers(self, recursive=True, include_self=True):\n if include_self:\n yield self\n\n # Only instantiate set and deque if needed.\n layers_or_containers = getattr(self, '_layers', None)\n if layers_or_containers:\n seen_object_ids = set()\n deque = collections.deque(layers_or_containers)\n while deque:\n layer_or_container = deque.popleft()\n\n layer_or_container_id = id(layer_or_container)\n if layer_or_container_id in seen_object_ids:\n continue\n seen_object_ids.add(layer_or_container_id)\n\n if isinstance(layer_or_container, Layer):\n yield layer_or_container\n # Introspect recursively through sublayers.\n if recursive:\n sublayers = getattr(layer_or_container, '_layers', None)\n if sublayers:\n deque.extendleft(reversed(sublayers))\n elif isinstance(layer_or_container,\n data_structures.TrackableDataStructure):\n # Data structures are introspected even with `recursive=False`.\n tracked_values = layer_or_container._values\n if tracked_values:\n deque.extendleft(reversed(tracked_values))\n\n # This is a hack so that the is_layer (within\n # training/trackable/layer_utils.py) check doesn't get the weights attr.\n # TODO(b/110718070): Remove when fixed.\n def _is_layer(self):\n return True\n\n def _init_call_fn_args(self):\n # Clear cached call function arguments.\n self.__class__._call_full_argspec.fget.cache.pop(self, None)\n self.__class__._call_fn_args.fget.cache.pop(self, None)\n self.__class__._call_accepts_kwargs.fget.cache.pop(self, None)\n\n call_fn_args = self._call_fn_args\n self._expects_training_arg = ('training' in call_fn_args or\n self._call_accepts_kwargs)\n # The default training arg will be any (non-None) default specified in the\n # method signature, or None if no value is specified.\n self._default_training_arg = self._call_fn_arg_defaults.get(\n 'training')\n self._expects_mask_arg = ('mask' in call_fn_args or\n self._call_accepts_kwargs)\n\n @property\n @tracking.cached_per_instance\n def _call_full_argspec(self):\n # Argspec inspection is expensive and the call spec is used often, so it\n # makes sense to cache the result.\n return tf_inspect.getfullargspec(self.call)\n\n @property\n @tracking.cached_per_instance\n def _call_fn_args(self):\n all_args = self._call_full_argspec.args\n # Scrub `self` that appears if a decorator was applied.\n if all_args and all_args[0] == 'self':\n return all_args[1:]\n return all_args\n\n @property\n @tracking.cached_per_instance\n def _call_fn_arg_defaults(self):\n call_fn_args = self._call_fn_args\n call_fn_defaults = self._call_full_argspec.defaults or []\n defaults = dict()\n\n # The call arg defaults are an n-tuple of the last n elements of the args\n # list. (n = # of elements that have a default argument)\n for i in range(-1 * len(call_fn_defaults), 0):\n defaults[call_fn_args[i]] = call_fn_defaults[i]\n return defaults\n\n @property\n @tracking.cached_per_instance\n def _call_fn_arg_positions(self):\n call_fn_arg_positions = dict()\n for pos, arg in enumerate(self._call_fn_args):\n call_fn_arg_positions[arg] = pos\n return call_fn_arg_positions\n\n @property\n @tracking.cached_per_instance\n def _call_accepts_kwargs(self):\n return self._call_full_argspec.varkw is not None\n\n @property\n def _eager_losses(self):\n # A list of loss values containing activity regularizers and losses\n # manually added through `add_loss` during eager execution. It is cleared\n # after every batch.\n # Because we plan on eventually allowing a same model instance to be trained\n # in eager mode or graph mode alternatively, we need to keep track of\n # eager losses and symbolic losses via separate attributes.\n if not hasattr(self._thread_local, '_eager_losses'):\n self._thread_local._eager_losses = []\n return self._thread_local._eager_losses\n\n @_eager_losses.setter\n def _eager_losses(self, losses):\n self._thread_local._eager_losses = losses\n\n def _dedup_weights(self, weights):\n \"\"\"Dedupe weights while maintaining order as much as possible.\"\"\"\n output, seen_weights = [], object_identity.ObjectIdentitySet()\n for w in weights:\n if w not in seen_weights:\n output.append(w)\n # Track the Variable's identity to avoid __eq__ issues.\n seen_weights.add(w)\n return output\n\n def _split_out_first_arg(self, args, kwargs):\n # Grab the argument corresponding to the first argument in the\n # layer's `call` method spec. This will either be the first positional\n # argument, or it will be provided as a keyword argument.\n if args:\n inputs = args[0]\n args = args[1:]\n elif self._call_fn_args[0] in kwargs:\n kwargs = copy.copy(kwargs)\n inputs = kwargs.pop(self._call_fn_args[0])\n else:\n raise ValueError(\n 'The first argument to `Layer.call` must always be passed.')\n return inputs, args, kwargs\n\n # SavedModel properties. Please see keras/saving/saved_model for details.\n\n @trackable.no_automatic_dependency_tracking\n def _set_save_spec(self, inputs):\n if self._saved_model_inputs_spec is not None:\n return # Already set.\n\n self._saved_model_inputs_spec = nest.map_structure(tf_utils.get_tensor_spec,\n inputs)\n\n def _get_save_spec(self, dynamic_batch=True):\n if self._saved_model_inputs_spec is None:\n return None\n\n return nest.map_structure(\n lambda t: tf_utils.get_tensor_spec(t, dynamic_batch=dynamic_batch),\n self._saved_model_inputs_spec)\n\n @property\n def _trackable_saved_model_saver(self):\n return layer_serialization.LayerSavedModelSaver(self)\n\n @property\n def _object_identifier(self):\n return self._trackable_saved_model_saver.object_identifier\n\n @property\n def _tracking_metadata(self):\n return self._trackable_saved_model_saver.tracking_metadata\n\n def _list_extra_dependencies_for_serialization(self, serialization_cache):\n return (self._trackable_saved_model_saver\n .list_extra_dependencies_for_serialization(serialization_cache))\n\n def _list_functions_for_serialization(self, serialization_cache):\n return (self._trackable_saved_model_saver\n .list_functions_for_serialization(serialization_cache))\n\n def __getstate__(self):\n # Override to support `copy.deepcopy` and pickling.\n # Thread-local objects cannot be copied in Python 3, so pop these.\n # Thread-local objects are used to cache losses in MirroredStrategy, and\n # so shouldn't be copied.\n state = self.__dict__.copy()\n state.pop('_thread_local', None)\n state.pop('_metrics_lock', None)\n return state\n\n def __setstate__(self, state):\n state['_thread_local'] = threading.local()\n state['_metrics_lock'] = threading.Lock()\n # Bypass Trackable logic as `__dict__` already contains this info.\n object.__setattr__(self, '__dict__', state)\n\n\nclass TensorFlowOpLayer(Layer):\n \"\"\"Wraps a TensorFlow Operation in a Layer.\n\n This class is used internally by the Functional API. When a user\n uses a raw TensorFlow Operation on symbolic tensors originating\n from an `Input` Layer, the resultant operation will be wrapped\n with this Layer object in order to make the operation compatible\n with the Keras API.\n\n This Layer will create a new, identical operation (except for inputs\n and outputs) every time it is called. If `run_eagerly` is `True`,\n the op creation and calculation will happen inside an Eager function.\n\n Instances of this Layer are created when `autolambda` is called, which\n is whenever a Layer's `__call__` encounters symbolic inputs that do\n not have Keras metadata, or when a Network's `__init__` encounters\n outputs that do not have Keras metadata.\n\n Attributes:\n node_def: String, the serialized NodeDef of the Op this layer will wrap.\n name: String, the name of the Layer.\n constants: Dict of NumPy arrays, the values of any Tensors needed for this\n Operation that do not originate from a Keras `Input` Layer. Since all\n placeholders must come from Keras `Input` Layers, these Tensors must be\n treated as constant in the Functional API.\n trainable: Bool, whether this Layer is trainable. Currently Variables are\n not supported, and so this parameter has no effect.\n dtype: The default dtype of this Layer. Inherited from `Layer` and has no\n effect on this class, however is used in `get_config`.\n \"\"\"\n\n @trackable.no_automatic_dependency_tracking\n def __init__(self,\n node_def,\n name,\n constants=None,\n trainable=True,\n dtype=None):\n # Pass autocast=False, as if inputs are cast, input types might not match\n # Operation type.\n super(TensorFlowOpLayer, self).__init__(\n name=_TF_OP_LAYER_NAME_PREFIX + name, trainable=trainable, dtype=dtype,\n autocast=False)\n _keras_layers_gauge.get_cell('TensorflowOpLayer').set(True)\n if isinstance(node_def, dict):\n self.node_def = json_format.ParseDict(node_def, node_def_pb2.NodeDef())\n else:\n if not isinstance(node_def, bytes):\n node_def = node_def.encode('utf-8')\n self.node_def = node_def_pb2.NodeDef.FromString(node_def)\n # JSON serialization stringifies keys which are integer input indices.\n self.constants = ({\n int(index): constant for index, constant in constants.items()\n } if constants is not None else {})\n # Layer uses original op unless it is called on new inputs.\n # This means `built` is not set in `__call__`.\n self.built = True\n\n def call(self, inputs):\n if context.executing_eagerly():\n return self._defun_call(inputs)\n return self._make_op(inputs)\n\n def _make_node_def(self, graph):\n node_def = node_def_pb2.NodeDef()\n node_def.CopyFrom(self.node_def)\n # Used in TPUReplicateContext to indicate whether this node has been cloned\n # and to not add TPU attributes.\n node_def.attr['_cloned'].b = True\n node_def.name = graph.unique_name(node_def.name)\n return node_def\n\n def _make_op(self, inputs):\n inputs = nest.flatten(inputs)\n graph = inputs[0].graph\n node_def = self._make_node_def(graph)\n with graph.as_default():\n for index, constant in self.constants.items():\n # Recreate constant in graph to add distribution context.\n value = tensor_util.constant_value(constant)\n if value is not None:\n constant = constant_op.constant(value, name=node_def.input[index])\n inputs.insert(index, constant)\n c_op = ops._create_c_op(graph, node_def, inputs, control_inputs=[])\n op = graph._create_op_from_tf_operation(c_op)\n op._control_flow_post_processing()\n\n # Record the gradient because custom-made ops don't go through the\n # code-gen'd eager call path\n op_type = compat.as_str(op.op_def.name)\n attr_names = [compat.as_str(attr.name) for attr in op.op_def.attr]\n attrs = []\n for attr_name in attr_names:\n attrs.append(attr_name)\n attrs.append(op.get_attr(attr_name))\n attrs = tuple(attrs)\n execute.record_gradient(op_type, op.inputs, attrs, op.outputs)\n\n if len(op.outputs) == 1:\n return op.outputs[0]\n return op.outputs\n\n @function.defun\n def _defun_call(self, inputs):\n \"\"\"Wraps the op creation method in an Eager function for `run_eagerly`.\"\"\"\n return self._make_op(inputs)\n\n def get_config(self):\n config = super(TensorFlowOpLayer, self).get_config()\n config.update({\n # `__init__` prefixes the name. Revert to the constructor argument.\n 'name': config['name'][len(_TF_OP_LAYER_NAME_PREFIX):],\n 'node_def': json_format.MessageToDict(self.node_def),\n 'constants': {\n i: backend.get_value(c) for i, c in self.constants.items()\n }\n })\n return config\n\n\nclass AddLoss(Layer):\n \"\"\"Adds its inputs as a loss.\n\n Attributes:\n unconditional: Whether or not the loss should be conditioned on the inputs.\n \"\"\"\n\n def __init__(self, unconditional, **kwargs):\n # Pass autocast=False, as there is no reason to cast loss to a different\n # dtype.\n kwargs['autocast'] = False\n super(AddLoss, self).__init__(**kwargs)\n self.unconditional = unconditional\n\n def call(self, inputs):\n self.add_loss(inputs, inputs=(not self.unconditional))\n return inputs\n\n def get_config(self):\n config = super(AddLoss, self).get_config()\n config.update({'unconditional': self.unconditional})\n return config\n\n\nclass AddMetric(Layer):\n \"\"\"Adds its inputs as a metric.\n\n Attributes:\n aggregation: 'mean' or None. How the inputs should be aggregated.\n metric_name: The name to use for this metric.\n \"\"\"\n\n def __init__(self, aggregation=None, metric_name=None, **kwargs):\n super(AddMetric, self).__init__(**kwargs)\n self.aggregation = aggregation\n self.metric_name = metric_name\n\n def call(self, inputs):\n self.add_metric(inputs, aggregation=self.aggregation, name=self.metric_name)\n return inputs\n\n def get_config(self):\n config = super(AddMetric, self).get_config()\n config.update({\n 'aggregation': self.aggregation,\n 'metric_name': self.metric_name\n })\n return config\n\n\ndef _in_functional_construction_mode(inputs, args, kwargs, input_list): # pylint: disable=unused-argument\n \"\"\"Check the arguments to see if we are constructing a functional model.\"\"\"\n if keras_tensor.keras_tensors_enabled():\n # We are constructing a functional model if any of the inputs\n # are KerasTensors\n return any(\n isinstance(tensor, keras_tensor.KerasTensor)\n for tensor in nest.flatten([inputs, args, kwargs]))\n else:\n if context.executing_eagerly():\n return all(tf_utils.is_symbolic_tensor(t) for t in input_list)\n else:\n return (base_layer_utils.is_in_keras_graph() or\n all(hasattr(t, '_keras_history') for t in input_list))\n\n\ndef _convert_numpy_or_python_types(x):\n if isinstance(x, (np.ndarray, float, int)):\n return ops.convert_to_tensor_v2(x)\n return x\n\n\n# Avoid breaking users who directly import this symbol from this file.\n# TODO(fchollet): remove this.\nInputSpec = input_spec.InputSpec # pylint:disable=invalid-name\n"
]
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_blobs\nimport pandas as pd\nfrom sklearn.preprocessing import Normalizer, MinMaxScaler\nfrom math import sqrt\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n\nclass KMeansModel():\n\n def __init__(self, K_clusters, X):\n self.K = K_clusters\n self.X = X\n self.Centres = np.random.rand(self.K, self.X.shape[1])\n self.Normalize()\n self.Classes = None\n self.N_Samples = self.X.shape[0]\n\n def GetEudlideanDistance(self, v1, v2):\n return sqrt(np.sum((v1-v2)**2))\n\n def FindClosestCentre(self, v1):\n # loops through all centres and returns the index of closest centre\n ClosestCentreDistance = float(\"inf\")\n ClosestCentreIndex = None\n for i in range(self.Centres.shape[0]):\n distance = self.GetEudlideanDistance(v1, self.Centres[i])\n if distance < ClosestCentreDistance:\n ClosestCentreDistance = distance\n ClosestCentreIndex = i\n return ClosestCentreIndex\n\n def MapClosestCentre(self):\n # This is done for each sample and creates a column vector where the \n # element at index i of the vector corresponds to the closest centre of\n # the ith sample\n Vec = []\n for i in range(self.N_Samples):\n Vec.append(self.FindClosestCentre(self.X[i]))\n\n self.Classes = np.array(Vec).reshape((-1, 1))\n\n def Normalize(self):\n # Normalizing function to express values between 0 and 1 \n N = MinMaxScaler()\n self.X = N.fit_transform(self.X)\n\n def ChangeCentres(self):\n # updates each centre to be the take on the mean position of each \n # sample which takes on the corresponding class of the centre\n for i in range(self.Centres.shape[0]): # we loop through all the centres \n self.Centres[i] = np.sum(\n # We use boolean indexing to only take the rows which correspond to the ith centre (the one we are currently re-calculating) \n self.X[np.array(km.Classes == i).reshape(1, -1)[0]], axis=0) / len(self.Classes[self.Classes == i]) # we divide by the number of samples in the class \n\nif __name__ == \"__main__\":\n # Creating some testing data \n k=2\n TrainingX, TrainingY = make_blobs(\n n_samples=1000, n_features=10, cluster_std=4, centers=k)\n km = KMeansModel(k, TrainingX)\n \n km.MapClosestCentre()\n\n\n for i in range(50):\n km.ChangeCentres()\n data = np.concatenate((km.X, km.Classes), axis=1)\n km.MapClosestCentre()\n \n # only uncomment if n_features =2 \n # plt.scatter(data[:, : -2], data[:, 1: -1], c=\"r\")\n # plt.scatter(km.Centres[:, [0]], km.Centres[:, [1]], c=\"b\")\n # plt.show()\n # print(np.concatenate((km.X, km.Classes), axis=1))\n\n # this code either yields a very low or high accuracy in most cases, this is just\n # becuase this is an unsupervised learning model and that the names of classes \n # are completely arbitrary. A better measure of accuracy the the confusion matrix, \n # which shows classes and their frequencies \n pred = km.Classes\n act = TrainingY.reshape(-1,1)\n print(np.concatenate((pred,act ), axis=1 ))\n print(confusion_matrix(pred,act ))\n print(accuracy_score(pred, act) *100,\"%\")\n"
]
[
"\"\"\"\nThis script operates on data from the qtm_extracted_data folder and populates the cleaned_data folder.\n\nThe objective of the script is to take the data from geographical format to a more simplified image based numerical format.\n\"\"\"\n\nimport os\nimport pandas as pd\nimport gdal\nfrom affine import Affine\n\nlandslides = pd.read_csv('data/qtm_extracted_data/landslides.csv', header=0)\nlandslides['DTM Path'] = [f'data/qtm_extracted_data/{name[-2]}.tif' for name in landslides['Name']] # path to tif file\n\npixels = []\nfor i, row in landslides.iterrows():\n ds = gdal.Open(row['DTM Path'])\n reverse = ~Affine.from_gdal(*ds.GetGeoTransform())\n coord = reverse * (row['X'], row['Y'])\n pixels.append((round(coord[0]), round(coord[1])))\n\nlandslides['X'] = [pixel[0] for pixel in pixels]\nlandslides['Y'] = [pixel[1] for pixel in pixels]\n\npoints = []\nfor tif in landslides['DTM Path'].unique():\n tif_landslides = landslides[landslides['DTM Path'] == tif]\n points.append(list(zip(tif_landslides['X'], tif_landslides['Y'])))\n\nclean_df = pd.DataFrame({'DTM Path': landslides['DTM Path'].unique(), 'Landslides': points},\n columns=['DTM Path', 'Landslides'])\nclean_df.to_pickle('data/cleaned_data/landslides_cleaned.pkl')\n# landslides[['Name', 'X', 'Y', 'DTM Path']].to_csv('cleaned_data/landslides_cleaned.csv')\n"
]
[
"# Copyright 2020 Huy Le Nguyen (@usimarit)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom tqdm import tqdm\nimport argparse\nfrom tensorflow_asr.utils import env_util, file_util\n\nlogger = env_util.setup_environment()\nimport tensorflow as tf\n\nDEFAULT_YAML = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"config.yml\")\n\ntf.keras.backend.clear_session()\n\nparser = argparse.ArgumentParser(prog=\"Conformer Testing\")\n\nparser.add_argument(\"--config\", type=str, default=DEFAULT_YAML, help=\"The file path of model configuration file\")\n\nparser.add_argument(\"--saved\", type=str, default=None, help=\"Path to saved model\")\n\nparser.add_argument(\"--mxp\", default=False, action=\"store_true\", help=\"Enable mixed precision\")\n\nparser.add_argument(\"--bs\", type=int, default=None, help=\"Test batch size\")\n\nparser.add_argument(\"--sentence_piece\", default=False, action=\"store_true\", help=\"Whether to use `SentencePiece` model\")\n\nparser.add_argument(\"--subwords\", default=False, action=\"store_true\", help=\"Use subwords\")\n\nparser.add_argument(\"--device\", type=int, default=0, help=\"Device's id to run test on\")\n\nparser.add_argument(\"--cpu\", default=False, action=\"store_true\", help=\"Whether to only use cpu\")\n\nparser.add_argument(\"--output\", type=str, default=\"test.tsv\", help=\"Result filepath\")\n\nargs = parser.parse_args()\n\nassert args.saved\n\ntf.config.optimizer.set_experimental_options({\"auto_mixed_precision\": args.mxp})\n\nenv_util.setup_devices([args.device], cpu=args.cpu)\n\nfrom tensorflow_asr.configs.config import Config\nfrom tensorflow_asr.datasets.asr_dataset import ASRSliceDataset\nfrom tensorflow_asr.featurizers.speech_featurizers import TFSpeechFeaturizer\nfrom tensorflow_asr.featurizers.text_featurizers import SubwordFeaturizer, SentencePieceFeaturizer, CharFeaturizer\nfrom tensorflow_asr.models.transducer.conformer import Conformer\nfrom tensorflow_asr.utils import app_util\n\nconfig = Config(args.config)\nspeech_featurizer = TFSpeechFeaturizer(config.speech_config)\n\nif args.sentence_piece:\n logger.info(\"Use SentencePiece ...\")\n text_featurizer = SentencePieceFeaturizer(config.decoder_config)\nelif args.subwords:\n logger.info(\"Use subwords ...\")\n text_featurizer = SubwordFeaturizer(config.decoder_config)\nelse:\n logger.info(\"Use characters ...\")\n text_featurizer = CharFeaturizer(config.decoder_config)\n\ntf.random.set_seed(0)\n\ntest_dataset = ASRSliceDataset(\n speech_featurizer=speech_featurizer,\n text_featurizer=text_featurizer,\n **vars(config.learning_config.test_dataset_config)\n)\n\n# build model\nconformer = Conformer(**config.model_config, vocabulary_size=text_featurizer.num_classes)\nconformer.make(speech_featurizer.shape)\nconformer.load_weights(args.saved, by_name=True)\nconformer.summary(line_length=100)\nconformer.add_featurizers(speech_featurizer, text_featurizer)\n\nbatch_size = args.bs or config.learning_config.running_config.batch_size\ntest_data_loader = test_dataset.create(batch_size)\n\nwith file_util.save_file(file_util.preprocess_paths(args.output)) as filepath:\n overwrite = True\n if tf.io.gfile.exists(filepath):\n overwrite = input(f\"Overwrite existing result file {filepath} ? (y/n): \").lower() == \"y\"\n if overwrite:\n results = conformer.predict(test_data_loader, verbose=1)\n logger.info(f\"Saving result to {args.output} ...\")\n with open(filepath, \"w\") as openfile:\n openfile.write(\"PATH\\tDURATION\\tGROUNDTRUTH\\tGREEDY\\tBEAMSEARCH\\n\")\n progbar = tqdm(total=test_dataset.total_steps, unit=\"batch\")\n for i, pred in enumerate(results):\n groundtruth, greedy, beamsearch = [x.decode('utf-8') for x in pred]\n path, duration, _ = test_dataset.entries[i]\n openfile.write(f\"{path}\\t{duration}\\t{groundtruth}\\t{greedy}\\t{beamsearch}\\n\")\n progbar.update(1)\n progbar.close()\n app_util.evaluate_results(filepath)\n"
]
[
"# coding: utf-8\n\nimport cv2\nimport numpy as np\n\nfrom shapely.geometry import mapping, Polygon as ShapelyPolygon\n\nfrom sd_lib.geometry.conversions import shapely_figure_to_coords_list\nfrom sd_lib.geometry.point_location import row_col_list_to_points, points_to_row_col_list\nfrom sd_lib.geometry.vector_geometry import VectorGeometry\nfrom sd_lib.geometry.constants import EXTERIOR, INTERIOR, POINTS, UPDATED_AT, CREATED_AT, ID, CLASS_ID #, , LABELER_LOGIN,\nfrom sd_lib.geometry import validation\nfrom sd_lib.sly_logger import logger\n\n\nclass Polygon(VectorGeometry):\n '''\n This is a class for creating and using Polygon objects for Labels\n '''\n @staticmethod\n def geometry_name():\n return 'polygon'\n\n def __init__(self, exterior, interior,\n sly_id=None, class_id=None, labeler_login=None, updated_at=None, created_at=None):\n '''\n :param exterior: list of PointLocation objects, the object contour is defined with these points\n :param interior: list of elements that has the same structure like the \"exterior\" field. This is the list of polygons that define object holes.\n '''\n if len(exterior) < 3:\n raise ValueError('\"{}\" field must contain at least 3 points to create \"Polygon\" object.'.format(EXTERIOR))\n if any(len(element) < 3 for element in interior):\n raise ValueError('\"{}\" element must contain at least 3 points.'.format(INTERIOR))\n\n super().__init__(exterior, interior, sly_id=sly_id, class_id=class_id, labeler_login=labeler_login,\n updated_at=updated_at, created_at=created_at)\n\n\n def crop(self, rect):\n '''\n Crop the current Polygon with a given rectangle, if polygon cat't be cropped it generate exception error\n :param rect: Rectangle class object\n :return: list of Poligon class objects\n '''\n try:\n clipping_window_shpl = ShapelyPolygon(points_to_row_col_list(rect.corners))\n self_shpl = ShapelyPolygon(self.exterior_np, holes=self.interior_np)\n intersections_shpl = self_shpl.buffer(0).intersection(clipping_window_shpl)\n mapping_shpl = mapping(intersections_shpl)\n except Exception:\n logger.warn('Polygon cropping exception, shapely.', exc_info=False)\n raise\n\n intersections = shapely_figure_to_coords_list(mapping_shpl)\n\n # Check for bad cropping cases (e.g. empty points list)\n out_polygons = []\n for intersection in intersections:\n if isinstance(intersection, list) and len(intersection) > 0 and len(intersection[0]) >= 3:\n exterior = row_col_list_to_points(intersection[0], do_round=True)\n interiors = []\n for interior_contour in intersection[1:]:\n if len(interior_contour) > 2:\n interiors.append(row_col_list_to_points(interior_contour, do_round=True))\n out_polygons.append(Polygon(exterior, interiors))\n return out_polygons\n\n def _draw_impl(self, bitmap, color, thickness=1, config=None):\n exterior = self.exterior_np[:, ::-1]\n interior = [x[:, ::-1] for x in self.interior_np]\n bmp_to_draw = np.zeros(bitmap.shape[:2], np.uint8)\n cv2.fillPoly(bmp_to_draw, pts=[exterior], color=1)\n cv2.fillPoly(bmp_to_draw, pts=interior, color=0)\n bool_mask = bmp_to_draw.astype(bool)\n bitmap[bool_mask] = color\n\n def _draw_contour_impl(self, bitmap, color, thickness=1, config=None):\n exterior = self.exterior_np[:, ::-1]\n interior = [x[:, ::-1] for x in self.interior_np]\n\n poly_lines = [exterior] + interior\n cv2.polylines(bitmap, pts=poly_lines, isClosed=True, color=color, thickness=thickness)\n\n # @TODO: extend possibilities, consider interior\n # returns area of exterior figure only\n @property\n def area(self):\n '''\n :return: area of current Poligon(exterior figure only)\n '''\n exterior = self.exterior_np\n return self._get_area_by_gauss_formula(exterior[:, 0], exterior[:, 1])\n\n @staticmethod\n def _get_area_by_gauss_formula(rows, cols):\n return 0.5 * np.abs(np.dot(rows, np.roll(cols, 1)) - np.dot(cols, np.roll(rows, 1)))\n\n def approx_dp(self, epsilon):\n '''\n The function approx_dp approximates a polygonal curve with the specified precision\n :param epsilon: Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation.\n :return: Poligon class object\n '''\n exterior_np = self._approx_ring_dp(self.exterior_np, epsilon, closed=True).tolist()\n interior_np = [self._approx_ring_dp(x, epsilon, closed=True).tolist() for x in self.interior_np]\n exterior = row_col_list_to_points(exterior_np, do_round=True)\n interior = [row_col_list_to_points(x, do_round=True) for x in interior_np]\n return Polygon(exterior, interior)\n"
]
[
"# import libraries\nfrom torchvision import models\nimport torch\n\n# create a dummy input with correct shape for the network\ndummy_input = torch.randn(16, 3, 224, 224, device='cuda')\n\n# created a resnet50 model\nmodel = models.resnet50(pretrained=True).cuda()\nmodel.eval()\n\n# Created dynamic axes for dynamic batch_size not required for static batch_size\ndynamic_axes = {\"actual_input_1\":{0:\"batch_size\"}, \"output1\":{0:\"batch_size\"}}\ninput_names = [ \"actual_input_1\" ]\noutput_names = [ \"output1\" ]\n\n# Export the model to onnx\ntorch.onnx.export(model, dummy_input, \"resnet50_dynamic.onnx\", \n verbose=False,input_names=input_names,\n output_names=output_names,dynamic_axes=dynamic_axes, export_params=True)\n"
]
[
"import pandas as pd\nimport re\nfrom .constants import ROSTER_SCHEME, SQUAD_URL\nfrom ..decorators import float_property_decorator, int_property_decorator\nfrom .fb_utils import _lookup_team\nfrom pyquery import PyQuery as pq\nfrom sportsreference.utils import (_get_stats_table,\n _parse_field,\n _remove_html_comment_tags)\n\n\nclass SquadPlayer:\n \"\"\"\n Get player information and stats.\n\n Given a player ID and data, capture all relevant stats and information for\n the player including name, nationality, goals, assists, expected goal\n difference, nutmegs, and much more.\n\n Parameters\n ----------\n player_data : PyQuery object\n A PyQuery object containing all fields of information for a single\n player, represented as one long row by concatenating all tables which\n hold values for the requested player.\n player_id : string\n A ``string`` representation of the player's unique 8-digit ID as shown\n on fbref.com.\n \"\"\"\n def __init__(self, player_data, player_id):\n self._name = None\n self._player_id = player_id\n self._nationality = None\n self._position = None\n self._age = None\n self._matches_played = None\n self._starts = None\n self._minutes = None\n self._goals = None\n self._assists = None\n self._penalty_kicks = None\n self._penalty_kick_attempts = None\n self._yellow_cards = None\n self._red_cards = None\n self._goals_per_90 = None\n self._assists_per_90 = None\n self._goals_and_assists_per_90 = None\n self._goals_non_penalty_per_90 = None\n self._goals_and_assists_non_penalty_per_90 = None\n self._expected_goals = None\n self._expected_goals_non_penalty = None\n self._expected_assists = None\n self._expected_goals_per_90 = None\n self._expected_assists_per_90 = None\n self._expected_goals_and_assists_per_90 = None\n self._expected_goals_non_penalty_per_90 = None\n self._expected_goals_and_assists_non_penalty_per_90 = None\n self._own_goals = None\n # Goalkeeping stats\n self._goals_against = None\n self._own_goals_against = None\n self._goals_against_per_90 = None\n self._shots_on_target_against = None\n self._saves = None\n self._save_percentage = None\n self._wins = None\n self._draws = None\n self._losses = None\n self._clean_sheets = None\n self._clean_sheet_percentage = None\n self._penalty_kicks_attempted = None\n self._penalty_kicks_allowed = None\n self._penalty_kicks_saved = None\n self._penalty_kicks_missed = None\n # Advanced goalkeeping stats\n self._free_kick_goals_against = None\n self._corner_kick_goals_against = None\n self._post_shot_expected_goals = None\n self._post_shot_expected_goals_per_shot = None\n self._post_shot_expected_goals_minus_allowed = None\n self._post_shot_expected_goals_minus_allowed_per_90 = None\n self._launches_completed = None\n self._launches_attempted = None\n self._launch_completion_percentage = None\n self._keeper_passes_attempted = None\n self._throws_attempted = None\n self._launch_percentage = None\n self._average_keeper_pass_length = None\n self._goal_kicks_attempted = None\n self._goal_kick_launch_percentage = None\n self._average_goal_kick_length = None\n self._opponent_cross_attempts = None\n self._opponent_cross_stops = None\n self._opponent_cross_stop_percentage = None\n self._keeper_actions_outside_penalty_area = None\n self._keeper_actions_outside_penalty_area_per_90 = None\n self._average_keeper_action_outside_penalty_distance = None\n # Shooting stats\n self._shots = None\n self._shots_on_target = None\n self._free_kick_shots = None\n self._shots_on_target_percentage = None\n self._shots_per_90 = None\n self._shots_on_target_per_90 = None\n self._goals_per_shot = None\n self._goals_per_shot_on_target = None\n self._expected_goals_non_penalty_per_shot = None\n self._goals_minus_expected = None\n self._non_penalty_minus_expected_non_penalty = None\n # Passing stats\n self._assists_minus_expected = None\n self._key_passes = None\n self._passes_completed = None\n self._passes_attempted = None\n self._pass_completion = None\n self._short_passes_completed = None\n self._short_passes_attempted = None\n self._short_pass_completion = None\n self._medium_passes_completed = None\n self._medium_passes_attempted = None\n self._medium_pass_completion = None\n self._long_passes_completed = None\n self._long_passes_attempted = None\n self._long_pass_completion = None\n self._left_foot_passes = None\n self._right_foot_passes = None\n self._free_kick_passes = None\n self._through_balls = None\n self._corner_kicks = None\n self._throw_ins = None\n self._final_third_passes = None\n self._penalty_area_passes = None\n self._penalty_area_crosses = None\n # Playing time stats\n self._minutes_per_match = None\n self._minutes_played_percentage = None\n self._nineties_played = None\n self._minutes_per_start = None\n self._subs = None\n self._minutes_per_sub = None\n self._unused_sub = None\n self._points_per_match = None\n self._goals_scored_on_pitch = None\n self._goals_against_on_pitch = None\n self._goal_difference_on_pitch = None\n self._goal_difference_on_pitch_per_90 = None\n self._net_difference_on_pitch_per_90 = None\n self._expected_goals_on_pitch = None\n self._expected_goals_against_on_pitch = None\n self._expected_goal_difference = None\n self._expected_goal_difference_per_90 = None\n self._net_expected_goal_difference_per_90 = None\n # Miscellaneous stats\n self._soft_reds = None\n self._fouls_committed = None\n self._fouls_drawn = None\n self._offsides = None\n self._crosses = None\n self._tackles_won = None\n self._interceptions = None\n self._penalty_kicks_won = None\n self._penalty_kicks_conceded = None\n self._successful_dribbles = None\n self._attempted_dribbles = None\n self._dribble_success_rate = None\n self._players_dribbled_past = None\n self._nutmegs = None\n self._dribblers_tackled = None\n self._dribblers_contested = None\n self._tackle_percentage = None\n self._times_dribbled_past = None\n\n self._parse_player_stats(player_data)\n\n def _parse_nationality(self, player_data):\n \"\"\"\n Parse the player's nationality.\n\n If the nationality is listed for a player, it will contain a URI which\n includes the name of the country the player represents. For example, an\n English player would have a URI of the following:\n \"/en/country/ENG/England-Football\". Pulling out the country name and\n returning it as a string is a simple solution to pulling someone's\n nationality.\n\n Parameters\n ----------\n player_data : PyQuery object\n A PyQuery object representing all of the player's stats fields\n combined as a singular row.\n\n Returns\n -------\n string\n Returns a ``string`` of the player's home country, such as\n 'England'.\n \"\"\"\n country = player_data(ROSTER_SCHEME['nationality'])\n if not country:\n return None\n country = country.attr('href')\n country = re.sub(r'.*\\/', '', country)\n country = country.replace('-Football', '')\n return country\n\n def _parse_player_stats(self, player_data):\n \"\"\"\n Parse a value for every attribute.\n\n This method looks through every class attribute with a few exceptions\n and retrieves the value according to the parsing scheme and index of\n the attribute from the passed HTML data. Once the value is retrieved,\n the attribute's value is updated with the returned result.\n\n Parameters\n ----------\n player_data : string\n A ``string`` representation of all of the player's stats fields\n combined as a singular row.\n player_id : string\n A ``string`` of the player's unique 8-digit ID.\n \"\"\"\n for field in self.__dict__:\n # The short field truncates the leading '_' in the attribute name.\n short_field = str(field)[1:]\n if short_field == 'player_id':\n continue\n if short_field == 'nationality':\n value = self._parse_nationality(player_data)\n else:\n value = _parse_field(ROSTER_SCHEME, player_data, short_field)\n setattr(self, field, value)\n\n @property\n def dataframe(self):\n \"\"\"\n Returns a pandas ``DataFame`` containing all other class properties\n and values. The index for the DataFrame is the player ID.\n \"\"\"\n fields_to_include = {\n 'name': self.name,\n 'player_id': self.player_id,\n 'nationality': self.nationality,\n 'position': self.position,\n 'age': self.age,\n 'matches_played': self.matches_played,\n 'starts': self.starts,\n 'minutes': self.minutes,\n 'goals': self.goals,\n 'assists': self.assists,\n 'penalty_kicks': self.penalty_kicks,\n 'penalty_kick_attempts': self.penalty_kick_attempts,\n 'yellow_cards': self.yellow_cards,\n 'red_cards': self.red_cards,\n 'goals_per_90': self.goals_per_90,\n 'assists_per_90': self.assists_per_90,\n 'goals_and_assists_per_90': self.goals_and_assists_per_90,\n 'goals_non_penalty_per_90': self.goals_non_penalty_per_90,\n 'goals_and_assists_non_penalty_per_90':\n self.goals_and_assists_non_penalty_per_90,\n 'expected_goals': self.expected_goals,\n 'expected_goals_non_penalty': self.expected_goals_non_penalty,\n 'expected_assists': self.expected_assists,\n 'expected_goals_per_90': self.expected_goals_per_90,\n 'expected_assists_per_90': self.expected_assists_per_90,\n 'expected_goals_and_assists_per_90':\n self.expected_goals_and_assists_per_90,\n 'expected_goals_non_penalty_per_90':\n self.expected_goals_non_penalty_per_90,\n 'expected_goals_and_assists_non_penalty_per_90':\n self.expected_goals_and_assists_non_penalty_per_90,\n 'own_goals': self.own_goals,\n 'goals_against': self.goals_against,\n 'own_goals_against': self.own_goals_against,\n 'goals_against_per_90': self.goals_against_per_90,\n 'shots_on_target_against': self.shots_on_target_against,\n 'saves': self.saves,\n 'save_percentage': self.save_percentage,\n 'wins': self.wins,\n 'draws': self.draws,\n 'losses': self.losses,\n 'clean_sheets': self.clean_sheets,\n 'clean_sheet_percentage': self.clean_sheet_percentage,\n 'penalty_kicks_attempted': self.penalty_kicks_attempted,\n 'penalty_kicks_allowed': self.penalty_kicks_allowed,\n 'penalty_kicks_saved': self.penalty_kicks_saved,\n 'penalty_kicks_missed': self.penalty_kicks_missed,\n 'free_kick_goals_against': self.free_kick_goals_against,\n 'corner_kick_goals_against': self.corner_kick_goals_against,\n 'post_shot_expected_goals': self.post_shot_expected_goals,\n 'post_shot_expected_goals_per_shot':\n self.post_shot_expected_goals_per_shot,\n 'post_shot_expected_goals_minus_allowed':\n self.post_shot_expected_goals_minus_allowed,\n 'launches_completed': self.launches_completed,\n 'launches_attempted': self.launches_attempted,\n 'launch_completion_percentage': self.launch_completion_percentage,\n 'keeper_passes_attempted': self.keeper_passes_attempted,\n 'throws_attempted': self.throws_attempted,\n 'launch_percentage': self.launch_percentage,\n 'average_keeper_pass_length': self.average_keeper_pass_length,\n 'goal_kicks_attempted': self.goal_kicks_attempted,\n 'goal_kick_launch_percentage': self.goal_kick_launch_percentage,\n 'average_goal_kick_length': self.average_goal_kick_length,\n 'opponent_cross_attempts': self.opponent_cross_attempts,\n 'opponent_cross_stops': self.opponent_cross_stops,\n 'opponent_cross_stop_percentage':\n self.opponent_cross_stop_percentage,\n 'keeper_actions_outside_penalty_area':\n self.keeper_actions_outside_penalty_area,\n 'keeper_actions_outside_penalty_area_per_90':\n self.keeper_actions_outside_penalty_area_per_90,\n 'average_keeper_action_outside_penalty_distance':\n self.average_keeper_action_outside_penalty_distance,\n 'shots': self.shots,\n 'shots_on_target': self.shots_on_target,\n 'free_kick_shots': self.free_kick_shots,\n 'shots_on_target_percentage': self.shots_on_target_percentage,\n 'shots_per_90': self.shots_per_90,\n 'shots_on_target_per_90': self.shots_on_target_per_90,\n 'goals_per_shot': self.goals_per_shot,\n 'goals_per_shot_on_target': self.goals_per_shot_on_target,\n 'expected_goals_non_penalty_per_shot':\n self.expected_goals_non_penalty_per_shot,\n 'goals_minus_expected': self.goals_minus_expected,\n 'non_penalty_minus_expected_non_penalty':\n self.non_penalty_minus_expected_non_penalty,\n 'assists_minus_expected': self.assists_minus_expected,\n 'key_passes': self.key_passes,\n 'passes_completed': self.passes_completed,\n 'passes_attempted': self.passes_attempted,\n 'pass_completion': self.pass_completion,\n 'short_passes_completed': self.short_passes_completed,\n 'short_passes_attempted': self.short_passes_attempted,\n 'short_pass_completion': self.short_pass_completion,\n 'medium_passes_completed': self.medium_passes_completed,\n 'medium_passes_attempted': self.medium_passes_attempted,\n 'medium_pass_completion': self.medium_pass_completion,\n 'long_passes_completed': self.long_passes_completed,\n 'long_passes_attempted': self.long_passes_attempted,\n 'long_pass_completion': self.long_pass_completion,\n 'left_foot_passes': self.left_foot_passes,\n 'right_foot_passes': self.right_foot_passes,\n 'free_kick_passes': self.free_kick_passes,\n 'through_balls': self.through_balls,\n 'corner_kicks': self.corner_kicks,\n 'throw_ins': self.throw_ins,\n 'final_third_passes': self.final_third_passes,\n 'penalty_area_passes': self.penalty_area_passes,\n 'penalty_area_crosses': self.penalty_area_crosses,\n 'minutes_per_match': self.minutes_per_match,\n 'minutes_played_percentage': self.minutes_played_percentage,\n 'nineties_played': self.nineties_played,\n 'minutes_per_start': self.minutes_per_start,\n 'subs': self.subs,\n 'minutes_per_sub': self.minutes_per_sub,\n 'unused_sub': self.unused_sub,\n 'points_per_match': self.points_per_match,\n 'goals_scored_on_pitch': self.goals_scored_on_pitch,\n 'goals_against_on_pitch': self.goals_against_on_pitch,\n 'goal_difference_on_pitch': self.goal_difference_on_pitch,\n 'goal_difference_on_pitch_per_90':\n self.goal_difference_on_pitch_per_90,\n 'net_difference_on_pitch_per_90':\n self.net_difference_on_pitch_per_90,\n 'expected_goals_on_pitch': self.expected_goals_on_pitch,\n 'expected_goals_against_on_pitch':\n self.expected_goals_against_on_pitch,\n 'expected_goal_difference': self.expected_goal_difference,\n 'expected_goal_difference_per_90':\n self.expected_goal_difference_per_90,\n 'net_expected_goal_difference_per_90':\n self.net_expected_goal_difference_per_90,\n 'soft_reds': self.soft_reds,\n 'fouls_committed': self.fouls_committed,\n 'fouls_drawn': self.fouls_drawn,\n 'offsides': self.offsides,\n 'crosses': self.crosses,\n 'tackles_won': self.tackles_won,\n 'interceptions': self.interceptions,\n 'penalty_kicks_won': self.penalty_kicks_won,\n 'penalty_kicks_conceded': self.penalty_kicks_conceded,\n 'successful_dribbles': self.successful_dribbles,\n 'attempted_dribbles': self.attempted_dribbles,\n 'dribble_success_rate': self.dribble_success_rate,\n 'players_dribbled_past': self.players_dribbled_past,\n 'nutmegs': self.nutmegs,\n 'dribblers_tackled': self.dribblers_tackled,\n 'dribblers_contested': self.dribblers_contested,\n 'tackle_percentage': self.tackle_percentage,\n 'times_dribbled_past': self.times_dribbled_past\n }\n return pd.DataFrame([fields_to_include], index=[self.player_id])\n\n @property\n def name(self):\n \"\"\"\n Returns a ``string`` of the player's full name, such as 'Harry Kane'.\n \"\"\"\n return self._name\n\n @property\n def player_id(self):\n \"\"\"\n Returns a ``string`` of the player's 8-digit ID, such as '21a66f6a' for\n Harry Kane.\n \"\"\"\n return self._player_id\n\n @property\n def nationality(self):\n \"\"\"\n Returns a ``string`` of the player's home country, such as 'England'.\n \"\"\"\n return self._nationality\n\n @property\n def position(self):\n \"\"\"\n Returns a ``string`` of the player's primary position(s). Multiple\n positions are separated by commas.\n \"\"\"\n return self._position\n\n @int_property_decorator\n def age(self):\n \"\"\"\n Returns an ``int`` of the player's age as of August 1 for winter\n leagues and February 1 for summer leagues for the given season.\n \"\"\"\n return self._age\n\n @int_property_decorator\n def matches_played(self):\n \"\"\"\n Returns an ``int`` of the number of matches the player has participated\n in.\n \"\"\"\n return self._matches_played\n\n @int_property_decorator\n def starts(self):\n \"\"\"\n Returns an ``int`` of the number of games the player has started.\n \"\"\"\n return self._starts\n\n @int_property_decorator\n def minutes(self):\n \"\"\"\n Returns an ``int`` of the number of minutes the player has spent on the\n field in all competitions.\n \"\"\"\n return self._minutes.replace(',', '')\n\n @int_property_decorator\n def goals(self):\n \"\"\"\n Returns an ``int`` of the number of goals the player has scored.\n \"\"\"\n return self._goals\n\n @int_property_decorator\n def assists(self):\n \"\"\"\n Returns an ``int`` of the number of goals the player has assisted.\n \"\"\"\n return self._assists\n\n @int_property_decorator\n def penalty_kicks(self):\n \"\"\"\n Returns an ``int`` of the number of penalty kicks the player has scored\n during regular play.\n \"\"\"\n return self._penalty_kicks\n\n @int_property_decorator\n def penalty_kick_attempts(self):\n \"\"\"\n Returns an ``int`` of the number of penalty kicks the player has\n attempted.\n \"\"\"\n return self._penalty_kick_attempts\n\n @int_property_decorator\n def yellow_cards(self):\n \"\"\"\n Returns an ``int`` of the number of yellow cards the player has\n accumulated during the season.\n \"\"\"\n return self._yellow_cards\n\n @int_property_decorator\n def red_cards(self):\n \"\"\"\n Returns an ``int`` of the number of red cards the player has\n accumulated during the season.\n \"\"\"\n return self._red_cards\n\n @float_property_decorator\n def goals_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of goals the player has scored per\n 90 minutes on the field.\n \"\"\"\n return self._goals_per_90\n\n @float_property_decorator\n def assists_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of goals the player has assisted per\n 90 minutes on the field.\n \"\"\"\n return self._assists_per_90\n\n @float_property_decorator\n def goals_and_assists_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of goals the player has either scored\n or assisted per 90 minutes on the field.\n \"\"\"\n return self._goals_and_assists_per_90\n\n @float_property_decorator\n def goals_non_penalty_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of non-penalty goals the player has\n scored per 90 minutes on the field.\n \"\"\"\n return self._goals_non_penalty_per_90\n\n @float_property_decorator\n def goals_and_assists_non_penalty_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of non-penalty goals the player has\n either scored or assisted per 90 minutes on the field.\n \"\"\"\n return self._goals_and_assists_non_penalty_per_90\n\n @float_property_decorator\n def expected_goals(self):\n \"\"\"\n Returns a ``float`` of the number of goals the player was expected to\n score based on the quality and quantity of shots taken.\n \"\"\"\n return self._expected_goals\n\n @float_property_decorator\n def expected_goals_non_penalty(self):\n \"\"\"\n Returns a ``float`` of the number of non-penalty goals the player was\n expected to score based on the quality and quantity of shots taken.\n \"\"\"\n return self._expected_goals_non_penalty\n\n @float_property_decorator\n def expected_assists(self):\n \"\"\"\n Returns a ``float`` of the number of goals the player was expected go\n assist based on the quality and quantity of teammate shots taken.\n \"\"\"\n return self._expected_assists\n\n @float_property_decorator\n def expected_goals_per_90(self):\n \"\"\"\n Returns a ``float`` of the player's expected goals per 90 minutes\n played.\n \"\"\"\n return self._expected_goals_per_90\n\n @float_property_decorator\n def expected_assists_per_90(self):\n \"\"\"\n Returns a ``float`` of the player's expected assists per 90 minutes\n played.\n \"\"\"\n return self._expected_assists_per_90\n\n @float_property_decorator\n def expected_goals_and_assists_per_90(self):\n \"\"\"\n Returns a ``float`` of the player's expected goals and assists per 90\n minutes played.\n \"\"\"\n return self._expected_goals_and_assists_per_90\n\n @float_property_decorator\n def expected_goals_non_penalty_per_90(self):\n \"\"\"\n Returns a ``float`` of the player's expected non-penalty goals per 90\n minutes played.\n \"\"\"\n return self._expected_goals_non_penalty_per_90\n\n @float_property_decorator\n def expected_goals_and_assists_non_penalty_per_90(self):\n \"\"\"\n Returns a ``float`` of the player's expected non-penalty goals and\n assists per 90 minutes played.\n \"\"\"\n return self._expected_goals_and_assists_non_penalty_per_90\n\n @int_property_decorator\n def own_goals(self):\n \"\"\"\n Returns an ``int`` of the number of own goals the player has conceded.\n \"\"\"\n return self._own_goals\n\n @int_property_decorator\n def goals_against(self):\n \"\"\"\n Returns an ``int`` of the number of goals a keeper has conceded.\n \"\"\"\n return self._goals_against\n\n @int_property_decorator\n def own_goals_against(self):\n \"\"\"\n Returns an ``int`` of the number of own goals the team scored on a\n keeper.\n \"\"\"\n return self._own_goals_against\n\n @float_property_decorator\n def goals_against_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of goals a keeper has coneceded per\n 90 minutes played.\n \"\"\"\n return self._goals_against_per_90\n\n @int_property_decorator\n def shots_on_target_against(self):\n \"\"\"\n Returns an ``int`` of the number of shots on target a keeper has faced.\n \"\"\"\n return self._shots_on_target_against\n\n @int_property_decorator\n def saves(self):\n \"\"\"\n Returns an ``int`` of the number of shots a keeper has saved.\n \"\"\"\n return self._saves\n\n @float_property_decorator\n def save_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of shots the keeper saved.\n Percentage ranges from 0-1.\n \"\"\"\n return self._save_percentage\n\n @int_property_decorator\n def wins(self):\n \"\"\"\n Returns an ``int`` of the number of games a keeper has won.\n \"\"\"\n return self._wins\n\n @int_property_decorator\n def draws(self):\n \"\"\"\n Returns an ``int`` of the number of games a keeper has drawn.\n \"\"\"\n return self._draws\n\n @int_property_decorator\n def losses(self):\n \"\"\"\n Returns an ``int`` of the number of games a keeper has lost.\n \"\"\"\n return self._losses\n\n @int_property_decorator\n def clean_sheets(self):\n \"\"\"\n Returns an ``int`` of the number of clean sheets a keeper has\n registered.\n \"\"\"\n return self._clean_sheets\n\n @float_property_decorator\n def clean_sheet_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of games a keeper has\n participated in that resulted in a clean sheet.\n \"\"\"\n return self._clean_sheet_percentage\n\n @int_property_decorator\n def penalty_kicks_attempted(self):\n \"\"\"\n Returns an ``int`` of the number of penalty kicks a keeper has faced\n during regular play.\n \"\"\"\n return self._penalty_kicks_attempted\n\n @int_property_decorator\n def penalty_kicks_allowed(self):\n \"\"\"\n Returns an ``int`` of the number of penalty kicks a keeper has conceded\n during regular play.\n \"\"\"\n return self._penalty_kicks_allowed\n\n @int_property_decorator\n def penalty_kicks_saved(self):\n \"\"\"\n Returns an ``int`` of the number of penalty kicks a keeper has saved\n during regular play.\n \"\"\"\n return self._penalty_kicks_saved\n\n @int_property_decorator\n def penalty_kicks_missed(self):\n \"\"\"\n Returns an ``int`` of the number of penalty kicks a keeper has faced\n where the opponent missed the goal.\n \"\"\"\n return self._penalty_kicks_missed\n\n @int_property_decorator\n def free_kick_goals_against(self):\n \"\"\"\n Returns an ``int`` of the number of goals a keeper conceded as a result\n of an opponent's free kick.\n \"\"\"\n return self._free_kick_goals_against\n\n @int_property_decorator\n def corner_kick_goals_against(self):\n \"\"\"\n Returns an ``int`` of the number of goals a keeper conceded as a result\n of an opponent's corner kick.\n \"\"\"\n return self._corner_kick_goals_against\n\n @float_property_decorator\n def post_shot_expected_goals(self):\n \"\"\"\n Returns a ``float`` of the number of goals a keeper was expected to\n concede.\n \"\"\"\n return self._post_shot_expected_goals\n\n @float_property_decorator\n def post_shot_expected_goals_per_shot(self):\n \"\"\"\n Returns a ``float`` of the number of goals a keeper was expected to\n concede per shot faced.\n \"\"\"\n return self._post_shot_expected_goals_per_shot\n\n @float_property_decorator\n def post_shot_expected_goals_minus_allowed(self):\n \"\"\"\n Returns a ``float`` of the number of goals a keeper was expected to\n concede minus the number of goals they actually conceded.\n \"\"\"\n return self._post_shot_expected_goals_minus_allowed\n\n @float_property_decorator\n def post_shot_expected_goals_minus_allowed_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of goals a keeper was expected to\n concede minus the number of goals they actually conceded, per 90\n minutes played.\n \"\"\"\n return self._post_shot_expected_goals_minus_allowed_per_90\n\n @int_property_decorator\n def launches_completed(self):\n \"\"\"\n Returns an ``int`` of the number of passes longer than 40 yards a\n keeper completed.\n \"\"\"\n return self._launches_completed\n\n @int_property_decorator\n def launches_attempted(self):\n \"\"\"\n Returns an ``int`` of the number of passes longer than 40 yards a\n keeper attempted.\n \"\"\"\n return self._launches_attempted\n\n @float_property_decorator\n def launch_completion_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of passes longer than 40 yards a\n keeper completed. Percentage ranges from 0-100.\n \"\"\"\n return self._launch_completion_percentage\n\n @int_property_decorator\n def keeper_passes_attempted(self):\n \"\"\"\n Returns an ``int`` of the number of non-goal kick passes a keeper\n attempted.\n \"\"\"\n return self._keeper_passes_attempted\n\n @int_property_decorator\n def throws_attempted(self):\n \"\"\"\n Returns an ``int`` of the number of throws a keeper attempted.\n \"\"\"\n return self._throws_attempted\n\n @float_property_decorator\n def launch_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of passes a keeper makes longer\n than 40 yards excluding goal kicks. Percentage ranges from 0-100.\n \"\"\"\n return self._launch_percentage\n\n @float_property_decorator\n def average_keeper_pass_length(self):\n \"\"\"\n Returns a ``float`` of the average pass length for a keeper in yards\n excluding goal kicks.\n \"\"\"\n return self._average_keeper_pass_length\n\n @int_property_decorator\n def goal_kicks_attempted(self):\n \"\"\"\n Returns an ``int`` of the number of goal kicks a keeper attempted.\n \"\"\"\n return self._goal_kicks_attempted\n\n @float_property_decorator\n def goal_kick_launch_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of goal kicks a keeper has\n launched further than 40 yards. Percentage ranges from 0-100.\n \"\"\"\n return self._goal_kick_launch_percentage\n\n @float_property_decorator\n def average_goal_kick_length(self):\n \"\"\"\n Returns a ``float`` of the average pass length for goal kicks in yards\n for a keeper.\n \"\"\"\n return self._average_goal_kick_length\n\n @int_property_decorator\n def opponent_cross_attempts(self):\n \"\"\"\n Returns an ``int`` of the number of crosses a keeper has faced.\n \"\"\"\n return self._opponent_cross_attempts\n\n @int_property_decorator\n def opponent_cross_stops(self):\n \"\"\"\n Returns an ``int`` of the number of crosses a keeper has successfully\n stopped.\n \"\"\"\n return self._opponent_cross_stops\n\n @float_property_decorator\n def opponent_cross_stop_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of crosses the keeper has\n successfully stopped. Percentage ranges from 0-100.\n \"\"\"\n return self._opponent_cross_stop_percentage\n\n @int_property_decorator\n def keeper_actions_outside_penalty_area(self):\n \"\"\"\n Returns an ``int`` of the number of defensive actions a keeper made\n outside the penalty area.\n \"\"\"\n return self._keeper_actions_outside_penalty_area\n\n @float_property_decorator\n def keeper_actions_outside_penalty_area_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of defensive actions a keeper made\n outside the penalty area per 90 minutes played.\n \"\"\"\n return self._keeper_actions_outside_penalty_area_per_90\n\n @float_property_decorator\n def average_keeper_action_outside_penalty_distance(self):\n \"\"\"\n Returns a ``float`` of the average distance from goal in yards a keeper\n performed a defensive action outside the penalty area.\n \"\"\"\n return self._average_keeper_action_outside_penalty_distance\n\n @int_property_decorator\n def shots(self):\n \"\"\"\n Returns an ``int`` of the number of shots the player has taken.\n \"\"\"\n return self._shots\n\n @int_property_decorator\n def shots_on_target(self):\n \"\"\"\n Returns an ``int`` of the number of shots on target the player has\n taken.\n \"\"\"\n return self._shots_on_target\n\n @int_property_decorator\n def free_kick_shots(self):\n \"\"\"\n Returns an ``int`` of the number of shots the player has taken from\n free kicks.\n \"\"\"\n return self._free_kick_shots\n\n @float_property_decorator\n def shots_on_target_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of shots taken by the player that\n were on target. Percentage ranges from 0-100.\n \"\"\"\n return self._shots_on_target_percentage\n\n @float_property_decorator\n def shots_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of shots the player has taken per 90\n minutes played.\n \"\"\"\n return self._shots_per_90\n\n @float_property_decorator\n def shots_on_target_per_90(self):\n \"\"\"\n Returns a ``float`` of the number of shots on target the player has\n taken per 90 minutes played.\n \"\"\"\n return self._shots_on_target_per_90\n\n @float_property_decorator\n def goals_per_shot(self):\n \"\"\"\n Returns a ``float`` of the average number of goals scored per shot\n taken by the player.\n \"\"\"\n return self._goals_per_shot\n\n @float_property_decorator\n def goals_per_shot_on_target(self):\n \"\"\"\n Returns a ``float`` of the average number of goals scored per shot on\n target by the player.\n \"\"\"\n return self._goals_per_shot_on_target\n\n @float_property_decorator\n def expected_goals_non_penalty_per_shot(self):\n \"\"\"\n Returns a ``float`` of the nuber of non-penalty goals the player was\n expected to score per shot.\n \"\"\"\n return self._expected_goals_non_penalty_per_shot\n\n @float_property_decorator\n def goals_minus_expected(self):\n \"\"\"\n Returns a ``float`` of the number of goals scored minus the number of\n goals the player was expected to score.\n \"\"\"\n return self._goals_minus_expected\n\n @float_property_decorator\n def non_penalty_minus_expected_non_penalty(self):\n \"\"\"\n Returns a ``float`` of the number of non-penalty goals scored minus the\n number of non-penalty goals the player was expected to score.\n \"\"\"\n return self._non_penalty_minus_expected_non_penalty\n\n @float_property_decorator\n def assists_minus_expected(self):\n \"\"\"\n Returns a ``float`` of the number of assists the player registered\n minus the actual number of assists the player tallied.\n \"\"\"\n return self._assists_minus_expected\n\n @int_property_decorator\n def key_passes(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made that\n directly lead to a shot.\n \"\"\"\n return self._key_passes\n\n @int_property_decorator\n def passes_completed(self):\n \"\"\"\n Returns an ``int`` of the total number of passes the player has\n completed.\n \"\"\"\n return self._passes_completed\n\n @int_property_decorator\n def passes_attempted(self):\n \"\"\"\n Returns an ``int`` of the total number of passes the player has\n attempted.\n \"\"\"\n return self._passes_attempted\n\n @float_property_decorator\n def pass_completion(self):\n \"\"\"\n Returns a ``float`` of the player's overall pass completion rating.\n Percentage ranges from 0-100.\n \"\"\"\n return self._pass_completion\n\n @int_property_decorator\n def short_passes_completed(self):\n \"\"\"\n Returns an ``int`` of the total number of passes under 5 yards the\n player has completed.\n \"\"\"\n return self._short_passes_completed\n\n @int_property_decorator\n def short_passes_attempted(self):\n \"\"\"\n Returns an ``int`` of the total number of passes under 5 yards the\n player has attempted.\n \"\"\"\n return self._short_passes_attempted\n\n @float_property_decorator\n def short_pass_completion(self):\n \"\"\"\n Returns a ``float`` of the player's overall pass completion rating for\n passes under 5 yards. Percentage ranges from 0-100.\n \"\"\"\n return self._short_pass_completion\n\n @int_property_decorator\n def medium_passes_completed(self):\n \"\"\"\n Returns an ``int`` of the total number of passes between 5 and 25 yards\n the player has completed.\n \"\"\"\n return self._medium_passes_completed\n\n @int_property_decorator\n def medium_passes_attempted(self):\n \"\"\"\n Returns an ``int`` of the total number of passes between 5 and 25 yards\n the player has attempted.\n \"\"\"\n return self._medium_passes_attempted\n\n @float_property_decorator\n def medium_pass_completion(self):\n \"\"\"\n Returns a ``float`` of the player's overall pass completion rating for\n passes between 5 and 25 yards. Percentage ranges from 0-100.\n \"\"\"\n return self._medium_pass_completion\n\n @int_property_decorator\n def long_passes_completed(self):\n \"\"\"\n Returns an ``int`` of the total number of passes greater than 25 yards\n the player has completed.\n \"\"\"\n return self._long_passes_completed\n\n @int_property_decorator\n def long_passes_attempted(self):\n \"\"\"\n Returns an ``int`` of the total number of passes greater than 25 yards\n the player has attempted.\n \"\"\"\n return self._long_passes_attempted\n\n @float_property_decorator\n def long_pass_completion(self):\n \"\"\"\n Returns a ``float`` of the player's overall pass completion rating for\n passes greater than 25 yards. Percentage ranges from 0-100.\n \"\"\"\n return self._long_pass_completion\n\n @int_property_decorator\n def left_foot_passes(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made with their\n left foot.\n \"\"\"\n return self._left_foot_passes\n\n @int_property_decorator\n def right_foot_passes(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made with their\n right foot.\n \"\"\"\n return self._right_foot_passes\n\n @int_property_decorator\n def free_kick_passes(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made from a free\n kick.\n \"\"\"\n return self._free_kick_passes\n\n @int_property_decorator\n def through_balls(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made between the\n last line of defenders into open space.\n \"\"\"\n return self._through_balls\n\n @int_property_decorator\n def corner_kicks(self):\n \"\"\"\n Returns an ``int`` of the number of corner kicks the player has taken.\n \"\"\"\n return self._corner_kicks\n\n @int_property_decorator\n def throw_ins(self):\n \"\"\"\n Returns an ``int`` of the number of throw-ins the player took.\n \"\"\"\n return self._throw_ins\n\n @int_property_decorator\n def final_third_passes(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made into the\n final third.\n \"\"\"\n return self._final_third_passes\n\n @int_property_decorator\n def penalty_area_passes(self):\n \"\"\"\n Returns an ``int`` of the number of passes the player made into the\n opposing penalty area.\n \"\"\"\n return self._penalty_area_passes\n\n @int_property_decorator\n def penalty_area_crosses(self):\n \"\"\"\n Returns an ``int`` of the number of non-set piece crosses the player\n made into the penalty area.\n \"\"\"\n return self._penalty_area_crosses\n\n @int_property_decorator\n def minutes_per_match(self):\n \"\"\"\n Returns an ``int`` of the average number of minutes the player played\n per match.\n \"\"\"\n return self._minutes_per_match\n\n @float_property_decorator\n def minutes_played_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of time the player has been on\n the field for all games the team participated in. Percentage ranges\n from 0-100.\n \"\"\"\n return self._minutes_played_percentage\n\n @float_property_decorator\n def nineties_played(self):\n \"\"\"\n Returns a ``float`` of number of the number of minutes the player has\n played divided by 90.\n \"\"\"\n return self._nineties_played\n\n @int_property_decorator\n def minutes_per_start(self):\n \"\"\"\n Returns an ``int`` of the number of minutes the player plays on average\n per game started.\n \"\"\"\n return self._minutes_per_start\n\n @int_property_decorator\n def subs(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has come on as a\n sub.\n \"\"\"\n return self._subs\n\n @int_property_decorator\n def minutes_per_sub(self):\n \"\"\"\n Returns an ``int`` of the average number of minutes the player has\n played per game after coming in as a sub.\n \"\"\"\n return self._minutes_per_sub\n\n @int_property_decorator\n def unused_sub(self):\n \"\"\"\n Returns an ``int`` of the number of times the player was an unused sub\n and spent the entirety of the game on the bench.\n \"\"\"\n return self._unused_sub\n\n @float_property_decorator\n def points_per_match(self):\n \"\"\"\n Returns a ``float`` of the average number of points the team has gained\n per game in which the player participated.\n \"\"\"\n return self._points_per_match\n\n @int_property_decorator\n def goals_scored_on_pitch(self):\n \"\"\"\n Returns an ``int`` of the number of goals the team has scored while the\n player was on the field.\n \"\"\"\n return self._goals_scored_on_pitch\n\n @int_property_decorator\n def goals_against_on_pitch(self):\n \"\"\"\n Returns an ``int`` of the number of goals the team has conceded while\n the player was on the field.\n \"\"\"\n return self._goals_against_on_pitch\n\n @int_property_decorator\n def goal_difference_on_pitch(self):\n \"\"\"\n Returns an ``int`` of the team's goal difference while the player is on\n the field.\n \"\"\"\n return self._goal_difference_on_pitch\n\n @float_property_decorator\n def goal_difference_on_pitch_per_90(self):\n \"\"\"\n Returns a ``float`` of the team's average goal difference while the\n player is on the field, per 90 minutes played.\n \"\"\"\n return self._goal_difference_on_pitch_per_90\n\n @float_property_decorator\n def net_difference_on_pitch_per_90(self):\n \"\"\"\n Returns a ``float`` of the team's goal difference while the player is\n on the pitch minus the team's goal difference while the player is off\n the pitch, per 90 minutes.\n \"\"\"\n return self._net_difference_on_pitch_per_90\n\n @float_property_decorator\n def expected_goals_on_pitch(self):\n \"\"\"\n Returns a ``float`` of the number of goals the team was expected to\n score while the player was on the pitch.\n \"\"\"\n return self._expected_goals_on_pitch\n\n @float_property_decorator\n def expected_goals_against_on_pitch(self):\n \"\"\"\n Returns a ``float`` of the number of goals the team was expected to\n concede while the player was on the pitch.\n \"\"\"\n return self._expected_goals_against_on_pitch\n\n @float_property_decorator\n def expected_goal_difference(self):\n \"\"\"\n Returns a ``float`` of the difference between expected team goals\n scored and conceded while the player was on the pitch.\n \"\"\"\n return self._expected_goal_difference\n\n @float_property_decorator\n def expected_goal_difference_per_90(self):\n \"\"\"\n Returns a ``float`` of the difference between expected team goals\n scored and conceded while the player was on the pitch, per 90 minutes.\n \"\"\"\n return self._expected_goal_difference_per_90\n\n @float_property_decorator\n def net_expected_goal_difference_per_90(self):\n \"\"\"\n Returns a ``float`` of the team's expected goal difference while the\n player is on the pitch minus the team's exepcted goal difference while\n the player is off the pitch, per 90 minutes.\n \"\"\"\n return self._net_expected_goal_difference_per_90\n\n @int_property_decorator\n def soft_reds(self):\n \"\"\"\n Returns an ``int`` of the number of games where the player received two\n yellow cards, resulting in a red, or a \"soft red\".\n \"\"\"\n return self._soft_reds\n\n @int_property_decorator\n def fouls_committed(self):\n \"\"\"\n Returns an ``int`` of the number of fouls the player has committed.\n \"\"\"\n return self._fouls_committed\n\n @int_property_decorator\n def fouls_drawn(self):\n \"\"\"\n Returns an ``int`` of the number of fouls the player has been the\n victim of.\n \"\"\"\n return self._fouls_drawn\n\n @int_property_decorator\n def offsides(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has been called\n offside.\n \"\"\"\n return self._offsides\n\n @int_property_decorator\n def crosses(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has crossed the\n ball.\n \"\"\"\n return self._crosses\n\n @int_property_decorator\n def tackles_won(self):\n \"\"\"\n Returns an ``int`` of the number of tackles the player has won.\n \"\"\"\n return self._tackles_won\n\n @int_property_decorator\n def interceptions(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has intercepted\n the ball.\n \"\"\"\n return self._interceptions\n\n @int_property_decorator\n def penalty_kicks_won(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has won a penalty\n kick for the team.\n \"\"\"\n return self._penalty_kicks_won\n\n @int_property_decorator\n def penalty_kicks_conceded(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has conceded a\n penalty kick to the opposition.\n \"\"\"\n return self._penalty_kicks_conceded\n\n @int_property_decorator\n def successful_dribbles(self):\n \"\"\"\n Returns an ``int`` of the number of dribbles the player has completed\n successfully.\n \"\"\"\n return self._successful_dribbles\n\n @int_property_decorator\n def attempted_dribbles(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has attempted a\n dribble.\n \"\"\"\n return self._attempted_dribbles\n\n @float_property_decorator\n def dribble_success_rate(self):\n \"\"\"\n Returns a ``float`` of the percentage of attempted dribbles the player\n has successfully completed. Percentage ranges from 0-100.\n \"\"\"\n return self._dribble_success_rate\n\n @int_property_decorator\n def players_dribbled_past(self):\n \"\"\"\n Returns an ``int`` of the number of opponents the player dribbled past.\n \"\"\"\n return self._players_dribbled_past\n\n @int_property_decorator\n def nutmegs(self):\n \"\"\"\n Returns an ``int`` of the number of opponents the player has nutmegged.\n \"\"\"\n return self._nutmegs\n\n @int_property_decorator\n def dribblers_tackled(self):\n \"\"\"\n Returns an ``int`` of the number of opponents who were attempting a\n dribble that the player tackled.\n \"\"\"\n return self._dribblers_tackled\n\n @int_property_decorator\n def dribblers_contested(self):\n \"\"\"\n Returns an ``int`` of the number of opponents who were attempting a\n dribble that the player contested.\n \"\"\"\n return self._dribblers_contested\n\n @float_property_decorator\n def tackle_percentage(self):\n \"\"\"\n Returns a ``float`` of the percentage of opposing dribblers the player\n has successfully tackled. Percentage ranges from 0-100.\n \"\"\"\n return self._tackle_percentage\n\n @int_property_decorator\n def times_dribbled_past(self):\n \"\"\"\n Returns an ``int`` of the number of times the player has been dribbled\n past.\n \"\"\"\n return self._times_dribbled_past\n\n\nclass Roster:\n \"\"\"\n Get stats for all players on a roster.\n\n Request a team's roster for a given season and create instances of the\n Player class for each player, containing a detailed list of the player's\n statistics and information for the season.\n\n Parameters\n ----------\n squad_id : string\n The team's 8-digit squad ID or the team's name, such as '361ca564' or\n 'Tottenham Hotspur'.\n doc : PyQuery object (optional)\n If passed to the class instantiation, this will be used to pull all\n information instead of making another request to the website. If the\n document is not provided, it will be pulled during a later step.\n \"\"\"\n def __init__(self, squad_id, doc=None):\n self._players = []\n\n self._squad_id = _lookup_team(squad_id)\n player_data_dict = self._pull_stats(doc)\n if not player_data_dict:\n return None\n self._instantiate_players(player_data_dict)\n\n def __call__(self, player):\n \"\"\"\n Return a specified player on the roster.\n\n Returns a specific player as requested by the passed name or player ID.\n The input string must either match a player's 8-digit unique ID or the\n named listed on fbref.com for the player.\n\n Parameters\n ----------\n player : string\n A ``string`` of either the player's 8-digit unique ID or the name\n listed on fbref.com for the player.\n\n Returns\n -------\n Player instance\n If the requested player can be found, their Player instance is\n returned.\n\n Raises\n ------\n ValueError\n If the requested player cannot be matched with a player in the\n squad.\n \"\"\"\n for player_instance in self._players:\n if not player_instance.name or not player_instance.player_id:\n continue # pragma: no cover\n if player.lower() == player_instance.player_id.lower():\n return player_instance\n if player.lower().strip() == player_instance.name.lower().strip():\n return player_instance\n raise ValueError('No player found with the requested name or ID')\n\n def __repr__(self):\n \"\"\"\n Returns a ``list`` of all players for the given team.\n \"\"\"\n return self._players\n\n def __iter__(self):\n \"\"\"\n Returns an iterator of all of the players on the given team's roster.\n \"\"\"\n return iter(self.__repr__())\n\n def __len__(self):\n \"\"\"\n Returns the number of player on the given team's roster.\n \"\"\"\n return len(self.__repr__())\n\n def _player_id(self, player_data):\n \"\"\"\n Parse the player's ID from a row.\n\n The player ID is embedded within the header column of each individual\n player's row within a stats table. The specific ID is in a URL and can\n be easily parsed and returned.\n\n Parameters\n ----------\n player_data : PyQuery object\n A PyQuery object representing a single row in a stats table for a\n player.\n\n Returns\n -------\n string\n Returns a ``string`` of the player's unique 8-digit player ID.\n \"\"\"\n player = player_data('th[data-stat=\"player\"]')\n player_id = player('a').attr('href')\n try:\n player_id = re.sub(r'.*\\/players\\/', '', player_id)\n player_id = re.sub(r'\\/.*', '', player_id)\n except TypeError:\n player_id = None\n return player_id\n\n def _add_stats_data(self, stats_table, player_data_dict):\n \"\"\"\n Add each player's stats rows to a dictionary.\n\n Given the player stats are spread throughout many tables, they should\n be combined by player for a single reference for each player for easier\n lookups.\n\n Parameters\n ----------\n stats_table : generator\n A generator of all row items in a given table.\n player_data_dict : {str: {'data': str}} dictionary\n A dictionary where every key is the player's ID and every value is\n another dictionary with a 'data' key which contains the string\n version of the row data for the matched player.\n\n Returns\n -------\n dictionary\n An updated version of the player_data_dict with the passed table\n row information included.\n \"\"\"\n for player_data in stats_table:\n if 'class=\"thead\"' in str(player_data):\n continue # pragma: no cover\n player_id = self._player_id(player_data)\n if not player_id:\n continue\n try:\n player_data_dict[player_id]['data'] += player_data\n except KeyError:\n player_data_dict[player_id] = {'data': player_data}\n return player_data_dict\n\n def _pull_stats(self, doc):\n \"\"\"\n Download the team page and pull all stats.\n\n Download the requested team's season page and pull all of the relevant\n stats tables for later parsing.\n\n Parameters\n ----------\n doc : PyQuery object\n If passed to the class instantiation, this will be used to pull all\n information instead of making another request to the website. If\n the document is not provided, this value will be None.\n\n Returns\n -------\n dictionary\n Returns a ``dictionary`` where every key is the player's ID and\n every value is another dictionary with a 'data' key which contains\n the string version of the row data for the matched player.\n \"\"\"\n if not doc:\n doc = pq(SQUAD_URL % self._squad_id)\n doc = pq(_remove_html_comment_tags(doc))\n stats_table = []\n player_data_dict = {}\n\n # Most leagues use the 'stats_*_ks_combined' tag for competitions, but\n # some, like the MLS in North America, use a different table ID.\n for table_id in ['table#stats_standard_ks_combined',\n 'table#stats_keeper_ks_combined',\n 'table#stats_keeper_adv_ks_combined',\n 'table#stats_shooting_ks_combined',\n 'table#stats_passing_ks_combined',\n 'table#stats_playing_time_ks_combined',\n 'table#stats_misc_ks_combined',\n 'table#stats_standard_10090',\n 'table#stats_keeper_10090',\n 'table#stats_keeper_adv_10090',\n 'table#stats_shooting_10090',\n 'table#stats_passing_10090',\n 'table#stats_playing_time_10090',\n 'table#stats_misc_10090']:\n table = _get_stats_table(doc, table_id)\n if not table:\n continue\n player_data_dict = self._add_stats_data(table, player_data_dict)\n return player_data_dict\n\n def _instantiate_players(self, player_data_dict):\n \"\"\"\n Create Player instances for each squad member.\n\n Given the stats information for all players, an instance of the Player\n class should be created and appended to the overall list of players for\n easy future reference.\n\n Parameters\n ----------\n player_data_dict : {str: {'data': str}} dictionary\n A dictionary where every key is the player's ID and every value is\n another dictionary with a 'data' key which contains the string\n version of the row data for the matched player.\n \"\"\"\n for player_id, player_data in player_data_dict.items():\n player = SquadPlayer(player_data['data'], player_id)\n self._players.append(player)\n"
]
[
"import argparse\nfrom pathlib import Path\nimport sys\n\nimport onnx\nimport torch\nimport torch.onnx\n\n\ndef positive_int_arg(values):\n \"\"\"Check positive integer type for input argument\"\"\"\n result = []\n for value in values.split(','):\n try:\n ivalue = int(value)\n if ivalue < 0:\n raise argparse.ArgumentTypeError('Argument must be a positive integer')\n result.append(ivalue)\n except Exception as exc:\n print(exc)\n sys.exit('Invalid value for input argument: {!r}, a positive integer is expected'.format(value))\n return result\n\n\ndef model_parameter(parameter):\n param, value = parameter.split('=', 1)\n try:\n value = eval(value, {}, {})\n except NameError as err:\n print('Cannot evaluate {!r} value in {}. For string values use \"{}=\\'{}\\'\" (with all quotes).'\n .format(value, parameter, param, value))\n sys.exit(err)\n return param, value\n\n\ndef parse_args():\n \"\"\"Parse input arguments\"\"\"\n\n parser = argparse.ArgumentParser(description='Conversion of pretrained models from PyTorch to ONNX')\n\n parser.add_argument('--model-name', type=str, required=True,\n help='Model to convert. May be class name or name of constructor function')\n parser.add_argument('--weights', type=str, required=True,\n help='Path to the weights in PyTorch\\'s format')\n parser.add_argument('--input-shape', metavar='INPUT_DIM', type=positive_int_arg, required=True,\n help='Shape of the input blob')\n parser.add_argument('--output-file', type=Path, required=True,\n help='Path to the output ONNX model')\n parser.add_argument('--from-torchvision', action='store_true',\n help='Sets model\\'s origin as Torchvision*')\n parser.add_argument('--model-path', type=str,\n help='Path to PyTorch model\\'s source code if model is not from Torchvision*')\n parser.add_argument('--import-module', type=str, default='',\n help='Name of module, which contains model\\'s constructor.'\n 'Requires if model not from Torchvision')\n parser.add_argument('--input-names', type=str, metavar='L[,L...]',\n help='Space separated names of the input layers')\n parser.add_argument('--output-names', type=str, metavar='L[,L...]',\n help='Space separated names of the output layers')\n parser.add_argument('--model-param', type=model_parameter, default=[], action='append',\n help='Pair \"name\"=\"value\" of model constructor parameter')\n return parser.parse_args()\n\n\ndef load_model(model_name, weights, from_torchvision, model_path, module_name, model_params):\n \"\"\"Import model and load pretrained weights\"\"\"\n\n if from_torchvision:\n try:\n import torchvision.models\n creator = getattr(torchvision.models, model_name)\n model = creator()\n except ImportError as err:\n print(err)\n sys.exit('The torchvision package was not found.'\n 'Please install it to default location or '\n 'update PYTHONPATH environment variable '\n 'with the path to the installed torchvision package.')\n except AttributeError as err:\n print('ERROR: Model {} doesn\\'t exist in torchvision!'.format(model_name))\n sys.exit(err)\n else:\n sys.path.append(model_path)\n try:\n module = __import__(module_name)\n creator = getattr(module, model_name)\n model = creator(**model_params)\n except ImportError as err:\n print('Module {} in {} doesn\\'t exist. Check import path and name'.format(model_name, model_path))\n sys.exit(err)\n except AttributeError as err:\n print('ERROR: Module {} contains no class or function with name {}!'\n .format(module_name, model_name))\n sys.exit(err)\n\n try:\n model.load_state_dict(torch.load(weights, map_location='cpu'))\n except RuntimeError as err:\n print('ERROR: Weights from \\n{}\\n cannot be loaded for model {}! Check matching between model and weights')\n sys.exit(err)\n return model\n\n\ndef convert_to_onnx(model, input_shape, output_file, input_names, output_names):\n \"\"\"Convert PyTorch model to ONNX and check the resulting onnx model\"\"\"\n\n output_file.parent.mkdir(parents=True, exist_ok=True)\n model.eval()\n dummy_input = torch.randn(input_shape)\n model(dummy_input)\n torch.onnx.export(model, dummy_input, str(output_file), verbose=False,\n input_names=input_names.split(','), output_names=output_names.split(','))\n\n # Model check after conversion\n model = onnx.load(str(output_file))\n try:\n onnx.checker.check_model(model)\n print('ONNX check passed successfully.')\n except onnx.onnx_cpp2py_export.checker.ValidationError as exc:\n sys.exit('ONNX check failed with error: ' + str(exc))\n\n\ndef main():\n args = parse_args()\n model = load_model(args.model_name, args.weights, args.from_torchvision,\n args.model_path, args.import_module, dict(args.model_param))\n\n convert_to_onnx(model, args.input_shape, args.output_file, args.input_names, args.output_names)\n\n\nif __name__ == '__main__':\n main()\n"
]
[
"from numpy import *\nimport pandas as pd\nimport random\nimport nlopt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numbers\nimport math\nimport random\nimport autograd.numpy as ag\nfrom autograd import grad\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom numpy.lib.function_base import vectorize\nfrom autograd import value_and_grad\nnp.set_printoptions(precision=20)\npd.set_option(\"display.precision\", 14)\n\n\n##### the functions in this file are used to generated random starting points for test functions and our economic application\n\n\ndef get_starting_points(n,problem_info_object,p):\n \n \n ### n: number of desired dimensions of the problem\n ### problem_info_object: object that contains the known information of the problem e.g.: g_1=griewank_info(n,a=200)\n ### p: desired number of starting points you want to draw\n \n ## as Guvenen et al. do not specify how they generate the random starting points I will choose a method\n ### Method:\n # as the starting point has to be a vector fo dimension = dimension of the function, I draw every coordinate\n # for the vector from a uniform distribution\n # repeat this until you get 100 vectors of dimension = dim of function which are randomly generated\n data=[]\n \n lower_b=problem_info_object.lower_bound\n upper_b=problem_info_object.upper_bound\n \n for i in range(n):\n v=np.random.uniform(lower_b[i],upper_b[i],p)\n data.append(v)\n df=pd.DataFrame(data)\n return df.transpose()\n\n\n\ndef get_start_points_application(alpha_dirichlet,p,B):\n \n ## alpha dirichlet is a vector that contains alphas for dirichlet distribution\n ## this also stores the dimension of the problem\n ## p is the number of start points we want to generate\n ## B is the budget we consider\n ## function works\n data=[]\n \n for i in range(p):\n \n vector_dirichlet=np.random.dirichlet(alpha_dirichlet,1)\n vector_budget_adjusted=vector_dirichlet*B\n data.append(vector_budget_adjusted)\n \n df=pd.DataFrame(np.concatenate(data))\n return df\n \n \n \n \n\n\n\n\n\n\n"
]
[
"# Lint as: python3\n# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Prepare TF.Examples for on-device recommendation model.\n\nFollowing functions are included: 1) downloading raw data 2) processing to user\nactivity sequence and splitting to train/test data 3) convert to TF.Examples\nand write in output location.\n\nMore information about the movielens dataset can be found here:\nhttps://grouplens.org/datasets/movielens/\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport os\n\nfrom absl import app\nfrom absl import flags\nimport pandas as pd\nimport tensorflow as tf\n\nFLAGS = flags.FLAGS\n# Permalinks to download movielens data.\nMOVIELENS_1M_URL = \"http://files.grouplens.org/datasets/movielens/ml-1m.zip\"\nMOVIELENS_ZIP_FILENAME = \"ml-1m.zip\"\nMOVIELENS_ZIP_HASH = \"a6898adb50b9ca05aa231689da44c217cb524e7ebd39d264c56e2832f2c54e20\"\nMOVIELENS_EXTRACTED_DIR = \"ml-1m\"\nRATINGS_FILE_NAME = \"ratings.dat\"\nMOVIES_FILE_NAME = \"movies.dat\"\nRATINGS_DATA_COLUMNS = [\"UserID\", \"MovieID\", \"Rating\", \"Timestamp\"]\nMOVIES_DATA_COLUMNS = [\"MovieID\", \"Title\", \"Genres\"]\nOUTPUT_TRAINING_DATA_FILENAME = \"train_movielens_1m.tfrecord\"\nOUTPUT_TESTING_DATA_FILENAME = \"test_movielens_1m.tfrecord\"\nOUTPUT_MOVIE_VOCAB_FILENAME = \"movie_vocab.json\"\nOOV_MOVIE_ID = 0\n\n\ndef define_flags():\n flags.DEFINE_string(\"data_dir\", \"/tmp\",\n \"Path to download and store movielens data.\")\n flags.DEFINE_string(\"output_dir\", None,\n \"Path to the directory of output files.\")\n flags.DEFINE_bool(\"build_movie_vocab\", True,\n \"If yes, generate sorted movie vocab.\")\n flags.DEFINE_integer(\"min_timeline_length\", 3,\n \"The minimum timeline length to construct examples.\")\n flags.DEFINE_integer(\"max_context_length\", 10,\n \"The maximun length of user context history.\")\n\n\ndef download_and_extract_data(data_directory, url=MOVIELENS_1M_URL):\n \"\"\"Download and extract zip containing MovieLens data to a given directory.\n\n Args:\n data_directory: Local path to extract dataset to.\n url: Direct path to MovieLens dataset .zip file. See constants above for\n examples.\n\n Returns:\n Downloaded and extracted data file directory.\n \"\"\"\n path_to_zip = tf.keras.utils.get_file(\n fname=MOVIELENS_ZIP_FILENAME,\n origin=url,\n file_hash=MOVIELENS_ZIP_HASH,\n hash_algorithm=\"sha256\",\n extract=True,\n cache_dir=data_directory)\n extracted_file_dir = os.path.join(\n os.path.dirname(path_to_zip), MOVIELENS_EXTRACTED_DIR)\n return extracted_file_dir\n\n\ndef read_data(data_directory):\n \"\"\"Read movielens ratings.dat and movies.dat file into dataframe.\"\"\"\n ratings_df = pd.read_csv(\n os.path.join(data_directory, RATINGS_FILE_NAME),\n sep=\"::\",\n names=RATINGS_DATA_COLUMNS)\n ratings_df[\"Timestamp\"] = ratings_df[\"Timestamp\"].apply(int)\n movies_df = pd.read_csv(\n os.path.join(data_directory, MOVIES_FILE_NAME),\n sep=\"::\",\n names=MOVIES_DATA_COLUMNS)\n return ratings_df, movies_df\n\n\ndef convert_to_timelines(ratings_df):\n \"\"\"Convert ratings data to user.\"\"\"\n timelines = collections.defaultdict(list)\n movie_counts = collections.Counter()\n for user_id, movie_id, _, timestamp in ratings_df.values:\n timelines[user_id].append([movie_id, int(timestamp)])\n movie_counts[movie_id] += 1\n # Sort per-user timeline by timestamp\n for (user_id, timeline) in timelines.items():\n timeline.sort(key=lambda x: x[1])\n timelines[user_id] = [movie_id for movie_id, _ in timeline]\n return timelines, movie_counts\n\n\ndef generate_examples_from_timelines(timelines,\n min_timeline_len=3,\n max_context_len=100):\n \"\"\"Convert user timelines to tf examples.\n\n Convert user timelines to tf examples by adding all possible context-label\n pairs in the examples pool.\n\n Args:\n timelines: the user timelines to process.\n min_timeline_len: minimum length of the user timeline.\n max_context_len: maximum length of context signals.\n\n Returns:\n train_examples: tf example list for training.\n test_examples: tf example list for testing.\n \"\"\"\n train_examples = []\n test_examples = []\n for timeline in timelines.values():\n # Skip if timeline is shorter than min_timeline_len.\n if len(timeline) < min_timeline_len:\n continue\n for label_idx in range(1, len(timeline)):\n start_idx = max(0, label_idx - max_context_len)\n context = timeline[start_idx:label_idx]\n # Pad context with out-of-vocab movie id 0.\n while len(context) < max_context_len:\n context.append(OOV_MOVIE_ID)\n label = timeline[label_idx]\n feature = {\n \"context\":\n tf.train.Feature(int64_list=tf.train.Int64List(value=context)),\n \"label\":\n tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))\n }\n tf_example = tf.train.Example(features=tf.train.Features(feature=feature))\n if label_idx == len(timeline) - 1:\n test_examples.append(tf_example.SerializeToString())\n else:\n train_examples.append(tf_example.SerializeToString())\n return train_examples, test_examples\n\n\ndef write_tfrecords(tf_examples, filename):\n \"\"\"Writes tf examples to tfrecord file, and returns the count.\"\"\"\n with tf.io.TFRecordWriter(filename) as file_writer:\n i = 0\n for example in tf_examples:\n file_writer.write(example)\n i += 1\n return i\n\n\ndef generate_sorted_movie_vocab(movies_df, movie_counts):\n \"\"\"Generate vocabulary for movies, and sort by usage count.\"\"\"\n vocab_movies = []\n for movie_id, title, genres in movies_df.values:\n count = movie_counts[movie_id] if movie_id in movie_counts else 0\n vocab_movies.append([movie_id, title, genres, count])\n vocab_movies.sort(key=lambda x: x[3], reverse=True)\n return vocab_movies\n\n\ndef write_vocab_json(vocab_movies, filename):\n \"\"\"Write generated movie vocabulary to specified file.\"\"\"\n with open(filename, \"w\", encoding=\"utf-8\") as jsonfile:\n json.dump(vocab_movies, jsonfile, indent=2)\n\n\ndef generate_datasets(data_dir, output_dir, min_timeline_length,\n max_context_length, build_movie_vocab):\n \"\"\"Generates train and test datasets as TFRecord, and returns stats.\"\"\"\n if not tf.io.gfile.exists(data_dir):\n tf.io.gfile.makedirs(data_dir)\n\n extracted_file_dir = download_and_extract_data(data_directory=data_dir)\n ratings_df, movies_df = read_data(data_directory=extracted_file_dir)\n timelines, movie_counts = convert_to_timelines(ratings_df)\n train_examples, test_examples = generate_examples_from_timelines(\n timelines=timelines,\n min_timeline_len=min_timeline_length,\n max_context_len=max_context_length)\n\n if not tf.io.gfile.exists(output_dir):\n tf.io.gfile.makedirs(output_dir)\n train_file = os.path.join(output_dir, OUTPUT_TRAINING_DATA_FILENAME)\n train_size = write_tfrecords(tf_examples=train_examples, filename=train_file)\n test_file = os.path.join(output_dir, OUTPUT_TESTING_DATA_FILENAME)\n test_size = write_tfrecords(tf_examples=test_examples, filename=test_file)\n stats = {\n \"train_size\": train_size,\n \"test_size\": test_size,\n \"train_file\": train_file,\n \"test_file\": test_file,\n }\n if build_movie_vocab:\n vocab_movies = generate_sorted_movie_vocab(\n movies_df=movies_df, movie_counts=movie_counts)\n vocab_file = os.path.join(output_dir, OUTPUT_MOVIE_VOCAB_FILENAME)\n write_vocab_json(vocab_movies=vocab_movies, filename=vocab_file)\n stats.update(vocab_size=len(vocab_movies), vocab_file=vocab_file)\n return stats\n\n\ndef main(_):\n stats = generate_datasets(FLAGS.data_dir, FLAGS.output_dir,\n FLAGS.min_timeline_length, FLAGS.max_context_length,\n FLAGS.build_movie_vocab)\n tf.compat.v1.logging.info(\"Generated dataset: %s\", stats)\n\n\nif __name__ == \"__main__\":\n define_flags()\n app.run(main)\n"
]
[
"import numpy as np\nfrom sklearn.neighbors import KDTree\nimport scipy.linalg\n\ntry:\n import pynndescent\n index = pynndescent.NNDescent(np.random.random((100, 3)), n_jobs=2)\n del index\n ANN = True\nexcept ImportError:\n ANN = False\n\n\ndef p2p_to_FM(p2p, eigvects1, eigvects2, A2=None):\n \"\"\"\n Compute a Functional Map from a vertex to vertex maps (with possible subsampling).\n Can compute with the pseudo inverse of eigenvectors (if no subsampling) or least square.\n\n Parameters\n ------------------------------\n p2p : (n2,) vertex to vertex map from target to source (for the functional map).\n For each vertex on the target shape, gives the index of the corresponding vertex on mesh 1.\n eigvects1 : (n1,k1) eigenvectors on source mesh. Possibly subsampled on the first dimension.\n eigvects2 : (n2,k2) eigenvectors on target mesh. Possibly subsampled on the first dimension.\n A2 : (n2,n2) area matrix of the target mesh. If specified, the eigenvectors can't be subsampled\n\n Outputs\n -------------------------------\n FM : (k2,k1) functional map corresponding to the p2p map given.\n Solved with pseudo inverse if A2 is given, else using least square.\n \"\"\"\n if A2 is not None:\n if A2.shape[0] != eigvects2.shape[0]:\n raise ValueError(\"Can't compute pseudo inverse with subsampled eigenvectors\")\n return eigvects2.T @ A2 @ eigvects1[p2p, :] # (k2,k1)\n\n # Solve with least square\n return scipy.linalg.lstsq(eigvects2, eigvects1[p2p, :])[0] # (k2,k1)\n\n\ndef mesh_p2p_to_FM(p2p, mesh1, mesh2, dims=None, subsample=None):\n \"\"\"\n Compute a Functional Map from a vertex to vertex maps (with possible subsampling).\n\n Parameters\n ------------------------------\n p2p : (n2,) or (n2',) vertex to vertex map from mesh2 to mesh1.\n For each vertex on mesh2 gives the index of the corresponding vertex on mesh 1.\n If subsample is specified, gives a index-to-index map between the subsamples.\n mesh1 : source mesh for the functional map. Requires enough processed eigenvectors.\n mesh2 : target mesh for the functional map. Requires enough processed eigenvectors.\n dims : int, or 2-uple of int. Dimension of the functional map to return.\n If None uses all the processed eigenvectors.\n If single int k , returns a (k,k) functional map\n If 2-uple of int (k1,k2), returns a (k2,k1) functional map\n subsample : None or size 2 iterable ((n1',), (n2',)).\n Subsample of vertices for both mesh.\n If specified the p2p map is between the two subsamples.\n \"\"\"\n if dims is None:\n k1,k2 = len(mesh1.eigenvalues),len(mesh2.eigenvalues)\n elif type(dims) is int:\n k1 = dims\n k2 = dims\n else:\n k1,k2 = dims\n\n if subsample is None:\n return p2p_to_FM(p2p, mesh1.eigenvectors[:, :k1], mesh2.eigenvectors[:, :k2], A2=mesh2.A)\n\n sub1,sub2 = subsample\n return p2p_to_FM(p2p, mesh1.eigenvectors[sub1, :k1], mesh2.eigenvectors[sub2, :k2])\n\n\ndef FM_to_p2p(FM, eigvects1, eigvects2, use_ANN=False):\n \"\"\"\n Obtain a point to point map from a functional map using the adjoint.\n For each row in Phi2, looks for the nearest row in Phi1 @ C.T\n\n Parameters\n --------------------------\n FM : (k2,k1) functional map in reduced basis\n eigvects1 : (n1,k1') first k' eigenvectors of the first basis (k1'>k1).\n First dimension can be subsampled.\n eigvects2 : (n2,k2') first k' eigenvectors of the second basis (k2'>k2)\n First dimension can be subsampled.\n use_ANN : Whether to use approximate nearest neighbors\n\n Outputs:\n --------------------------\n p2p : (n2,) match vertex i on shape 2 to vertex p2p[i] on shape 1,\n or equivalent result if the eigenvectors are subsampled.\n \"\"\"\n if use_ANN and not ANN:\n raise ValueError('Please install pydescent to achieve Approximate Nearest Neighbor')\n\n k2,k1 = FM.shape\n\n assert k1 <= eigvects1.shape[1], \\\n f'At least {k1} should be provided, here only {eigvects1.shape[1]} are given'\n assert k2 <= eigvects2.shape[1], \\\n f'At least {k2} should be provided, here only {eigvects2.shape[1]} are given'\n\n if use_ANN:\n index = pynndescent.NNDescent(eigvects1[:, :k1] @ FM.T, n_jobs=8)\n matches,_ = index.query(eigvects2[:, :k2],k=1) # (n2,1)\n matches = matches.flatten() # (n2,)\n else:\n tree = KDTree(eigvects1[:, :k1] @ FM.T) # Tree on (n1,k2)\n matches = tree.query(eigvects2[:, :k2], k=1, return_distance=False).flatten() # (n2,)\n\n return matches # (n2,)\n\n\ndef FM_to_p2p_aux(FM, eigvects1, eigvects2, use_ANN=False):\n \"\"\"\n Obtain a point to point map from a functional map with another method.\n For each row in Phi2 @ C, looks for the nearest row in Phi1\n\n Parameters\n --------------------------\n FM : (k2,k1) functional map in reduced basis\n eigvects1 : (n1,k1') first k' eigenvectors of the first basis (k1'>k1).\n First dimension can be subsampled.\n eigvects2 : (n2,k2') first k' eigenvectors of the second basis (k2'>k2)\n First dimension can be subsampled.\n use_ANN : Whether to use approximate nearest neighbors\n\n Outputs:\n --------------------------\n p2p : (n2,) match vertex i on shape 2 to vertex p2p[i] on shape 1,\n or equivalent result if the eigenvectors are subsampled.\n \"\"\"\n if use_ANN and not ANN:\n raise ValueError('Please install pydescent to achieve Approximate Nearest Neighbor')\n\n k2,k1 = FM.shape\n\n assert k1 <= eigvects1.shape[1], \\\n f'At least {k1} should be provided, here only {eigvects1.shape[1]} are given'\n assert k2 <= eigvects2.shape[1], \\\n f'At least {k2} should be provided, here only {eigvects2.shape[1]} are given'\n\n if use_ANN:\n index = pynndescent.NNDescent(eigvects1[:, :k1], n_jobs=8)\n matches,_ = index.query(eigvects2[:, :k2] @ FM, k=1) # (n2,1)\n matches = matches.flatten() # (n2,)\n else:\n tree = KDTree(eigvects1[:, :k1]) # Tree on (n1,k1)\n matches = tree.query(eigvects2[:, :k2] @ FM, k=1, return_distance=False).flatten() # (n2,)\n\n return matches # (n2,)\n"
]
[
"import datajoint as dj\nimport pathlib\nimport re\nimport numpy as np\nimport inspect\nimport importlib\n\nfrom .readers import spikeglx, kilosort, openephys\nfrom . import probe, find_full_path, find_root_directory, dict_to_uuid\n\nschema = dj.schema()\n\n_linking_module = None\n\n\ndef activate(ephys_schema_name, probe_schema_name=None, *, create_schema=True,\n create_tables=True, linking_module=None):\n \"\"\"\n activate(ephys_schema_name, probe_schema_name=None, *, create_schema=True, create_tables=True, linking_module=None)\n :param ephys_schema_name: schema name on the database server to activate the `ephys` element\n :param probe_schema_name: schema name on the database server to activate the `probe` element\n - may be omitted if the `probe` element is already activated\n :param create_schema: when True (default), create schema in the database if it does not yet exist.\n :param create_tables: when True (default), create tables in the database if they do not yet exist.\n :param linking_module: a module name or a module containing the\n required dependencies to activate the `ephys` element:\n Upstream tables:\n + Session: parent table to ProbeInsertion, typically identifying a recording session\n + SkullReference: Reference table for InsertionLocation, specifying the skull reference\n used for probe insertion location (e.g. Bregma, Lambda)\n Functions:\n + get_ephys_root_data_dir() -> list\n Retrieve the root data directory - e.g. containing the raw ephys recording files for all subject/sessions.\n :return: a string for full path to the root data directory\n + get_session_directory(session_key: dict) -> str\n Retrieve the session directory containing the recorded Neuropixels data for a given Session\n :param session_key: a dictionary of one Session `key`\n :return: a string for full path to the session directory\n \"\"\"\n\n if isinstance(linking_module, str):\n linking_module = importlib.import_module(linking_module)\n assert inspect.ismodule(linking_module),\\\n \"The argument 'dependency' must be a module's name or a module\"\n\n global _linking_module\n _linking_module = linking_module\n\n # activate\n probe.activate(probe_schema_name, create_schema=create_schema,\n create_tables=create_tables)\n schema.activate(ephys_schema_name, create_schema=create_schema,\n create_tables=create_tables, add_objects=_linking_module.__dict__)\n\n\n# -------------- Functions required by the elements-ephys ---------------\n\ndef get_ephys_root_data_dir() -> list:\n \"\"\"\n All data paths, directories in DataJoint Elements are recommended to be stored as\n relative paths, with respect to some user-configured \"root\" directory,\n which varies from machine to machine (e.g. different mounted drive locations)\n\n get_ephys_root_data_dir() -> list\n This user-provided function retrieves the possible root data directories\n containing the ephys data for all subjects/sessions\n (e.g. acquired SpikeGLX or Open Ephys raw files,\n output files from spike sorting routines, etc.)\n :return: a string for full path to the ephys root data directory,\n or list of strings for possible root data directories\n \"\"\"\n return _linking_module.get_ephys_root_data_dir()\n\n\ndef get_session_directory(session_key: dict) -> str:\n \"\"\"\n get_session_directory(session_key: dict) -> str\n Retrieve the session directory containing the\n recorded Neuropixels data for a given Session\n :param session_key: a dictionary of one Session `key`\n :return: a string for full path to the session directory\n \"\"\"\n return _linking_module.get_session_directory(session_key)\n\n\n# ----------------------------- Table declarations ----------------------\n\n\n@schema\nclass AcquisitionSoftware(dj.Lookup):\n definition = \"\"\" # Name of software used for recording of neuropixels probes - SpikeGLX or Open Ephys\n acq_software: varchar(24) \n \"\"\"\n contents = zip(['SpikeGLX', 'Open Ephys'])\n\n\n@schema\nclass ProbeInsertion(dj.Manual):\n definition = \"\"\"\n # Probe insertion implanted into an animal for a given session.\n -> Session\n insertion_number: tinyint unsigned\n ---\n -> probe.Probe\n \"\"\"\n\n\n@schema\nclass InsertionLocation(dj.Manual):\n definition = \"\"\"\n # Brain Location of a given probe insertion.\n -> ProbeInsertion\n ---\n -> SkullReference\n ap_location: decimal(6, 2) # (um) anterior-posterior; ref is 0; more anterior is more positive\n ml_location: decimal(6, 2) # (um) medial axis; ref is 0 ; more right is more positive\n depth: decimal(6, 2) # (um) manipulator depth relative to surface of the brain (0); more ventral is more negative\n theta=null: decimal(5, 2) # (deg) - elevation - rotation about the ml-axis [0, 180] - w.r.t the z+ axis\n phi=null: decimal(5, 2) # (deg) - azimuth - rotation about the dv-axis [0, 360] - w.r.t the x+ axis\n beta=null: decimal(5, 2) # (deg) rotation about the shank of the probe [-180, 180] - clockwise is increasing in degree - 0 is the probe-front facing anterior\n \"\"\"\n\n\n@schema\nclass EphysRecording(dj.Imported):\n definition = \"\"\"\n # Ephys recording from a probe insertion for a given session.\n -> ProbeInsertion \n ---\n -> probe.ElectrodeConfig\n -> AcquisitionSoftware\n sampling_rate: float # (Hz) \n \"\"\"\n\n class EphysFile(dj.Part):\n definition = \"\"\"\n # Paths of files of a given EphysRecording round.\n -> master\n file_path: varchar(255) # filepath relative to root data directory\n \"\"\"\n\n def make(self, key):\n sess_dir = pathlib.Path(get_session_directory(key))\n sess_dir_full = find_full_path(get_ephys_root_data_dir(), sess_dir)\n\n inserted_probe_serial_number = (ProbeInsertion * probe.Probe & key).fetch1('probe')\n\n # search session dir and determine acquisition software\n for ephys_pattern, ephys_acq_type in zip(['*.ap.meta', '*.oebin'],\n ['SpikeGLX', 'Open Ephys']):\n ephys_meta_filepaths = [fp for fp in sess_dir_full.rglob(ephys_pattern)]\n if ephys_meta_filepaths:\n acq_software = ephys_acq_type\n break\n else:\n raise FileNotFoundError(\n f'Ephys recording data not found!'\n f' Neither SpikeGLX nor Open Ephys recording files found'\n f' in {sess_dir}')\n\n if acq_software == 'SpikeGLX':\n for meta_filepath in ephys_meta_filepaths:\n spikeglx_meta = spikeglx.SpikeGLXMeta(meta_filepath)\n if str(spikeglx_meta.probe_SN) == inserted_probe_serial_number:\n break\n else:\n raise FileNotFoundError(\n 'No SpikeGLX data found for probe insertion: {}'.format(key))\n\n if re.search('(1.0|2.0)', spikeglx_meta.probe_model):\n probe_type = spikeglx_meta.probe_model\n electrode_query = probe.ProbeType.Electrode & {'probe_type': probe_type}\n\n probe_electrodes = {\n (shank, shank_col, shank_row): key\n for key, shank, shank_col, shank_row in zip(*electrode_query.fetch(\n 'KEY', 'shank', 'shank_col', 'shank_row'))}\n\n electrode_group_members = [\n probe_electrodes[(shank, shank_col, shank_row)]\n for shank, shank_col, shank_row, _ in spikeglx_meta.shankmap['data']]\n else:\n raise NotImplementedError(\n 'Processing for neuropixels probe model'\n ' {} not yet implemented'.format(spikeglx_meta.probe_model))\n\n self.insert1({**key,\n **generate_electrode_config(probe_type, electrode_group_members),\n 'acq_software': acq_software,\n 'sampling_rate': spikeglx_meta.meta['imSampRate']})\n\n root_dir = find_root_directory(get_ephys_root_data_dir(), meta_filepath)\n self.EphysFile.insert1({\n **key,\n 'file_path': meta_filepath.relative_to(root_dir).as_posix()})\n elif acq_software == 'Open Ephys':\n dataset = openephys.OpenEphys(sess_dir_full)\n for serial_number, probe_data in dataset.probes.items():\n if str(serial_number) == inserted_probe_serial_number:\n break\n else:\n raise FileNotFoundError(\n 'No Open Ephys data found for probe insertion: {}'.format(key))\n\n if re.search('(1.0|2.0)', probe_data.probe_model):\n probe_type = probe_data.probe_model\n electrode_query = probe.ProbeType.Electrode & {'probe_type': probe_type}\n\n probe_electrodes = {key['electrode']: key\n for key in electrode_query.fetch('KEY')}\n\n electrode_group_members = [\n probe_electrodes[channel_idx]\n for channel_idx in probe_data.ap_meta['channels_ids']]\n else:\n raise NotImplementedError(\n 'Processing for neuropixels'\n ' probe model {} not yet implemented'.format(probe_data.probe_model))\n\n self.insert1({**key,\n **generate_electrode_config(probe_type, electrode_group_members),\n 'acq_software': acq_software,\n 'sampling_rate': probe_data.ap_meta['sample_rate']})\n\n root_dir = find_root_directory(\n get_ephys_root_data_dir(),\n probe_data.recording_info['recording_files'][0])\n self.EphysFile.insert([{**key,\n 'file_path': fp.relative_to(root_dir).as_posix()}\n for fp in probe_data.recording_info['recording_files']])\n else:\n raise NotImplementedError(f'Processing ephys files from'\n f' acquisition software of type {acq_software} is'\n f' not yet implemented')\n\n\n@schema\nclass LFP(dj.Imported):\n definition = \"\"\"\n # Acquired local field potential (LFP) from a given Ephys recording.\n -> EphysRecording\n ---\n lfp_sampling_rate: float # (Hz)\n lfp_time_stamps: longblob # (s) timestamps with respect to the start of the recording (recording_timestamp)\n lfp_mean: longblob # (uV) mean of LFP across electrodes - shape (time,)\n \"\"\"\n\n class Electrode(dj.Part):\n definition = \"\"\"\n -> master\n -> probe.ElectrodeConfig.Electrode \n ---\n lfp: longblob # (uV) recorded lfp at this electrode \n \"\"\"\n\n # Only store LFP for every 9th channel, due to high channel density,\n # close-by channels exhibit highly similar LFP\n _skip_channel_counts = 9\n\n def make(self, key):\n acq_software, probe_sn = (EphysRecording\n * ProbeInsertion & key).fetch1('acq_software', 'probe')\n\n electrode_keys, lfp = [], []\n\n if acq_software == 'SpikeGLX':\n spikeglx_meta_filepath = get_spikeglx_meta_filepath(key)\n spikeglx_recording = spikeglx.SpikeGLX(spikeglx_meta_filepath.parent)\n\n lfp_channel_ind = spikeglx_recording.lfmeta.recording_channels[\n -1::-self._skip_channel_counts]\n\n # Extract LFP data at specified channels and convert to uV\n lfp = spikeglx_recording.lf_timeseries[:, lfp_channel_ind] # (sample x channel)\n lfp = (lfp * spikeglx_recording.get_channel_bit_volts('lf')[lfp_channel_ind]).T # (channel x sample)\n\n self.insert1(dict(key,\n lfp_sampling_rate=spikeglx_recording.lfmeta.meta['imSampRate'],\n lfp_time_stamps=(np.arange(lfp.shape[1])\n / spikeglx_recording.lfmeta.meta['imSampRate']),\n lfp_mean=lfp.mean(axis=0)))\n\n electrode_query = (probe.ProbeType.Electrode\n * probe.ElectrodeConfig.Electrode\n * EphysRecording & key)\n probe_electrodes = {\n (shank, shank_col, shank_row): key\n for key, shank, shank_col, shank_row in zip(*electrode_query.fetch(\n 'KEY', 'shank', 'shank_col', 'shank_row'))}\n\n for recorded_site in lfp_channel_ind:\n shank, shank_col, shank_row, _ = spikeglx_recording.apmeta.shankmap['data'][recorded_site]\n electrode_keys.append(probe_electrodes[(shank, shank_col, shank_row)])\n elif acq_software == 'Open Ephys':\n sess_dir = pathlib.Path(get_session_directory(key))\n sess_dir_full = find_full_path(get_ephys_root_data_dir(), sess_dir)\n loaded_oe = openephys.OpenEphys(sess_dir_full)\n oe_probe = loaded_oe.probes[probe_sn]\n\n lfp_channel_ind = np.arange(\n len(oe_probe.lfp_meta['channels_ids']))[-1::-self._skip_channel_counts]\n\n lfp = oe_probe.lfp_timeseries[:, lfp_channel_ind] # (sample x channel)\n lfp = (lfp * np.array(oe_probe.lfp_meta['channels_gains'])[lfp_channel_ind]).T # (channel x sample)\n lfp_timestamps = oe_probe.lfp_timestamps\n\n self.insert1(dict(key,\n lfp_sampling_rate=oe_probe.lfp_meta['sample_rate'],\n lfp_time_stamps=lfp_timestamps,\n lfp_mean=lfp.mean(axis=0)))\n\n electrode_query = (probe.ProbeType.Electrode\n * probe.ElectrodeConfig.Electrode\n * EphysRecording & key)\n probe_electrodes = {key['electrode']: key\n for key in electrode_query.fetch('KEY')}\n\n for channel_idx in np.array(oe_probe.lfp_meta['channels_ids'])[lfp_channel_ind]:\n electrode_keys.append(probe_electrodes[channel_idx])\n else:\n raise NotImplementedError(f'LFP extraction from acquisition software'\n f' of type {acq_software} is not yet implemented')\n\n # single insert in loop to mitigate potential memory issue\n for electrode_key, lfp_trace in zip(electrode_keys, lfp):\n self.Electrode.insert1({**key, **electrode_key, 'lfp': lfp_trace})\n\n\n# ------------ Clustering --------------\n\n@schema\nclass ClusteringMethod(dj.Lookup):\n definition = \"\"\"\n # Method for clustering\n clustering_method: varchar(16)\n ---\n clustering_method_desc: varchar(1000)\n \"\"\"\n\n contents = [('kilosort', 'kilosort clustering method'),\n ('kilosort2', 'kilosort2 clustering method')]\n\n\n@schema\nclass ClusteringParamSet(dj.Lookup):\n definition = \"\"\"\n # Parameter set to be used in a clustering procedure\n paramset_idx: smallint\n ---\n -> ClusteringMethod \n paramset_desc: varchar(128)\n param_set_hash: uuid\n unique index (param_set_hash)\n params: longblob # dictionary of all applicable parameters\n \"\"\"\n\n @classmethod\n def insert_new_params(cls, processing_method: str, paramset_idx: int,\n paramset_desc: str, params: dict):\n param_dict = {'clustering_method': processing_method,\n 'paramset_idx': paramset_idx,\n 'paramset_desc': paramset_desc,\n 'params': params,\n 'param_set_hash': dict_to_uuid(params)}\n param_query = cls & {'param_set_hash': param_dict['param_set_hash']}\n\n if param_query: # If the specified param-set already exists\n existing_paramset_idx = param_query.fetch1('paramset_idx')\n if existing_paramset_idx == paramset_idx: # If the existing set has the same paramset_idx: job done\n return\n else: # If not same name: human error, trying to add the same paramset with different name\n raise dj.DataJointError(\n 'The specified param-set'\n ' already exists - paramset_idx: {}'.format(existing_paramset_idx))\n else:\n cls.insert1(param_dict)\n\n\n@schema\nclass ClusterQualityLabel(dj.Lookup):\n definition = \"\"\"\n # Quality\n cluster_quality_label: varchar(100)\n ---\n cluster_quality_description: varchar(4000)\n \"\"\"\n contents = [\n ('good', 'single unit'),\n ('ok', 'probably a single unit, but could be contaminated'),\n ('mua', 'multi-unit activity'),\n ('noise', 'bad unit')\n ]\n\n\n@schema\nclass ClusteringTask(dj.Manual):\n definition = \"\"\"\n # Manual table for defining a clustering task ready to be run\n -> EphysRecording\n -> ClusteringParamSet\n ---\n clustering_output_dir: varchar(255) # clustering output directory relative to the clustering root data directory\n task_mode='load': enum('load', 'trigger') # 'load': load computed analysis results, 'trigger': trigger computation\n \"\"\"\n\n\n@schema\nclass Clustering(dj.Imported):\n \"\"\"\n A processing table to handle each ClusteringTask:\n + If `task_mode == \"trigger\"`: trigger clustering analysis\n according to the ClusteringParamSet (e.g. launch a kilosort job)\n + If `task_mode == \"load\"`: verify output\n \"\"\"\n definition = \"\"\"\n # Clustering Procedure\n -> ClusteringTask\n ---\n clustering_time: datetime # time of generation of this set of clustering results \n package_version='': varchar(16)\n \"\"\"\n\n def make(self, key):\n task_mode, output_dir = (ClusteringTask & key).fetch1(\n 'task_mode', 'clustering_output_dir')\n kilosort_dir = find_full_path(get_ephys_root_data_dir(), output_dir)\n\n if task_mode == 'load':\n kilosort_dataset = kilosort.Kilosort(kilosort_dir) # check if the directory is a valid Kilosort output\n creation_time, _, _ = kilosort.extract_clustering_info(kilosort_dir)\n elif task_mode == 'trigger':\n raise NotImplementedError('Automatic triggering of'\n ' clustering analysis is not yet supported')\n else:\n raise ValueError(f'Unknown task mode: {task_mode}')\n\n self.insert1({**key, 'clustering_time': creation_time})\n\n\n@schema\nclass Curation(dj.Manual):\n definition = \"\"\"\n # Manual curation procedure\n -> Clustering\n curation_id: int\n ---\n curation_time: datetime # time of generation of this set of curated clustering results \n curation_output_dir: varchar(255) # output directory of the curated results, relative to clustering root data directory\n quality_control: bool # has this clustering result undergone quality control?\n manual_curation: bool # has manual curation been performed on this clustering result?\n curation_note='': varchar(2000) \n \"\"\"\n\n def create1_from_clustering_task(self, key, curation_note=''):\n \"\"\"\n A convenient function to create a new corresponding \"Curation\"\n for a particular \"ClusteringTask\"\n \"\"\"\n if key not in Clustering():\n raise ValueError(f'No corresponding entry in Clustering available'\n f' for: {key}; do `Clustering.populate(key)`')\n\n task_mode, output_dir = (ClusteringTask & key).fetch1(\n 'task_mode', 'clustering_output_dir')\n kilosort_dir = find_full_path(get_ephys_root_data_dir(), output_dir)\n\n creation_time, is_curated, is_qc = kilosort.extract_clustering_info(kilosort_dir)\n # Synthesize curation_id\n curation_id = dj.U().aggr(self & key, n='ifnull(max(curation_id)+1,1)').fetch1('n')\n self.insert1({**key, 'curation_id': curation_id,\n 'curation_time': creation_time, 'curation_output_dir': output_dir,\n 'quality_control': is_qc, 'manual_curation': is_curated,\n 'curation_note': curation_note})\n\n\n@schema\nclass CuratedClustering(dj.Imported):\n definition = \"\"\"\n # Clustering results of a curation.\n -> Curation \n \"\"\"\n\n class Unit(dj.Part):\n definition = \"\"\" \n # Properties of a given unit from a round of clustering (and curation)\n -> master\n unit: int\n ---\n -> probe.ElectrodeConfig.Electrode # electrode with highest waveform amplitude for this unit\n -> ClusterQualityLabel\n spike_count: int # how many spikes in this recording for this unit\n spike_times: longblob # (s) spike times of this unit, relative to the start of the EphysRecording\n spike_sites : longblob # array of electrode associated with each spike\n spike_depths : longblob # (um) array of depths associated with each spike, relative to the (0, 0) of the probe \n \"\"\"\n\n def make(self, key):\n output_dir = (Curation & key).fetch1('curation_output_dir')\n kilosort_dir = find_full_path(get_ephys_root_data_dir(), output_dir)\n\n kilosort_dataset = kilosort.Kilosort(kilosort_dir)\n acq_software = (EphysRecording & key).fetch1('acq_software')\n\n # ---------- Unit ----------\n # -- Remove 0-spike units\n withspike_idx = [i for i, u in enumerate(kilosort_dataset.data['cluster_ids'])\n if (kilosort_dataset.data['spike_clusters'] == u).any()]\n valid_units = kilosort_dataset.data['cluster_ids'][withspike_idx]\n valid_unit_labels = kilosort_dataset.data['cluster_groups'][withspike_idx]\n # -- Get channel and electrode-site mapping\n channel2electrodes = get_neuropixels_channel2electrode_map(key, acq_software)\n\n # -- Spike-times --\n # spike_times_sec_adj > spike_times_sec > spike_times\n spike_time_key = ('spike_times_sec_adj' if 'spike_times_sec_adj' in kilosort_dataset.data\n else 'spike_times_sec' if 'spike_times_sec'\n in kilosort_dataset.data else 'spike_times')\n spike_times = kilosort_dataset.data[spike_time_key]\n kilosort_dataset.extract_spike_depths()\n\n # -- Spike-sites and Spike-depths --\n spike_sites = np.array([channel2electrodes[s]['electrode']\n for s in kilosort_dataset.data['spike_sites']])\n spike_depths = kilosort_dataset.data['spike_depths']\n\n # -- Insert unit, label, peak-chn\n units = []\n for unit, unit_lbl in zip(valid_units, valid_unit_labels):\n if (kilosort_dataset.data['spike_clusters'] == unit).any():\n unit_channel, _ = kilosort_dataset.get_best_channel(unit)\n unit_spike_times = (spike_times[kilosort_dataset.data['spike_clusters'] == unit]\n / kilosort_dataset.data['params']['sample_rate'])\n spike_count = len(unit_spike_times)\n\n units.append({\n 'unit': unit,\n 'cluster_quality_label': unit_lbl,\n **channel2electrodes[unit_channel],\n 'spike_times': unit_spike_times,\n 'spike_count': spike_count,\n 'spike_sites': spike_sites[kilosort_dataset.data['spike_clusters'] == unit],\n 'spike_depths': spike_depths[kilosort_dataset.data['spike_clusters'] == unit]})\n\n self.insert1(key)\n self.Unit.insert([{**key, **u} for u in units])\n\n\n@schema\nclass WaveformSet(dj.Imported):\n definition = \"\"\"\n # A set of spike waveforms for units out of a given CuratedClustering\n -> CuratedClustering\n \"\"\"\n\n class PeakWaveform(dj.Part):\n definition = \"\"\"\n # Mean waveform across spikes for a given unit at its representative electrode\n -> master\n -> CuratedClustering.Unit\n ---\n peak_electrode_waveform: longblob # (uV) mean waveform for a given unit at its representative electrode\n \"\"\"\n\n class Waveform(dj.Part):\n definition = \"\"\"\n # Spike waveforms and their mean across spikes for the given unit\n -> master\n -> CuratedClustering.Unit\n -> probe.ElectrodeConfig.Electrode \n --- \n waveform_mean: longblob # (uV) mean waveform across spikes of the given unit\n waveforms=null: longblob # (uV) (spike x sample) waveforms of a sampling of spikes at the given electrode for the given unit\n \"\"\"\n\n def make(self, key):\n output_dir = (Curation & key).fetch1('curation_output_dir')\n kilosort_dir = find_full_path(get_ephys_root_data_dir(), output_dir)\n\n kilosort_dataset = kilosort.Kilosort(kilosort_dir)\n\n acq_software, probe_serial_number = (EphysRecording * ProbeInsertion & key).fetch1(\n 'acq_software', 'probe')\n\n # -- Get channel and electrode-site mapping\n recording_key = (EphysRecording & key).fetch1('KEY')\n channel2electrodes = get_neuropixels_channel2electrode_map(recording_key, acq_software)\n\n is_qc = (Curation & key).fetch1('quality_control')\n\n # Get all units\n units = {u['unit']: u for u in (CuratedClustering.Unit & key).fetch(\n as_dict=True, order_by='unit')}\n\n if is_qc:\n unit_waveforms = np.load(kilosort_dir / 'mean_waveforms.npy') # unit x channel x sample\n\n def yield_unit_waveforms():\n for unit_no, unit_waveform in zip(kilosort_dataset.data['cluster_ids'],\n unit_waveforms):\n unit_peak_waveform = {}\n unit_electrode_waveforms = []\n if unit_no in units:\n for channel, channel_waveform in zip(\n kilosort_dataset.data['channel_map'],\n unit_waveform):\n unit_electrode_waveforms.append({\n **units[unit_no], **channel2electrodes[channel],\n 'waveform_mean': channel_waveform})\n if channel2electrodes[channel]['electrode'] == units[unit_no]['electrode']:\n unit_peak_waveform = {\n **units[unit_no],\n 'peak_electrode_waveform': channel_waveform}\n yield unit_peak_waveform, unit_electrode_waveforms\n else:\n if acq_software == 'SpikeGLX':\n spikeglx_meta_filepath = get_spikeglx_meta_filepath(key)\n neuropixels_recording = spikeglx.SpikeGLX(spikeglx_meta_filepath.parent)\n elif acq_software == 'Open Ephys':\n sess_dir = pathlib.Path(get_session_directory(key))\n sess_dir_full = find_full_path(get_ephys_root_data_dir(), sess_dir)\n openephys_dataset = openephys.OpenEphys(sess_dir_full)\n neuropixels_recording = openephys_dataset.probes[probe_serial_number]\n\n def yield_unit_waveforms():\n for unit_dict in units.values():\n unit_peak_waveform = {}\n unit_electrode_waveforms = []\n\n spikes = unit_dict['spike_times']\n waveforms = neuropixels_recording.extract_spike_waveforms(\n spikes, kilosort_dataset.data['channel_map']) # (sample x channel x spike)\n waveforms = waveforms.transpose((1, 2, 0)) # (channel x spike x sample)\n for channel, channel_waveform in zip(\n kilosort_dataset.data['channel_map'], waveforms):\n unit_electrode_waveforms.append({\n **unit_dict, **channel2electrodes[channel],\n 'waveform_mean': channel_waveform.mean(axis=0),\n 'waveforms': channel_waveform})\n if channel2electrodes[channel]['electrode'] == unit_dict['electrode']:\n unit_peak_waveform = {\n **unit_dict,\n 'peak_electrode_waveform': channel_waveform.mean(axis=0)}\n\n yield unit_peak_waveform, unit_electrode_waveforms\n\n # insert waveform on a per-unit basis to mitigate potential memory issue\n self.insert1(key)\n for unit_peak_waveform, unit_electrode_waveforms in yield_unit_waveforms():\n self.PeakWaveform.insert1(unit_peak_waveform, ignore_extra_fields=True)\n self.Waveform.insert(unit_electrode_waveforms, ignore_extra_fields=True)\n\n\n# ---------------- HELPER FUNCTIONS ----------------\n\ndef get_spikeglx_meta_filepath(ephys_recording_key):\n # attempt to retrieve from EphysRecording.EphysFile\n spikeglx_meta_filepath = (EphysRecording.EphysFile & ephys_recording_key\n & 'file_path LIKE \"%.ap.meta\"').fetch1('file_path')\n\n try:\n spikeglx_meta_filepath = find_full_path(get_ephys_root_data_dir(),\n spikeglx_meta_filepath)\n except FileNotFoundError:\n # if not found, search in session_dir again\n if not spikeglx_meta_filepath.exists():\n sess_dir = pathlib.Path(get_session_directory(ephys_recording_key))\n inserted_probe_serial_number = (ProbeInsertion * probe.Probe\n & ephys_recording_key).fetch1('probe')\n\n spikeglx_meta_filepaths = [fp for fp in sess_dir.rglob('*.ap.meta')]\n for meta_filepath in spikeglx_meta_filepaths:\n spikeglx_meta = spikeglx.SpikeGLXMeta(meta_filepath)\n if str(spikeglx_meta.probe_SN) == inserted_probe_serial_number:\n spikeglx_meta_filepath = meta_filepath\n break\n else:\n raise FileNotFoundError(\n 'No SpikeGLX data found for probe insertion: {}'.format(ephys_recording_key))\n\n return spikeglx_meta_filepath\n\n\ndef get_neuropixels_channel2electrode_map(ephys_recording_key, acq_software):\n if acq_software == 'SpikeGLX':\n spikeglx_meta_filepath = get_spikeglx_meta_filepath(ephys_recording_key)\n spikeglx_meta = spikeglx.SpikeGLXMeta(spikeglx_meta_filepath)\n electrode_config_key = (EphysRecording * probe.ElectrodeConfig\n & ephys_recording_key).fetch1('KEY')\n\n electrode_query = (probe.ProbeType.Electrode\n * probe.ElectrodeConfig.Electrode & electrode_config_key)\n\n probe_electrodes = {\n (shank, shank_col, shank_row): key\n for key, shank, shank_col, shank_row in zip(*electrode_query.fetch(\n 'KEY', 'shank', 'shank_col', 'shank_row'))}\n\n channel2electrode_map = {\n recorded_site: probe_electrodes[(shank, shank_col, shank_row)]\n for recorded_site, (shank, shank_col, shank_row, _) in enumerate(\n spikeglx_meta.shankmap['data'])}\n elif acq_software == 'Open Ephys':\n sess_dir = pathlib.Path(get_session_directory(ephys_recording_key))\n sess_dir_full = find_full_path(get_ephys_root_data_dir(), sess_dir)\n openephys_dataset = openephys.OpenEphys(sess_dir_full)\n probe_serial_number = (ProbeInsertion & ephys_recording_key).fetch1('probe')\n probe_dataset = openephys_dataset.probes[probe_serial_number]\n\n electrode_query = (probe.ProbeType.Electrode\n * probe.ElectrodeConfig.Electrode\n * EphysRecording & ephys_recording_key)\n\n probe_electrodes = {key['electrode']: key\n for key in electrode_query.fetch('KEY')}\n\n channel2electrode_map = {\n channel_idx: probe_electrodes[channel_idx]\n for channel_idx in probe_dataset.ap_meta['channels_ids']}\n\n return channel2electrode_map\n\n\ndef generate_electrode_config(probe_type: str, electrodes: list):\n \"\"\"\n Generate and insert new ElectrodeConfig\n :param probe_type: probe type (e.g. neuropixels 2.0 - SS)\n :param electrodes: list of the electrode dict (keys of the probe.ProbeType.Electrode table)\n :return: a dict representing a key of the probe.ElectrodeConfig table\n \"\"\"\n # compute hash for the electrode config (hash of dict of all ElectrodeConfig.Electrode)\n electrode_config_hash = dict_to_uuid({k['electrode']: k for k in electrodes})\n\n electrode_list = sorted([k['electrode'] for k in electrodes])\n electrode_gaps = ([-1]\n + np.where(np.diff(electrode_list) > 1)[0].tolist()\n + [len(electrode_list) - 1])\n electrode_config_name = '; '.join([\n f'{electrode_list[start + 1]}-{electrode_list[end]}'\n for start, end in zip(electrode_gaps[:-1], electrode_gaps[1:])])\n\n electrode_config_key = {'electrode_config_hash': electrode_config_hash}\n\n # ---- make new ElectrodeConfig if needed ----\n if not probe.ElectrodeConfig & electrode_config_key:\n probe.ElectrodeConfig.insert1({**electrode_config_key, 'probe_type': probe_type,\n 'electrode_config_name': electrode_config_name})\n probe.ElectrodeConfig.Electrode.insert({**electrode_config_key, **electrode}\n for electrode in electrodes)\n\n return electrode_config_key\n\n"
]
[
"import torch\nimport torch.nn.functional as F\nfrom torch import nn\nimport time\nfrom models import MLP\nfrom action_utils import select_action, translate_action\nfrom networks import ProtoNetwork, ProtoLayer\nfrom noise import OUNoise\nimport numpy as np\n\nclass CommNetMLP(nn.Module):\n \"\"\"\n MLP based CommNet. Uses communication vector to communicate info\n between agents\n \"\"\"\n def __init__(self, args, num_inputs, train_mode=True):\n \"\"\"Initialization method for this class, setup various internal networks\n and weights\n\n Arguments:\n MLP {object} -- Self\n args {Namespace} -- Parse args namespace\n num_inputs {number} -- Environment observation dimension for agents\n \"\"\"\n\n super(CommNetMLP, self).__init__()\n self.args = args\n self.nagents = args.nagents\n self.hid_size = args.hid_size\n self.comm_passes = args.comm_passes\n self.recurrent = args.recurrent\n self.continuous = args.continuous\n # If true, we add noise to the communication being output by each agent.\n self.add_comm_noise = args.add_comm_noise\n\n # TODO: remove this is just for debugging purposes just to verify that the communication is happening in a\n # disrete manner\n self.unique_comms = []\n\n # defining mode which is useful in the case of prototype layers.\n self.train_mode = train_mode\n\n # Only really used when you're using prototypes\n self.exploration_noise = OUNoise(args.comm_dim)\n self.explore_choose_proto_noise = OUNoise(args.num_proto)\n\n # see if you're using discrete communication and using prototypes\n self.discrete_comm = args.discrete_comm\n # self.use_proto = args.use_proto\n\n # num_proto is not really relevant when use_proto is set to False\n self.num_proto = args.num_proto\n\n # this is discrete/proto communication which is not to be confused with discrete action. T\n # Although since the communication is being added to the encoded state directly, it makes things a bit tricky.\n if args.discrete_comm:\n self.proto_layer = ProtoNetwork(args.hid_size, args.comm_dim, args.discrete_comm, num_layers=2,\n hidden_dim=64, num_protos=args.num_proto, constrain_out=False)\n\n if self.continuous:\n self.action_mean = nn.Linear(args.hid_size, args.dim_actions)\n self.action_log_std = nn.Parameter(torch.zeros(1, args.dim_actions))\n else:\n self.heads = nn.ModuleList([nn.Linear(args.hid_size, o)\n for o in args.naction_heads])\n\n\n self.init_std = args.init_std if hasattr(args, 'comm_init_std') else 0.2\n\n # Mask for communication\n if self.args.comm_mask_zero:\n self.comm_mask = torch.zeros(self.nagents, self.nagents)\n else:\n # this just prohibits self communication\n self.comm_mask = torch.ones(self.nagents, self.nagents) \\\n - torch.eye(self.nagents, self.nagents)\n\n\n # Since linear layers in PyTorch now accept * as any number of dimensions\n # between last and first dim, num_agents dimension will be covered.\n # The network below is function r in the paper for encoding\n # initial environment stage\n\n # Note: num_inputs is 29 in the case Predator Prey.\n # TODO: Since currently you directly add the weighted hidden state to the encoded observation\n # the output of the encoder is of the shape hidden. Basically we need to now make sure that in case of\n # discrete also the dimension of the output of the state encoder is same as dimension of the output of the\n # discrete communication.\n\n # self.encoder = nn.Linear(num_inputs, args.hid_size)\n\n # changed this for prototype based method. But should still work in the old case.\n self.encoder = nn.Linear(num_inputs, args.comm_dim)\n\n # if self.args.env_name == 'starcraft':\n # self.state_encoder = nn.Linear(num_inputs, num_inputs)\n # self.encoder = nn.Linear(num_inputs * 2, args.hid_size)\n if args.recurrent:\n self.hidd_encoder = nn.Linear(args.hid_size, args.hid_size)\n\n # TODO: currently the prototype is only being handled for the recurrent case. Do it more generally\n if args.recurrent:\n # not sure why is hidden dependent on batch size\n # also the initialised hiddens arent being assigned to anything\n self.init_hidden(args.batch_size)\n\n # Old code when the input size was equal to the hidden size.\n # self.f_module = nn.LSTMCell(args.hid_size, args.hid_size)\n\n self.f_module = nn.LSTMCell(args.comm_dim, args.hid_size)\n\n\n else:\n if args.share_weights:\n self.f_module = nn.Linear(args.hid_size, args.hid_size)\n self.f_modules = nn.ModuleList([self.f_module\n for _ in range(self.comm_passes)])\n else:\n self.f_modules = nn.ModuleList([nn.Linear(args.hid_size, args.hid_size)\n for _ in range(self.comm_passes)])\n # else:\n # raise RuntimeError(\"Unsupported RNN type.\")\n\n # Our main function for converting current hidden state to next state\n # self.f = nn.Linear(args.hid_size, args.hid_size)\n\n if args.share_weights:\n self.C_module = nn.Linear(args.hid_size, args.hid_size)\n self.C_modules = nn.ModuleList([self.C_module\n for _ in range(self.comm_passes)])\n else:\n # changed t\n # self.C_modules = nn.ModuleList([nn.Linear(args.hid_size, args.hid_size)\n # for _ in range(self.comm_passes)])\n\n self.C_modules = nn.ModuleList([nn.Linear(args.comm_dim, args.comm_dim)\n for _ in range(self.comm_passes)])\n\n # self.C = nn.Linear(args.hid_size, args.hid_size)\n\n # initialise weights as 0\n\n if args.comm_init == 'zeros':\n for i in range(self.comm_passes):\n self.C_modules[i].weight.data.zero_()\n self.tanh = nn.Tanh()\n\n # print(self.C)\n # self.C.weight.data.zero_()\n # Init weights for linear layers\n # self.apply(self.init_weights)\n\n self.value_head = nn.Linear(self.hid_size, 1)\n\n # communication limit, default always allows communication\n self.comm_budget = torch.tensor([self.args.max_steps+1] * self.nagents)\n self.budget = args.budget\n\n # autoencoder decoder\n if self.args.autoencoder_action:\n self.decoderNet = nn.Linear(args.hid_size, num_inputs+self.args.nagents)\n else:\n self.decoderNet = nn.Linear(args.hid_size, num_inputs)\n\n # remove null messages\n # with open('IC3Net/nulls/'+self.args.pretrain_exp_name+'/seed' + str(self.args.seed) + '/nulls.txt', 'r') as f:\n # with open('/Users/seth/Documents/research/neurips/nulls/tj_easy_proto_soft_minComm_autoencoder/seed' + str(self.args.seed) + '/nulls.txt', 'r') as f:\n # with open('/Users/seth/Documents/research/neurips/nulls/'+self.args.exp_name+'/seed' + str(self.args.seed) + '/nulls.txt', 'r') as f:\n if self.args.remove_null:\n null_path = os.path.join(self.args.null_dict_dir, exp_name, \"seed\" + str(seed), 'nulls.txt')\n with open(null_path) as f:\n protos = f.readlines()\n for i in range(len(protos)):\n protos[i] = protos[i].replace(\"\\n\", \"\").split(',')\n self.null_dict = torch.tensor(np.array(protos).astype(np.float32))\n\n self.num_null = 0\n self.num_good_comms = 0\n self.num_cut_comms = 0\n self.num_comms = 0\n\n self.null_action = np.zeros(self.args.nagents)\n\n def get_agent_mask(self, batch_size, info):\n n = self.nagents\n\n if 'alive_mask' in info:\n agent_mask = torch.from_numpy(info['alive_mask'])\n num_agents_alive = agent_mask.sum()\n else:\n agent_mask = torch.ones(n)\n num_agents_alive = n\n\n agent_mask = agent_mask.view(1, 1, n)\n agent_mask = agent_mask.expand(batch_size, n, n).unsqueeze(-1)\n\n return num_agents_alive, agent_mask\n\n def forward_state_encoder(self, x):\n hidden_state, cell_state = None, None\n\n if self.args.recurrent:\n x, extras = x\n\n # In case of recurrent first take out the actual observation and then encode it.\n x = self.encoder(x)\n\n if self.args.rnn_type == 'LSTM':\n # if you're using the extras would have both the hidden and the cell state.\n hidden_state, cell_state = extras\n else:\n hidden_state = extras\n # hidden_state = self.tanh( self.hidd_encoder(prev_hidden_state) + x)\n else:\n x = self.encoder(x)\n x = self.tanh(x)\n hidden_state = x\n\n return x, hidden_state, cell_state\n\n def decode(self):\n y = self.h_state + self.comms_all\n y = self.decoderNet(y)\n return y\n\n def get_null_action(self):\n return self.null_action\n\n def forward(self, x, info={}):\n # TODO: Update dimensions\n \"\"\"Forward function for CommNet class, expects state, previous hidden\n and communication tensor.\n B: Batch Size: Normally 1 in case of episode\n N: number of agents\n\n Arguments:\n x {tensor} -- State of the agents (N x num_inputs)\n prev_hidden_state {tensor} -- Previous hidden state for the networks in\n case of multiple passes (1 x N x hid_size)\n comm_in {tensor} -- Communication tensor for the network. (1 x N x N x hid_size)\n\n Returns:\n tuple -- Contains\n next_hidden {tensor}: Next hidden state for network\n comm_out {tensor}: Next communication tensor\n action_data: Data needed for taking next action (Discrete values in\n case of discrete, mean and std in case of continuous)\n v: value head\n \"\"\"\n\n # if self.args.env_name == 'starcraft':\n # maxi = x.max(dim=-2)[0]\n # x = self.state_encoder(x)\n # x = x.sum(dim=-2)\n # x = torch.cat([x, maxi], dim=-1)\n # x = self.tanh(x)\n\n # print(x[0].size(), x[0],\"\\n\")\n x, hidden_state, cell_state = self.forward_state_encoder(x)\n if self.args.autoencoder:\n self.h_state = hidden_state.clone()\n # print(x, hidden_state, cell_state)\n # import sys\n # sys.exit(0)\n batch_size = x.size()[0]\n n = self.nagents\n\n # this should remain regardless of using prototypes or not.\n num_agents_alive, agent_mask = self.get_agent_mask(batch_size, info)\n\n # Hard Attention - action whether an agent communicates or not\n if self.args.hard_attn:\n comm_action = torch.tensor(info['comm_action'])\n for c in range(self.args.nagents):\n if agent_mask[0,0,c] == 0: continue\n # if info['comm_action'][c] == 0:\n # self.num_cut_comms += 1\n self.num_comms += num_agents_alive\n # not sure if this passes batch sizes larger than 1\n # assert batch_size == 1\n # if info['step_t'] == 0:\n # # reset communication budget at the beginning of the episode\n # self.comm_budget = self.budget * torch.tensor([self.args.max_steps] * self.nagents\n # # self.comm_budget -= comm_action\n # if self.budget != 1:\n # comm_action[self.comm_budget <= 0] = 0\n # Add random masking according to the budget\n if self.train_mode:\n info['comm_budget'] = np.random.choice([1.,0.], size=self.nagents, p=[self.budget, 1-self.budget])\n comm_action = comm_action * info['comm_budget']\n # print(\"comm action, budget\", comm_action, self.comm_budget, info['step_t'])\n comm_action_mask = comm_action.expand(batch_size, n, n).unsqueeze(-1)\n # action 1 is talk, 0 is silent i.e. act as dead for comm purposes.\n agent_mask = agent_mask * comm_action_mask.double()\n\n agent_mask_transpose = agent_mask.transpose(1, 2)\n all_comms = []\n for i in range(self.comm_passes):\n if self.args.use_proto:\n raw_outputs = self.proto_layer(hidden_state)\n # raw_outputs is of shape (1, num_agents, num_protos). But we need to get rid of that first dimension.\n raw_outputs = torch.squeeze(raw_outputs, 0)\n if self.train_mode:\n comm = self.proto_layer.step(raw_outputs, True, self.explore_choose_proto_noise, 'cpu')\n else:\n comm = self.proto_layer.step(raw_outputs, False, None, 'cpu')\n all_comms.append(comm.detach().clone())\n # Comm assumes shape (1, num_agents, num_protos), so just add that dimension back in.\n comm = torch.unsqueeze(comm, 0)\n\n if self.add_comm_noise:\n # Currently, just hardcoded. We want enough noise to have an effect but not too much to prevent\n # learning.\n std = 0.2 # 0.4 for dim 16\n # Generates samples from a zero-mean unit gaussian, which we rescale by the std parameter.\n noise = torch.randn_like(comm) * std\n comm += noise\n # check if comm contains null vector\n # print(comm.shape) # 1,5,64\n # sys.exit()\n # if self.args.null_regularization:\n\n elif self.args.discrete_comm: #one-hot\n raw_outputs = self.proto_layer(hidden_state)\n raw_outputs = torch.squeeze(raw_outputs, 0)\n comm = self.proto_layer.onehot_step(raw_outputs, self.train_mode)\n all_comms.append(comm.detach().clone())\n comm = torch.unsqueeze(comm, 0)\n\n else:\n # print(f\"inside else {hidden_state.size()}\")\n comm = hidden_state\n # print(\"before\", comm.shape, comm) # (5,32)\n all_comms.append(torch.squeeze(comm, 0).detach().clone())\n assert self.args.comm_dim == self.args.hid_size , \"If not using protos comm dim should be same as hid\"\n\n if self.args.remove_null:\n null_mask = torch.ones_like(comm)\n for j in range(self.args.nagents):\n if agent_mask[0,0,j] == 0:\n continue\n # print(comm[0,j].shape, self.null_dict[0].shape)\n found_null = False\n for null_i in range(len(self.null_dict)):\n # print(torch.nn.functional.mse_loss(self.null_dict[null_i], comm[0,j]))\n if torch.nn.functional.mse_loss(self.null_dict[null_i], comm[0,j]) < 0.1:\n null_mask[0,j] *= 0\n found_null = True\n break\n if not found_null:\n # track non null communicated\n if info['comm_action'][j] == 1:\n self.num_good_comms += 1\n # else:\n # if info['comm_action'][j] == 0:\n # self.num_null += 1\n self.null_action = np.zeros(self.args.nagents)\n if 'null' in self.args.exp_name or True:\n for j in range(self.args.nagents):\n if null_mask[0,j].sum() == 0:\n if info['comm_action'][j] == 1: # we cut an additional communication\n self.null_action[j] = 1 # get one comm back for later\n self.num_null += 1\n self.num_cut_comms += 1\n comm = comm * null_mask\n # comm = hidden_state.view(batch_size, n, self.hid_size) if self.args.recurrent else hidden_state\n comm = comm.view(batch_size, n, self.args.comm_dim) if self.args.recurrent else comm\n # Get the next communication vector based on next hidden state\n # comm = comm.unsqueeze(-2).expand(-1, n, n, self.hid_size)\n\n # changed for accomadating prototype based approach as well.\n comm = comm.unsqueeze(-2).expand(-1, n, n, self.args.comm_dim)\n\n # Create mask for masking self communication\n mask = self.comm_mask.view(1, n, n)\n\n mask = mask.expand(comm.shape[0], n, n)\n mask = mask.unsqueeze(-1)\n\n mask = mask.expand_as(comm)\n comm = comm * mask\n\n # print(\"comm mode \", self.args.comm_mode)\n if hasattr(self.args, 'comm_mode') and self.args.comm_mode == 'avg' \\\n and num_agents_alive > 1:\n comm = comm / (num_agents_alive - 1)\n\n # Mask comm_in\n # Mask communcation from dead agents\n comm = comm * agent_mask\n # Mask communication to dead agents\n comm = comm * agent_mask_transpose\n # Combine all of C_j for an ith agent which essentially are h_j\n comm_sum = comm.sum(dim=1)\n\n c = self.C_modules[i](comm_sum)\n if self.args.autoencoder:\n self.comms_all = c.clone() # encoded received communciations for autoencoder\n\n if self.args.recurrent:\n # skip connection - combine comm. matrix and encoded input for all agents\n inp = x + c\n\n # inp = inp.view(batch_size * n, self.hid_size)\n\n inp = inp.view(batch_size * n, self.args.comm_dim)\n\n output = self.f_module(inp, (hidden_state, cell_state))\n\n hidden_state = output[0]\n cell_state = output[1]\n\n else: # MLP|RNN\n # Get next hidden state from f node\n # and Add skip connection from start and sum them\n hidden_state = sum([x, self.f_modules[i](hidden_state), c])\n hidden_state = self.tanh(hidden_state)\n\n # v = torch.stack([self.value_head(hidden_state[:, i, :]) for i in range(n)])\n # v = v.view(hidden_state.size(0), n, -1)\n value_head = self.value_head(hidden_state)\n h = hidden_state.view(batch_size, n, self.hid_size)\n\n if self.continuous:\n action_mean = self.action_mean(h)\n action_log_std = self.action_log_std.expand_as(action_mean)\n action_std = torch.exp(action_log_std)\n # will be used later to sample\n action = (action_mean, action_log_std, action_std)\n else:\n # discrete actions\n action = [F.log_softmax(head(h), dim=-1) for head in self.heads]\n # print(f\"uses discrete actions {action}\")\n if self.args.recurrent:\n if info.get('record_comms') is not None:\n # Go through the all comms passes and only pick out comms for the agent you want.\n # filtered_comms = np.array([c[info.get('record_comms')] for c in all_comms])\n filtered_comms = np.array([c.numpy() for c in all_comms])\n if self.args.env_name == 'predator_prey':\n assert len(filtered_comms) == 1, \"Only support one agent at a time\"\n # print(\"communication comm.py\", c.shape, len(filtered_comms[0]))\n # print(info['comm_action'])\n return action, value_head, (hidden_state.clone(), cell_state.clone()), filtered_comms\n return action, value_head, (hidden_state.clone(), cell_state.clone())\n else:\n if info.get('record_comms') is not None:\n filtered_comms = [c[info.get('record_comms')] for c in all_comms]\n assert len(filtered_comms) == 1, \"Only support one agent at a time\"\n return action, value_head, filtered_comms[0]\n return action, value_head\n\n def init_weights(self, m):\n if type(m) == nn.Linear:\n m.weight.data.normal_(0, self.init_std)\n\n def init_hidden(self, batch_size):\n # dim 0 = num of layers * num of direction\n return tuple(( torch.zeros(batch_size * self.nagents, self.hid_size, requires_grad=True),\n torch.zeros(batch_size * self.nagents, self.hid_size, requires_grad=True)))\n"
]
[
"import numpy as np\nimport math\nimport functools\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.nn import Parameter as P\n\nimport layers\nfrom sync_batchnorm import SynchronizedBatchNorm2d as SyncBatchNorm2d\n\n# BigGAN-deep: uses a different resblock and pattern\n\n\n# Architectures for G\n# Attention is passed in in the format '32_64' to mean applying an attention\n# block at both resolution 32x32 and 64x64. Just '64' will apply at 64x64.\n\n# Channel ratio is the ratio of\nclass GBlock(nn.Module):\n def __init__(self, in_channels, out_channels,\n which_conv=nn.Conv2d, which_bn=layers.bn, activation=None,\n upsample=None, channel_ratio=4):\n super(GBlock, self).__init__()\n\n self.in_channels, self.out_channels = in_channels, out_channels\n self.hidden_channels = self.in_channels // channel_ratio\n self.which_conv, self.which_bn = which_conv, which_bn\n self.activation = activation\n self.upsample = upsample\n # Conv layers\n self.conv1 = self.which_conv(self.in_channels, self.hidden_channels,\n kernel_size=1, padding=0)\n self.conv2 = self.which_conv(self.hidden_channels, self.hidden_channels)\n self.conv3 = self.which_conv(self.hidden_channels, self.hidden_channels)\n self.conv4 = self.which_conv(self.hidden_channels, self.out_channels,\n kernel_size=1, padding=0)\n # Batchnorm layers\n self.bn1 = self.which_bn(self.in_channels)\n self.bn2 = self.which_bn(self.hidden_channels)\n self.bn3 = self.which_bn(self.hidden_channels)\n self.bn4 = self.which_bn(self.hidden_channels)\n # upsample layers\n self.upsample = upsample\n\n def forward(self, x, y):\n # Project down to channel ratio\n h = self.conv1(self.activation(self.bn1(x, y)))\n # Apply next BN-ReLU\n h = self.activation(self.bn2(h, y))\n # Drop channels in x if necessary\n if self.in_channels != self.out_channels:\n x = x[:, :self.out_channels]\n # Upsample both h and x at this point\n if self.upsample:\n h = self.upsample(h)\n x = self.upsample(x)\n # 3x3 convs\n h = self.conv2(h)\n h = self.conv3(self.activation(self.bn3(h, y)))\n # Final 1x1 conv\n h = self.conv4(self.activation(self.bn4(h, y)))\n return h + x\n\ndef G_arch(ch=64, attention='64', ksize='333333', dilation='111111'):\n arch = {}\n arch[256] = {'in_channels' : [ch * item for item in [16, 16, 8, 8, 4, 2]],\n 'out_channels' : [ch * item for item in [16, 8, 8, 4, 2, 1]],\n 'upsample' : [True] * 6,\n 'resolution' : [8, 16, 32, 64, 128, 256],\n 'attention' : {2**i: (2**i in [int(item) for item in attention.split('_')])\n for i in range(3,9)}}\n arch[128] = {'in_channels' : [ch * item for item in [16, 16, 8, 4, 2]],\n 'out_channels' : [ch * item for item in [16, 8, 4, 2, 1]],\n 'upsample' : [True] * 5,\n 'resolution' : [8, 16, 32, 64, 128],\n 'attention' : {2**i: (2**i in [int(item) for item in attention.split('_')])\n for i in range(3,8)}}\n arch[64] = {'in_channels' : [ch * item for item in [16, 16, 8, 4]],\n 'out_channels' : [ch * item for item in [16, 8, 4, 2]],\n 'upsample' : [True] * 4,\n 'resolution' : [8, 16, 32, 64],\n 'attention' : {2**i: (2**i in [int(item) for item in attention.split('_')])\n for i in range(3,7)}}\n arch[32] = {'in_channels' : [ch * item for item in [4, 4, 4]],\n 'out_channels' : [ch * item for item in [4, 4, 4]],\n 'upsample' : [True] * 3,\n 'resolution' : [8, 16, 32],\n 'attention' : {2**i: (2**i in [int(item) for item in attention.split('_')])\n for i in range(3,6)}}\n\n return arch\n\nclass Generator(nn.Module):\n def __init__(self, G_ch=64, G_depth=2, dim_z=128, bottom_width=4, resolution=128,\n G_kernel_size=3, G_attn='64', n_classes=1000,\n num_G_SVs=1, num_G_SV_itrs=1,\n G_shared=True, shared_dim=0, hier=False,\n cross_replica=False, mybn=False,\n G_activation=nn.ReLU(inplace=False),\n G_lr=5e-5, G_B1=0.0, G_B2=0.999, adam_eps=1e-8,\n BN_eps=1e-5, SN_eps=1e-12, G_mixed_precision=False, G_fp16=False,\n G_init='ortho', skip_init=False, no_optim=False,\n G_param='SN', norm_style='bn', quiet=False,\n **kwargs):\n super(Generator, self).__init__()\n # Channel width mulitplier\n self.ch = G_ch\n # Number of resblocks per stage\n self.G_depth = G_depth\n # Dimensionality of the latent space\n self.dim_z = dim_z\n # The initial spatial dimensions\n self.bottom_width = bottom_width\n # Resolution of the output\n self.resolution = resolution\n # Kernel size?\n self.kernel_size = G_kernel_size\n # Attention?\n self.attention = G_attn\n # number of classes, for use in categorical conditional generation\n self.n_classes = n_classes\n # Use shared embeddings?\n self.G_shared = G_shared\n # Dimensionality of the shared embedding? Unused if not using G_shared\n self.shared_dim = shared_dim if shared_dim > 0 else dim_z\n # Hierarchical latent space?\n self.hier = hier\n # Cross replica batchnorm?\n self.cross_replica = cross_replica\n # Use my batchnorm?\n self.mybn = mybn\n # nonlinearity for residual blocks\n self.activation = G_activation\n # Initialization style\n self.init = G_init\n # Parameterization style\n self.G_param = G_param\n # Normalization style\n self.norm_style = norm_style\n # Epsilon for BatchNorm?\n self.BN_eps = BN_eps\n # Epsilon for Spectral Norm?\n self.SN_eps = SN_eps\n # fp16?\n self.fp16 = G_fp16\n # Architecture dict\n self.arch = G_arch(self.ch, self.attention)[resolution]\n\n\n # Which convs, batchnorms, and linear layers to use\n if self.G_param == 'SN':\n self.which_conv = functools.partial(layers.SNConv2d,\n kernel_size=3, padding=1,\n num_svs=num_G_SVs, num_itrs=num_G_SV_itrs,\n eps=self.SN_eps)\n self.which_linear = functools.partial(layers.SNLinear,\n num_svs=num_G_SVs, num_itrs=num_G_SV_itrs,\n eps=self.SN_eps)\n else:\n self.which_conv = functools.partial(nn.Conv2d, kernel_size=3, padding=1)\n self.which_linear = nn.Linear\n\n # We use a non-spectral-normed embedding here regardless;\n # For some reason applying SN to G's embedding seems to randomly cripple G\n self.which_embedding = nn.Embedding\n bn_linear = (functools.partial(self.which_linear, bias=False) if self.G_shared\n else self.which_embedding)\n self.which_bn = functools.partial(layers.ccbn,\n which_linear=bn_linear,\n cross_replica=self.cross_replica,\n mybn=self.mybn,\n input_size=(self.shared_dim + self.dim_z if self.G_shared\n else self.n_classes),\n norm_style=self.norm_style,\n eps=self.BN_eps)\n\n\n # Prepare model\n # If not using shared embeddings, self.shared is just a passthrough\n self.shared = (self.which_embedding(n_classes, self.shared_dim) if G_shared\n else layers.identity())\n # First linear layer\n self.linear = self.which_linear(self.dim_z + self.shared_dim, self.arch['in_channels'][0] * (self.bottom_width **2))\n\n # self.blocks is a doubly-nested list of modules, the outer loop intended\n # to be over blocks at a given resolution (resblocks and/or self-attention)\n # while the inner loop is over a given block\n self.blocks = []\n for index in range(len(self.arch['out_channels'])):\n self.blocks += [[GBlock(in_channels=self.arch['in_channels'][index],\n out_channels=self.arch['in_channels'][index] if g_index==0 else self.arch['out_channels'][index],\n which_conv=self.which_conv,\n which_bn=self.which_bn,\n activation=self.activation,\n upsample=(functools.partial(F.interpolate, scale_factor=2)\n if self.arch['upsample'][index] and g_index == (self.G_depth-1) else None))]\n for g_index in range(self.G_depth)]\n\n # If attention on this block, attach it to the end\n if self.arch['attention'][self.arch['resolution'][index]]:\n if not quiet:\n print('Adding attention layer in G at resolution %d' % self.arch['resolution'][index])\n self.blocks[-1] += [layers.Attention(self.arch['out_channels'][index], self.which_conv)]\n\n # Turn self.blocks into a ModuleList so that it's all properly registered.\n self.blocks = nn.ModuleList([nn.ModuleList(block) for block in self.blocks])\n\n # output layer: batchnorm-relu-conv.\n # Consider using a non-spectral conv here\n self.output_layer = nn.Sequential(layers.bn(self.arch['out_channels'][-1],\n cross_replica=self.cross_replica,\n mybn=self.mybn),\n self.activation,\n self.which_conv(self.arch['out_channels'][-1], 3))\n\n # Initialize weights. Optionally skip init for testing.\n if not skip_init:\n self.init_weights(quiet)\n\n # Set up optimizer\n # If this is an EMA copy, no need for an optim, so just return now\n if no_optim:\n return\n self.lr, self.B1, self.B2, self.adam_eps = G_lr, G_B1, G_B2, adam_eps\n if G_mixed_precision:\n if not quiet:\n print('Using fp16 adam in G...')\n import utils\n self.optim = utils.Adam16(params=self.parameters(), lr=self.lr,\n betas=(self.B1, self.B2), weight_decay=0,\n eps=self.adam_eps)\n else:\n self.optim = optim.Adam(params=self.parameters(), lr=self.lr,\n betas=(self.B1, self.B2), weight_decay=0,\n eps=self.adam_eps)\n\n # LR scheduling, left here for forward compatibility\n # self.lr_sched = {'itr' : 0}# if self.progressive else {}\n # self.j = 0\n\n # Initialize\n def init_weights(self, quiet=False):\n self.param_count = 0\n for module in self.modules():\n if (isinstance(module, nn.Conv2d)\n or isinstance(module, nn.Linear)\n or isinstance(module, nn.Embedding)):\n if self.init == 'ortho':\n init.orthogonal_(module.weight)\n elif self.init == 'N02':\n init.normal_(module.weight, 0, 0.02)\n elif self.init in ['glorot', 'xavier']:\n init.xavier_uniform_(module.weight)\n else:\n raise RuntimeError('Init style not recognized...')\n self.param_count += sum([p.data.nelement() for p in module.parameters()])\n if not quiet:\n print('Param count for G''s initialized parameters: %d' % self.param_count)\n\n # Note on this forward function: we pass in a y vector which has\n # already been passed through G.shared to enable easy class-wise\n # interpolation later. If we passed in the one-hot and then ran it through\n # G.shared in this forward function, it would be harder to handle.\n # NOTE: The z vs y dichotomy here is for compatibility with not-y\n def forward(self, z, y):\n # If hierarchical, concatenate zs and ys\n if self.hier:\n z = torch.cat([y, z], 1)\n y = z\n # First linear layer\n h = self.linear(z)\n # Reshape\n h = h.view(h.size(0), -1, self.bottom_width, self.bottom_width)\n # Loop over blocks\n for index, blocklist in enumerate(self.blocks):\n # Second inner loop in case block has multiple layers\n for block in blocklist:\n h = block(h, y)\n\n # Apply batchnorm-relu-conv-tanh at output\n return torch.tanh(self.output_layer(h))\n\nclass DBlock(nn.Module):\n def __init__(self, in_channels, out_channels, which_conv=layers.SNConv2d, wide=True,\n preactivation=True, activation=None, downsample=None,\n channel_ratio=4):\n super(DBlock, self).__init__()\n self.in_channels, self.out_channels = in_channels, out_channels\n # If using wide D (as in SA-GAN and BigGAN), change the channel pattern\n self.hidden_channels = self.out_channels // channel_ratio\n self.which_conv = which_conv\n self.preactivation = preactivation\n self.activation = activation\n self.downsample = downsample\n\n # Conv layers\n self.conv1 = self.which_conv(self.in_channels, self.hidden_channels,\n kernel_size=1, padding=0)\n self.conv2 = self.which_conv(self.hidden_channels, self.hidden_channels)\n self.conv3 = self.which_conv(self.hidden_channels, self.hidden_channels)\n self.conv4 = self.which_conv(self.hidden_channels, self.out_channels,\n kernel_size=1, padding=0)\n\n self.learnable_sc = True if (in_channels != out_channels) else False\n if self.learnable_sc:\n self.conv_sc = self.which_conv(in_channels, out_channels - in_channels,\n kernel_size=1, padding=0)\n def shortcut(self, x):\n if self.downsample:\n x = self.downsample(x)\n if self.learnable_sc:\n x = torch.cat([x, self.conv_sc(x)], 1)\n return x\n\n def forward(self, x):\n # 1x1 bottleneck conv\n h = self.conv1(F.relu(x))\n # 3x3 convs\n h = self.conv2(self.activation(h))\n h = self.conv3(self.activation(h))\n # relu before downsample\n h = self.activation(h)\n # downsample\n if self.downsample:\n h = self.downsample(h)\n # final 1x1 conv\n h = self.conv4(h)\n return h + self.shortcut(x)\n\n# Discriminator architecture, same paradigm as G's above\ndef D_arch(ch=64, attention='64',ksize='333333', dilation='111111'):\n arch = {}\n arch[256] = {'in_channels' : [item * ch for item in [1, 2, 4, 8, 8, 16]],\n 'out_channels' : [item * ch for item in [2, 4, 8, 8, 16, 16]],\n 'downsample' : [True] * 6 + [False],\n 'resolution' : [128, 64, 32, 16, 8, 4, 4 ],\n 'attention' : {2**i: 2**i in [int(item) for item in attention.split('_')]\n for i in range(2,8)}}\n arch[128] = {'in_channels' : [item * ch for item in [1, 2, 4, 8, 16]],\n 'out_channels' : [item * ch for item in [2, 4, 8, 16, 16]],\n 'downsample' : [True] * 5 + [False],\n 'resolution' : [64, 32, 16, 8, 4, 4],\n 'attention' : {2**i: 2**i in [int(item) for item in attention.split('_')]\n for i in range(2,8)}}\n arch[64] = {'in_channels' : [item * ch for item in [1, 2, 4, 8]],\n 'out_channels' : [item * ch for item in [2, 4, 8, 16]],\n 'downsample' : [True] * 4 + [False],\n 'resolution' : [32, 16, 8, 4, 4],\n 'attention' : {2**i: 2**i in [int(item) for item in attention.split('_')]\n for i in range(2,7)}}\n arch[32] = {'in_channels' : [item * ch for item in [4, 4, 4]],\n 'out_channels' : [item * ch for item in [4, 4, 4]],\n 'downsample' : [True, True, False, False],\n 'resolution' : [16, 16, 16, 16],\n 'attention' : {2**i: 2**i in [int(item) for item in attention.split('_')]\n for i in range(2,6)}}\n return arch\n\nclass Discriminator(nn.Module):\n\n def __init__(self, D_ch=64, D_wide=True, D_depth=2, resolution=128,\n D_kernel_size=3, D_attn='64', n_classes=1000,\n num_D_SVs=1, num_D_SV_itrs=1, D_activation=nn.ReLU(inplace=False),\n D_lr=2e-4, D_B1=0.0, D_B2=0.999, adam_eps=1e-8,\n SN_eps=1e-12, output_dim=1, D_mixed_precision=False, D_fp16=False,\n D_init='ortho', skip_init=False, D_param='SN', **kwargs):\n super(Discriminator, self).__init__()\n # Width multiplier\n self.ch = D_ch\n # Use Wide D as in BigGAN and SA-GAN or skinny D as in SN-GAN?\n self.D_wide = D_wide\n # How many resblocks per stage?\n self.D_depth = D_depth\n # Resolution\n self.resolution = resolution\n # Kernel size\n self.kernel_size = D_kernel_size\n # Attention?\n self.attention = D_attn\n # Number of classes\n self.n_classes = n_classes\n # Activation\n self.activation = D_activation\n # Initialization style\n self.init = D_init\n # Parameterization style\n self.D_param = D_param\n # Epsilon for Spectral Norm?\n self.SN_eps = SN_eps\n # Fp16?\n self.fp16 = D_fp16\n # Architecture\n self.arch = D_arch(self.ch, self.attention)[resolution]\n\n\n # Which convs, batchnorms, and linear layers to use\n # No option to turn off SN in D right now\n if self.D_param == 'SN':\n self.which_conv = functools.partial(layers.SNConv2d,\n kernel_size=3, padding=1,\n num_svs=num_D_SVs, num_itrs=num_D_SV_itrs,\n eps=self.SN_eps)\n self.which_linear = functools.partial(layers.SNLinear,\n num_svs=num_D_SVs, num_itrs=num_D_SV_itrs,\n eps=self.SN_eps)\n self.which_embedding = functools.partial(layers.SNEmbedding,\n num_svs=num_D_SVs, num_itrs=num_D_SV_itrs,\n eps=self.SN_eps)\n\n\n # Prepare model\n # Stem convolution\n self.input_conv = self.which_conv(3, self.arch['in_channels'][0])\n # self.blocks is a doubly-nested list of modules, the outer loop intended\n # to be over blocks at a given resolution (resblocks and/or self-attention)\n self.blocks = []\n for index in range(len(self.arch['out_channels'])):\n self.blocks += [[DBlock(in_channels=self.arch['in_channels'][index] if d_index==0 else self.arch['out_channels'][index],\n out_channels=self.arch['out_channels'][index],\n which_conv=self.which_conv,\n wide=self.D_wide,\n activation=self.activation,\n preactivation=True,\n downsample=(nn.AvgPool2d(2) if self.arch['downsample'][index] and d_index==0 else None))\n for d_index in range(self.D_depth)]]\n # If attention on this block, attach it to the end\n if self.arch['attention'][self.arch['resolution'][index]]:\n print('Adding attention layer in D at resolution %d' % self.arch['resolution'][index])\n self.blocks[-1] += [layers.Attention(self.arch['out_channels'][index],\n self.which_conv)]\n # Turn self.blocks into a ModuleList so that it's all properly registered.\n self.blocks = nn.ModuleList([nn.ModuleList(block) for block in self.blocks])\n # Linear output layer. The output dimension is typically 1, but may be\n # larger if we're e.g. turning this into a VAE with an inference output\n self.linear = self.which_linear(self.arch['out_channels'][-1], output_dim)\n # Embedding for projection discrimination\n self.embed = self.which_embedding(self.n_classes, self.arch['out_channels'][-1])\n\n # Initialize weights\n if not skip_init:\n self.init_weights()\n\n # Set up optimizer\n self.lr, self.B1, self.B2, self.adam_eps = D_lr, D_B1, D_B2, adam_eps\n if D_mixed_precision:\n print('Using fp16 adam in D...')\n import utils\n self.optim = utils.Adam16(params=self.parameters(), lr=self.lr,\n betas=(self.B1, self.B2), weight_decay=0, eps=self.adam_eps)\n else:\n self.optim = optim.Adam(params=self.parameters(), lr=self.lr,\n betas=(self.B1, self.B2), weight_decay=0, eps=self.adam_eps)\n # LR scheduling, left here for forward compatibility\n # self.lr_sched = {'itr' : 0}# if self.progressive else {}\n # self.j = 0\n\n # Initialize\n def init_weights(self):\n self.param_count = 0\n for module in self.modules():\n if (isinstance(module, nn.Conv2d)\n or isinstance(module, nn.Linear)\n or isinstance(module, nn.Embedding)):\n if self.init == 'ortho':\n init.orthogonal_(module.weight)\n elif self.init == 'N02':\n init.normal_(module.weight, 0, 0.02)\n elif self.init in ['glorot', 'xavier']:\n init.xavier_uniform_(module.weight)\n else:\n print('Init style not recognized...')\n self.param_count += sum([p.data.nelement() for p in module.parameters()])\n print('Param count for D''s initialized parameters: %d' % self.param_count)\n\n def forward(self, x, y=None):\n # Run input conv\n h = self.input_conv(x)\n # Loop over blocks\n for index, blocklist in enumerate(self.blocks):\n for block in blocklist:\n h = block(h)\n # Apply global sum pooling as in SN-GAN\n h = torch.sum(self.activation(h), [2, 3])\n # Get initial class-unconditional output\n out = self.linear(h)\n # Get projection of final featureset onto class vectors and add to evidence\n out = out + torch.sum(self.embed(y) * h, 1, keepdim=True)\n return out\n\n# Parallelized G_D to minimize cross-gpu communication\n# Without this, Generator outputs would get all-gathered and then rebroadcast.\nclass G_D(nn.Module):\n def __init__(self, G, D):\n super(G_D, self).__init__()\n self.G = G\n self.D = D\n\n def forward(self, z, gy, x=None, dy=None, train_G=False, return_G_z=False,\n split_D=False):\n # If training G, enable grad tape\n with torch.set_grad_enabled(train_G):\n # Get Generator output given noise\n G_z = self.G(z, self.G.shared(gy))\n # Cast as necessary\n if self.G.fp16 and not self.D.fp16:\n G_z = G_z.float()\n if self.D.fp16 and not self.G.fp16:\n G_z = G_z.half()\n # Split_D means to run D once with real data and once with fake,\n # rather than concatenating along the batch dimension.\n if split_D:\n D_fake = self.D(G_z, gy)\n if x is not None:\n D_real = self.D(x, dy)\n return D_fake, D_real\n else:\n if return_G_z:\n return D_fake, G_z\n else:\n return D_fake\n # If real data is provided, concatenate it with the Generator's output\n # along the batch dimension for improved efficiency.\n else:\n D_input = torch.cat([G_z, x], 0) if x is not None else G_z\n D_class = torch.cat([gy, dy], 0) if dy is not None else gy\n # Get Discriminator output\n D_out = self.D(D_input, D_class)\n if x is not None:\n return torch.split(D_out, [G_z.shape[0], x.shape[0]]) # D_fake, D_real\n else:\n if return_G_z:\n return D_out, G_z\n else:\n return D_out\n"
]
[
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Runs a ResNet model on the Cifar-10 dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom absl import flags\nimport tensorflow as tf\nfrom official.benchmark.models import resnet_cifar_model\nfrom official.utils.flags import core as flags_core\nfrom official.utils.logs import logger\nfrom official.utils.misc import distribution_utils\nfrom official.utils.misc import keras_utils\nfrom official.vision.image_classification import cifar_preprocessing\nfrom official.vision.image_classification import common\n\n\nLR_SCHEDULE = [ # (multiplier, epoch to start) tuples\n (0.1, 91), (0.01, 136), (0.001, 182)\n]\n\n\ndef learning_rate_schedule(current_epoch,\n current_batch,\n batches_per_epoch,\n batch_size):\n \"\"\"Handles linear scaling rule and LR decay.\n\n Scale learning rate at epoch boundaries provided in LR_SCHEDULE by the\n provided scaling factor.\n\n Args:\n current_epoch: integer, current epoch indexed from 0.\n current_batch: integer, current batch in the current epoch, indexed from 0.\n batches_per_epoch: integer, number of steps in an epoch.\n batch_size: integer, total batch sized.\n\n Returns:\n Adjusted learning rate.\n \"\"\"\n del current_batch, batches_per_epoch # not used\n initial_learning_rate = common.BASE_LEARNING_RATE * batch_size / 128\n learning_rate = initial_learning_rate\n for mult, start_epoch in LR_SCHEDULE:\n if current_epoch >= start_epoch:\n learning_rate = initial_learning_rate * mult\n else:\n break\n return learning_rate\n\n\nclass LearningRateBatchScheduler(tf.keras.callbacks.Callback):\n \"\"\"Callback to update learning rate on every batch (not epoch boundaries).\n\n N.B. Only support Keras optimizers, not TF optimizers.\n\n Attributes:\n schedule: a function that takes an epoch index and a batch index as input\n (both integer, indexed from 0) and returns a new learning rate as\n output (float).\n \"\"\"\n\n def __init__(self, schedule, batch_size, steps_per_epoch):\n super(LearningRateBatchScheduler, self).__init__()\n self.schedule = schedule\n self.steps_per_epoch = steps_per_epoch\n self.batch_size = batch_size\n self.epochs = -1\n self.prev_lr = -1\n\n def on_epoch_begin(self, epoch, logs=None):\n if not hasattr(self.model.optimizer, 'learning_rate'):\n raise ValueError('Optimizer must have a \"learning_rate\" attribute.')\n self.epochs += 1\n\n def on_batch_begin(self, batch, logs=None):\n \"\"\"Executes before step begins.\"\"\"\n lr = self.schedule(self.epochs,\n batch,\n self.steps_per_epoch,\n self.batch_size)\n if not isinstance(lr, (float, np.float32, np.float64)):\n raise ValueError('The output of the \"schedule\" function should be float.')\n if lr != self.prev_lr:\n self.model.optimizer.learning_rate = lr # lr should be a float here\n self.prev_lr = lr\n tf.compat.v1.logging.debug(\n 'Epoch %05d Batch %05d: LearningRateBatchScheduler '\n 'change learning rate to %s.', self.epochs, batch, lr)\n\n\ndef run(flags_obj):\n \"\"\"Run ResNet Cifar-10 training and eval loop using native Keras APIs.\n\n Args:\n flags_obj: An object containing parsed flag values.\n\n Raises:\n ValueError: If fp16 is passed as it is not currently supported.\n\n Returns:\n Dictionary of training and eval stats.\n \"\"\"\n keras_utils.set_session_config(\n enable_eager=flags_obj.enable_eager,\n enable_xla=flags_obj.enable_xla)\n\n # Execute flag override logic for better model performance\n if flags_obj.tf_gpu_thread_mode:\n keras_utils.set_gpu_thread_mode_and_count(\n per_gpu_thread_count=flags_obj.per_gpu_thread_count,\n gpu_thread_mode=flags_obj.tf_gpu_thread_mode,\n num_gpus=flags_obj.num_gpus,\n datasets_num_private_threads=flags_obj.datasets_num_private_threads)\n common.set_cudnn_batchnorm_mode()\n\n dtype = flags_core.get_tf_dtype(flags_obj)\n if dtype == 'fp16':\n raise ValueError('dtype fp16 is not supported in Keras. Use the default '\n 'value(fp32).')\n\n data_format = flags_obj.data_format\n if data_format is None:\n data_format = ('channels_first'\n if tf.test.is_built_with_cuda() else 'channels_last')\n tf.keras.backend.set_image_data_format(data_format)\n\n strategy = distribution_utils.get_distribution_strategy(\n distribution_strategy=flags_obj.distribution_strategy,\n num_gpus=flags_obj.num_gpus,\n all_reduce_alg=flags_obj.all_reduce_alg,\n num_packs=flags_obj.num_packs)\n\n if strategy:\n # flags_obj.enable_get_next_as_optional controls whether enabling\n # get_next_as_optional behavior in DistributedIterator. If true, last\n # partial batch can be supported.\n strategy.extended.experimental_enable_get_next_as_optional = (\n flags_obj.enable_get_next_as_optional\n )\n\n strategy_scope = distribution_utils.get_strategy_scope(strategy)\n\n if flags_obj.use_synthetic_data:\n distribution_utils.set_up_synthetic_data()\n input_fn = common.get_synth_input_fn(\n height=cifar_preprocessing.HEIGHT,\n width=cifar_preprocessing.WIDTH,\n num_channels=cifar_preprocessing.NUM_CHANNELS,\n num_classes=cifar_preprocessing.NUM_CLASSES,\n dtype=flags_core.get_tf_dtype(flags_obj),\n drop_remainder=True)\n else:\n distribution_utils.undo_set_up_synthetic_data()\n input_fn = cifar_preprocessing.input_fn\n\n train_input_dataset = input_fn(\n is_training=True,\n data_dir=flags_obj.data_dir,\n batch_size=flags_obj.batch_size,\n num_epochs=flags_obj.train_epochs,\n parse_record_fn=cifar_preprocessing.parse_record,\n datasets_num_private_threads=flags_obj.datasets_num_private_threads,\n dtype=dtype,\n # Setting drop_remainder to avoid the partial batch logic in normalization\n # layer, which triggers tf.where and leads to extra memory copy of input\n # sizes between host and GPU.\n drop_remainder=(not flags_obj.enable_get_next_as_optional))\n\n eval_input_dataset = None\n if not flags_obj.skip_eval:\n eval_input_dataset = input_fn(\n is_training=False,\n data_dir=flags_obj.data_dir,\n batch_size=flags_obj.batch_size,\n num_epochs=flags_obj.train_epochs,\n parse_record_fn=cifar_preprocessing.parse_record)\n\n steps_per_epoch = (\n cifar_preprocessing.NUM_IMAGES['train'] // flags_obj.batch_size)\n lr_schedule = 0.1\n if flags_obj.use_tensor_lr:\n initial_learning_rate = common.BASE_LEARNING_RATE * flags_obj.batch_size / 128\n lr_schedule = tf.keras.optimizers.schedules.PiecewiseConstantDecay(\n boundaries=list(p[1] * steps_per_epoch for p in LR_SCHEDULE),\n values=[initial_learning_rate] +\n list(p[0] * initial_learning_rate for p in LR_SCHEDULE))\n\n with strategy_scope:\n optimizer = common.get_optimizer(lr_schedule)\n model = resnet_cifar_model.resnet56(classes=cifar_preprocessing.NUM_CLASSES)\n\n # TODO(b/138957587): Remove when force_v2_in_keras_compile is on longer\n # a valid arg for this model. Also remove as a valid flag.\n if flags_obj.force_v2_in_keras_compile is not None:\n model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=optimizer,\n metrics=(['sparse_categorical_accuracy']\n if flags_obj.report_accuracy_metrics else None),\n run_eagerly=flags_obj.run_eagerly,\n experimental_run_tf_function=flags_obj.force_v2_in_keras_compile)\n else:\n model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=optimizer,\n metrics=(['sparse_categorical_accuracy']\n if flags_obj.report_accuracy_metrics else None),\n run_eagerly=flags_obj.run_eagerly)\n\n train_epochs = flags_obj.train_epochs\n\n callbacks = common.get_callbacks(steps_per_epoch)\n\n if not flags_obj.use_tensor_lr:\n lr_callback = LearningRateBatchScheduler(\n schedule=learning_rate_schedule,\n batch_size=flags_obj.batch_size,\n steps_per_epoch=steps_per_epoch)\n callbacks.append(lr_callback)\n\n # if mutliple epochs, ignore the train_steps flag.\n if train_epochs <= 1 and flags_obj.train_steps:\n steps_per_epoch = min(flags_obj.train_steps, steps_per_epoch)\n train_epochs = 1\n\n num_eval_steps = (cifar_preprocessing.NUM_IMAGES['validation'] //\n flags_obj.batch_size)\n\n validation_data = eval_input_dataset\n if flags_obj.skip_eval:\n if flags_obj.set_learning_phase_to_train:\n # TODO(haoyuzhang): Understand slowdown of setting learning phase when\n # not using distribution strategy.\n tf.keras.backend.set_learning_phase(1)\n num_eval_steps = None\n validation_data = None\n\n if not strategy and flags_obj.explicit_gpu_placement:\n # TODO(b/135607227): Add device scope automatically in Keras training loop\n # when not using distribition strategy.\n no_dist_strat_device = tf.device('/device:GPU:0')\n no_dist_strat_device.__enter__()\n\n history = model.fit(train_input_dataset,\n epochs=train_epochs,\n steps_per_epoch=steps_per_epoch,\n callbacks=callbacks,\n validation_steps=num_eval_steps,\n validation_data=validation_data,\n validation_freq=flags_obj.epochs_between_evals,\n verbose=2)\n eval_output = None\n if not flags_obj.skip_eval:\n eval_output = model.evaluate(eval_input_dataset,\n steps=num_eval_steps,\n verbose=2)\n\n if not strategy and flags_obj.explicit_gpu_placement:\n no_dist_strat_device.__exit__()\n\n stats = common.build_stats(history, eval_output, callbacks)\n return stats\n\n\ndef define_cifar_flags():\n common.define_keras_flags(dynamic_loss_scale=False)\n\n flags_core.set_defaults(data_dir='/tmp/cifar10_data/cifar-10-batches-bin',\n model_dir='/tmp/cifar10_model',\n epochs_between_evals=10,\n batch_size=128)\n\n\ndef main(_):\n with logger.benchmark_context(flags.FLAGS):\n return run(flags.FLAGS)\n\n\nif __name__ == '__main__':\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n define_cifar_flags()\n absl_app.run(main)\n"
]