repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
p-morais/rl
|
[
"6a39d8cec58fdd471f2de80a9c7c9b2f1879f096"
] |
[
"rl/utils/experiment.py"
] |
[
"import atexit, os\nimport os.path as osp\nfrom subprocess import Popen\nfrom functools import partial\nimport torch.multiprocessing as mp\nfrom .render import renderloop\nfrom .logging import Logger\nfrom rl.envs import Normalize, Vectorize\n\n\ndef run_experiment(algo, policy, env_fn, args, log=True, monitor=False, render=False):\n logger = Logger(args, viz=monitor) if log else None\n\n # HOTFIX for Patrick's desktop: (MP is buggy on it for some reason)\n if render:\n policy.share_memory()\n\n train_p = mp.Process(target=algo.train,\n args=(env_fn, policy, args.n_itr),\n kwargs=dict(logger=logger))\n train_p.start()\n\n # TODO: add normalize as a commandline argument\n renv_fn = partial(env_fn)\n\n renv = Normalize(Vectorize([renv_fn]))\n render_p = mp.Process(target=renderloop,\n args=(renv, policy))\n render_p.start()\n\n train_p.join()\n render_p.join()\n \n else:\n algo.train(env_fn, policy, args.n_itr, logger=logger)\n"
] |
[
[
"torch.multiprocessing.Process"
]
] |
johannestreutlein/op-tie-breaking
|
[
"ef9dada6c14efa416ecb4f1fcf48a7e4b344ba27",
"ef9dada6c14efa416ecb4f1fcf48a7e4b344ba27"
] |
[
"src/op_with_tie_breaking.py",
"src/modules/critics/pair_coma.py"
] |
[
"import argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport datetime\nimport pandas as pd\n\nimport json\n\nimport os\n\nfrom utils.uniquify import uniquify\n\ndef op_tie_breaking_evaluation(hash_lists, args):\n '''This function evaluates our method, other-play with tie-breaking. It applies the tie-breaking function to different training runs to\n choose policies and\n then starts an experiment that calculates cross-play values for the chosen policies.\n\n It would probably be better to run this with sacred, as part of an experiment, instead\n of an extra python file, etc., but this suffices for now.\n '''\n\n chosen_indices_dict = {}\n n_seeds_total = args.n_seeds_per_run\n number_of_runs = len(hash_lists[args.hash_function_seeds[0]]) // args.n_seeds_per_run\n\n for hash_seed, hashs in hash_lists.items():\n print('\\n\\n=============================================')\n print('-----------seed of hash function: {}---------'.format(hash_seed))\n\n n_seeds = 1 #the case of one seed represents simply doing other-play\n\n chosen_indices_dict[hash_seed] = {}\n\n while n_seeds <= n_seeds_total:\n print('\\n\\n----------- seeds per run: {}--------'.format(n_seeds))\n print('-------------------------------------')\n\n chosen_indices = []\n\n for index in range(number_of_runs):\n print('\\n-------- run {} -------'.format(index))\n\n hash_list = np.array(hashs[index*n_seeds_total:index*n_seeds_total+n_seeds_total])\n hash_list = hash_list[:n_seeds]\n\n print('\\nhash_list:')\n print(hash_list)\n\n chosen_indices.append(op_with_tie_breaking(hash_list))\n\n print('\\nchosen indices:')\n print(chosen_indices)\n\n chosen_indices_dict[hash_seed][n_seeds] = chosen_indices\n n_seeds *= 2\n\n print('\\nDoing a new cross play evaluation with the chosen models, for each hash-function seed\\n\\n')\n\n #now, constructing new csv with model paths\n #very inefficient with a loop and creating copies, but it doesn't matter at the moment\n\n new_model_paths = pd.DataFrame()\n\n for n_seeds in range(int(np.floor(np.log2(n_seeds_total))) + 1):\n for hash_seed in args.hash_function_seeds:\n for runs, chosen_policy in enumerate(chosen_indices_dict[hash_seed][2 ** n_seeds]):\n new_model_paths = new_model_paths.append(args.model_paths.iloc[runs * n_seeds_total + chosen_policy], ignore_index=True)\n\n print('Prepared model paths:')\n print(new_model_paths)\n\n filename = os.path.join('results', 'op_with_tie_breaking', 'chosen_model_list_hash_run_{}.csv'.format(args.hash_run))\n\n filename = uniquify(filename)\n\n new_model_paths.to_csv(filename)\n\n os.system('python3 src/main.py --env-config={} --config=policy_gradient \\\n with seed={} \\\n evaluate=True \\\n cross_play=True \\\n calculate_hash=False \\\n test_nepisode={} \\\n n_seeds_per_run={} \\\n hash_function_seeds={} \\\n model_paths={}'.format(args.env, args.seed, args.test_nepisode, number_of_runs,\n str(args.hash_function_seeds).replace(' ', ''), filename))\n #here, each run corresponds to a chosen amount of seeds and each seed is a chosen policy from a different run\n\ndef op_with_tie_breaking(hashes):\n '''this implements other-play with tie-breaking.\n input is a list of tie-breaking values, output is index of policy with highest value.\n The actual values are calculated in the hash-run, by a method of the environment\n '''\n\n best_policy = hashes.argmax()\n\n print('\\nIndex chosen policy:')\n print(best_policy)\n\n return best_policy\n\ndef load_info(args):\n returns = None\n\n filename = os.path.join('results', 'sacred', args.hash_run, 'config.json')\n print('\\n\\nloading config from {}'.format(filename))\n with open(filename) as json_file:\n config = json.load(json_file)\n\n args.env = config[\"env\"]\n args.hash_function_seeds = config[\"hash_function_seeds\"]\n\n print(args.hash_function_seeds)\n\n filename = os.path.join('results', 'sacred', args.hash_run, 'info.json')\n print('\\n\\nloading hashs from ' + filename)\n\n hash_lists = {}\n\n with open(filename) as json_file:\n data = json.load(json_file)\n\n for seed in args.hash_function_seeds:\n hashs = data['trajectories_hash_{}'.format(seed)]\n print('\\n')\n print('hash values seed {}:'.format(seed))\n print(hashs)\n hash_lists[seed] = hashs\n\n args.model_paths = data['model_paths']\n\n args.model_paths = pd.DataFrame(args.model_paths)\n\n print('\\nModel paths:')\n print(args.model_paths)\n\n return hash_lists, args\n\n\nif __name__ == '__main__':\n print(datetime.datetime.now())\n # Define the parser\n parser = argparse.ArgumentParser(description='Short sample app')\n\n parser.add_argument('--hash_run', action=\"store\", dest='hash_run', default=None) #sacred directory of the run from hash calculation\n parser.add_argument('--test_nepisode', action=\"store\", dest='test_nepisode', default='2048') #number of episodes to use to calculate cross-play values\n parser.add_argument('--seed', action=\"store\", dest='seed', default='100') # seed for environment and policy randomness\n parser.add_argument('--n_seeds_per_run', action=\"store\", dest='n_seeds_per_run', default='32') # seed for environment and policy randomness\n\n\n # Now, parse the command line arguments and store the\n # values in the `args` variable\n args = parser.parse_args()\n args.test_nepisode = json.loads(args.test_nepisode)\n args.seed = json.loads(args.seed)\n args.n_seeds_per_run= json.loads(args.n_seeds_per_run)\n\n hash_lists, args = load_info(args)\n\n op_tie_breaking_evaluation(hash_lists, args)\n\n print('\\n\\n')\n\n\n",
"import torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass PairComaCritic(nn.Module):\n def __init__(self, scheme, args):\n super(PairComaCritic, self).__init__()\n\n self.args = args\n self.n_actions = args.n_actions\n self.n_agents = args.n_agents\n\n input_shape = self._get_input_shape(scheme)\n self.output_type = \"q\"\n\n # Set up network layers\n self.fc1 = nn.Linear(input_shape, 128)\n self.fc2 = nn.Linear(128, 128)\n self.fc3 = nn.Linear(128, self.n_actions)\n\n def forward(self, batch, t=None):\n inputs = self._build_inputs(batch, t=t)\n x = F.relu(self.fc1(inputs))\n x = F.relu(self.fc2(x))\n q = self.fc3(x)\n q_final = self.add_q_values(q, batch, t)\n return q_final, q_final\n\n def add_q_values(self, q, batch, t):\n bs = batch.batch_size\n max_t = batch.max_seq_length if t is None else 1\n ts = slice(None) if t is None else slice(t, t + 1)\n identity = th.eye(self.n_agents, device=batch.device).unsqueeze(0).unsqueeze(0).unsqueeze(4).expand(bs, max_t, -1, -1, self.n_actions)\n q = (1 - identity) * q\n\n actions = batch[\"actions\"][:, ts].unsqueeze(3).expand(-1, -1, -1, self.n_agents, -1)\n\n q_taken = th.gather(q, dim=4, index=actions).squeeze(4)\n\n q_taken_tot = q_taken.sum(3).sum(2).unsqueeze(2).unsqueeze(3).expand(-1, -1, self.n_agents, self.n_actions)\n\n q_part = q.sum(3)\n\n q_part_2 = q_taken.sum(3).unsqueeze(3).expand(-1, -1, -1, self.n_actions)\n\n q_part_3 = q_taken.sum(2).unsqueeze(3).expand(-1, -1, -1, self.n_actions)\n\n q_result = q_taken_tot - q_part_3 - q_part_2 + 2 * q_part\n\n return q_result\n\n def _build_inputs(self, batch, t=None):\n bs = batch.batch_size\n max_t = batch.max_seq_length if t is None else 1\n ts = slice(None) if t is None else slice(t, t + 1)\n inputs = []\n # state\n inputs.append(batch[\"state\"][:, ts].unsqueeze(2).unsqueeze(2).repeat(1, 1, self.n_agents, self.n_agents, 1))\n\n # observation\n inputs.append(batch[\"obs\"][:, ts].unsqueeze(3).repeat(1, 1, 1, self.n_agents, 1))\n\n #mask_for_pairs = th.zeros(self.n_agents, self.n_agents, device=batch.device)\n\n # for i in range(self.n_agents):\n # for j in range(self.n_agents):\n # if i <= j:\n # mask_for_pairs[i][j] = 1\n #\n # mask_for_pairs_actions = mask_for_pairs.unsqueeze(0).unsqueeze(0).unsqueeze(4).expand(bs, max_t, -1, -1,\n # self.n_actions)\n #\n # compl_mask_for_pairs_actions = th.ones(bs, max_t, self.n_agents, self.n_agents,\n # self.n_actions) - mask_for_pairs_actions\n\n # last actions\n if t == 0:\n last_actions = th.zeros_like(batch[\"actions_onehot\"][:, 0:1])\n elif isinstance(t, int):\n last_actions = batch[\"actions_onehot\"][:, slice(t - 1, t)]\n else:\n last_actions = th.cat([th.zeros_like(batch[\"actions_onehot\"][:, 0:1]), batch[\"actions_onehot\"][:, :-1]],\n dim=1)\n\n last_actions_1 = last_actions.unsqueeze(3).expand(-1, -1, -1, self.n_agents, -1)\n last_actions_2 = last_actions.unsqueeze(2).expand(-1, -1, self.n_agents, -1, -1)\n\n inputs.append(last_actions_1)\n inputs.append(last_actions_2)\n\n # complete_last_actions_1 = mask_for_pairs_actions * last_actions_1 + compl_mask_for_pairs_actions * last_actions_2\n # complete_last_actions_2 = mask_for_pairs_actions * last_actions_2 + compl_mask_for_pairs_actions * last_actions_1\n #\n # inputs.append(complete_last_actions_1)\n # inputs.append(complete_last_actions_2)\n\n # mask_for_pairs_agents = mask_for_pairs.unsqueeze(0).unsqueeze(0).unsqueeze(4).expand(bs, max_t, -1, -1,\n # self.n_agents)\n #\n # compl_mask_for_pairs_agents = 1 - mask_for_pairs_agents\n\n identity = th.eye(self.n_agents, device=batch.device).unsqueeze(0).unsqueeze(0).expand(bs, max_t, -1, -1)\n\n identity_1 = identity.unsqueeze(3).expand(-1, -1, -1, self.n_agents, -1)\n identity_2 = identity.unsqueeze(2).expand(-1, -1, self.n_agents, -1, -1)\n\n # complete_identity_1 = mask_for_pairs_agents * identity_1 + compl_mask_for_pairs_agents * identity_2\n # complete_identity_2 = mask_for_pairs_agents * identity_2 + compl_mask_for_pairs_agents * identity_1\n #\n # inputs.append(complete_identity_1)\n # inputs.append(complete_identity_2)\n\n inputs.append(identity_1)\n inputs.append(identity_2)\n\n current_actions = batch[\"actions_onehot\"][:, ts].unsqueeze(2).expand(-1, -1, self.n_agents, -1, -1)\n # blank_actions = th.zeros_like(current_actions)\n #\n # complete_curr_actions_1 = mask_for_pairs_actions * blank_actions + compl_mask_for_pairs_actions * current_actions\n # complete_curr_actions_2 = mask_for_pairs_actions * current_actions + compl_mask_for_pairs_actions * blank_actions\n #\n # inputs.append(complete_curr_actions_1)\n # inputs.append(complete_curr_actions_2)\n\n inputs.append(current_actions)\n\n inputs = th.cat([x.reshape(bs, max_t, self.n_agents, self.n_agents, -1) for x in inputs], dim=-1)\n\n return inputs\n\n def _get_input_shape(self, scheme):\n # state\n input_shape = scheme[\"state\"][\"vshape\"]\n # observation\n input_shape += scheme[\"obs\"][\"vshape\"]\n # actions and last actions\n input_shape += 3 * scheme[\"actions_onehot\"][\"vshape\"][0]\n # agent id\n input_shape += 2 * self.n_agents\n return input_shape"
] |
[
[
"numpy.log2",
"numpy.array",
"pandas.DataFrame"
],
[
"torch.gather",
"torch.nn.Linear",
"torch.eye",
"torch.zeros_like"
]
] |
giulio1979/dldt
|
[
"b2140c083a068a63591e8c2e9b5f6b240790519d"
] |
[
"model-optimizer/mo/graph/graph.py"
] |
[
"\"\"\"\n Copyright (C) 2018-2020 Intel Corporation\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 collections\nimport logging as log\nfrom typing import List\n\nfrom copy import deepcopy\n\nimport networkx as nx\nimport numpy as np\n\nfrom mo.graph.port import Port\nfrom mo.middle.passes.eliminate import mark_output_reachable_nodes, shape_inference, mark_undead_nodes, \\\n mark_const_producer_nodes, eliminate_dead_nodes, add_constant_operations\nfrom mo.utils.error import Error\nfrom mo.utils.utils import refer_to_faq_msg, deprecated_api, shrink_str_value\n\n\ndef dict_to_ordered_dict(d: dict, func=lambda t: t):\n return collections.OrderedDict(sorted(d.items(), key=lambda t: func(t[0])))\n\n\nclass Node:\n def __init__(self, graph, node: str):\n assert node in graph, \"Attempt to access node {} that not in graph\".format(node)\n\n super(Node, self).__setattr__('graph', graph)\n super(Node, self).__setattr__('node', node) # obsolete\n super(Node, self).__setattr__('id', node)\n\n def __str__(self, max_length: int = 100):\n node_dict = self.graph.node[self.id]\n print_dict = {k: v if k != 'value' else shrink_str_value(v, max_symbols=max_length) for k, v in\n node_dict.items()}\n return str(print_dict)\n\n def __setattr__(self, k, v):\n # you can assign only existing attributes\n attrs = self.graph.node[self.node]\n if not k in attrs:\n raise AttributeError(\"Attribute {} missing in {} node\".format(k, self.name))\n attrs[k] = v\n\n def __getattr__(self, k):\n return self.graph.node[self.node][k]\n\n def __getitem__(self, k):\n return self.graph.node[self.node][k]\n\n def __setitem__(self, k, v):\n self.graph.node[self.node][k] = v\n\n def __contains__(self, k):\n return self.has(k)\n\n def __eq__(self, other):\n return (\n self.__class__ == other.__class__ and\n self.graph == other.graph and\n self.id == other.id\n )\n\n def __hash__(self):\n return hash((self.graph, self.id))\n\n def __delitem__(self, k):\n del self.graph.node[self.node][k]\n\n def add_input_port(self, idx, skip_if_exist=False, **kwargs):\n if not self.has_valid('_in_ports'):\n Node(self.graph, self.id)['_in_ports'] = {}\n control_flow = kwargs['control_flow'] if kwargs.get('control_flow') is not None else False\n if skip_if_exist is False and idx in self.in_ports(control_flow=control_flow):\n raise Error(\"Input port with {} index already exists for {} node.\".format(idx, self.name))\n self._in_ports.update({idx: kwargs})\n\n def delete_input_ports(self, idx_set, skip_if_absent=False):\n if len(idx_set) == 0:\n return # there is nothing to delete\n for idx in idx_set:\n self.delete_input_port(idx, skip_if_absent)\n\n def delete_input_port(self, idx, skip_if_absent=False):\n if not self.has_valid('_in_ports'):\n raise Error(\n 'Cannot removed ports with indices {} from node {} because node doesn\\'t '\n 'have _in_ports attribute'.format(idx, self.soft_get('name')))\n # no handling of control flow edges -- TODO\n control_flow = False\n if not skip_if_absent and idx not in self.in_ports(control_flow=control_flow):\n raise Error(\"Input port with index {} does't exist in node {}.\".format(idx, self.soft_get('name')))\n if not self.in_port(idx).disconnected():\n self.in_port(idx).disconnect()\n del self._in_ports[idx]\n # update in_ports_count for consistency but it is unlikely have any effect somewhere in the code\n self.in_ports_count = len(self._in_ports)\n\n def add_output_port(self, idx, skip_if_exist=False, **kwargs):\n if not self.has_valid('_out_ports'):\n Node(self.graph, self.id)['_out_ports'] = {}\n control_flow = kwargs['control_flow'] if kwargs.get('control_flow') is not None else False\n if skip_if_exist is False and idx in self.out_ports(control_flow=control_flow):\n raise Error(\"Output port with {} index already exists for {} node.\".format(idx, self.name))\n self._out_ports.update({idx: kwargs})\n\n def add_sequence_of_ports(self, type: str, rng):\n assert type in ['in', 'out']\n for idx in rng:\n if type == 'in':\n self.add_input_port(idx, skip_if_exist=True)\n if type == 'out':\n self.add_output_port(idx, skip_if_exist=True)\n\n def in_port(self, idx=None, control_flow=False) -> Port:\n if not self.has_valid('_in_ports'):\n raise Error(\"Operation {} {} has no _in_ports attribute\", self.op, self.name)\n if idx not in self._in_ports:\n raise Error(\"Input port with index {} is not in node {}\".format(idx, self.name))\n if not control_flow and 'control_flow' in self._in_ports[idx] and self._in_ports[idx]['control_flow']:\n raise Error(\"Attempt to access control flow port when it's prohibited for node {}\".format(self.name))\n return Port(node=self, idx=idx, type='in', **self._in_ports[idx])\n\n def in_ports(self, control_flow=False):\n if not self.has_valid('_in_ports'):\n raise Error(\"Operation {} {} has no _in_ports attribute\", self.op, self.name)\n ports = {}\n for idx in self._in_ports:\n if control_flow or 'control_flow' not in self._in_ports[idx] or not self._in_ports[idx]['control_flow']:\n ports.update({idx: self.in_port(idx, control_flow=control_flow)})\n return dict_to_ordered_dict(ports, func=lambda t: str(t))\n\n def out_port(self, idx=None, control_flow=False) -> Port:\n if not self.has_valid('_out_ports'):\n raise Error(\"Operation {} {} has no _out_ports attribute\", self.op, self.name)\n if idx not in self._out_ports:\n raise Error(\"Output port with index {} is not in node {}\".format(idx, self.name))\n if not control_flow and 'control_flow' in self._out_ports[idx] and self._out_ports[idx]['control_flow']:\n raise Error(\"Attempt to access control flow port when it's prohibited for node {}\".format(self.name))\n return Port(node=self, idx=idx, type='out', **self._out_ports[idx])\n\n def out_ports(self, control_flow=False):\n if not self.has_valid('_out_ports'):\n raise Error(\"Operation {} {} has no _out_ports attribute\", self.op, self.name)\n ports = {}\n for idx in self._out_ports:\n if control_flow or 'control_flow' not in self._out_ports[idx] or not self._out_ports[idx]['control_flow']:\n ports.update({idx: self.out_port(idx, control_flow=control_flow)})\n return dict_to_ordered_dict(ports, func=lambda t: str(t))\n\n def has_port(self, port_type, idx, control_flow=False):\n assert port_type in ['in', 'out'], \"Invalid usage of has_port method\"\n\n if port_type == 'in':\n return self.has_valid('_in_ports') and idx in self.in_ports(control_flow=control_flow)\n else:\n return self.has_valid('_out_ports') and idx in self.out_ports(control_flow=control_flow)\n\n def is_in_port_connected(self, idx, control_flow=False):\n return self.has_port('in', idx, control_flow) and not self.in_port(idx, control_flow).disconnected()\n\n def is_out_port_connected(self, idx, control_flow=False):\n return self.has_port('out', idx, control_flow) and not self.out_port(idx, control_flow).disconnected()\n\n def attrs(self):\n return self.graph.node[self.node]\n\n def has(self, k):\n return k in self.graph.node[self.node]\n\n def has_valid(self, k):\n return self.has(k) and not self.graph.node[self.node][k] is None\n\n def has_and_set(self, k):\n return self.has_valid(k) and self[k]\n\n def in_nodes_edges(self, control_flow: bool = False):\n return dict_to_ordered_dict({x[1]['in']: (Node(self.graph, x[0]), x[1]) for x in\n self.get_inputs(control_flow=control_flow)})\n\n def in_nodes(self, control_flow: bool = False):\n assert self.has('kind') # TODO: remove as it always exists\n assert self.kind in ['op', 'data'] # TODO: remove as it always exists\n if self.kind == 'op':\n return dict_to_ordered_dict({x[1]['in']: Node(self.graph, x[0]) for x in\n self.get_inputs(control_flow=control_flow)})\n elif self.kind == 'data':\n return [Node(self.graph, n) for n, d in self.get_inputs(control_flow=control_flow)]\n\n def in_node(self, key=0, control_flow: bool = False):\n return self.in_nodes(control_flow=control_flow)[key]\n\n def in_edges(self, control_flow: bool = False):\n assert self.has('kind')\n assert self.kind in ['op', 'data']\n if self.kind == 'op':\n return dict_to_ordered_dict({x[1]['in']: x[1] for x in self.get_inputs(control_flow=control_flow)})\n elif self.kind == 'data':\n return [d for n, d in self.get_inputs(control_flow=control_flow)]\n\n def out_nodes_edges(self, control_flow: bool = False):\n return dict_to_ordered_dict({x[1]['out']: (Node(self.graph, x[0]), x[1]) for x in\n self.get_outputs(control_flow=control_flow)})\n\n def out_nodes(self, control_flow: bool = False):\n assert self.has('kind')\n assert self.kind in ['op', 'data']\n if self.kind == 'op':\n return dict_to_ordered_dict({x[1]['out']: Node(self.graph, x[0]) for x in\n self.get_outputs(control_flow=control_flow)})\n elif self.kind == 'data':\n return [Node(self.graph, n) for n, d in self.get_outputs(control_flow=control_flow)]\n\n def out_edges(self, control_flow: bool = False):\n assert self.has('kind')\n assert self.kind in ['op', 'data']\n if self.kind == 'op':\n return dict_to_ordered_dict({x[1]['out']: x[1] for x in self.get_outputs(control_flow=control_flow)})\n elif self.kind == 'data':\n return [d for n, d in self.get_outputs(control_flow=control_flow)]\n\n def out_node(self, key=0, control_flow: bool = False):\n return self.out_nodes(control_flow=control_flow)[key]\n\n def in_edge(self, key=0, control_flow: bool = False):\n return self.in_edges(control_flow=control_flow)[key]\n\n def out_edge(self, key=0, control_flow: bool = False):\n return self.out_edges(control_flow=control_flow)[key]\n\n def get_attrs(self):\n return self.graph.node[self.node]\n\n def get_inputs(self, edge_attr: dict = None, control_flow: bool = False):\n if edge_attr is None:\n edge_attr = {}\n in_edges = self.graph.in_edges(self.id, data=True)\n if not control_flow:\n in_edges = [(u, v, d) for u, v, d in in_edges if 'control_flow_edge' not in d or not d['control_flow_edge']]\n return [(u, d) for u, v, d in in_edges if all([attr in d and d[attr] == edge_attr[attr] for attr in edge_attr])]\n\n def get_outputs(self, edge_attr: dict = None, control_flow: bool = False):\n if edge_attr is None:\n edge_attr = {}\n out_edges = self.graph.out_edges(self.id, data=True)\n if not control_flow:\n out_edges = [(u, v, d) for u, v, d in out_edges if\n 'control_flow_edge' not in d or not d['control_flow_edge']]\n return [(v, d) for u, v, d in out_edges if\n all([attr in d and d[attr] == edge_attr[attr] for attr in edge_attr])]\n\n def get_sorted_inputs(self, control_flow: bool = False):\n return sorted([x for x in self.get_inputs(control_flow=control_flow) if 'in' in x[1]],\n key=lambda x: x[1]['in'])\n\n def get_sorted_outputs(self, control_flow: bool = False):\n return sorted([x for x in self.get_outputs(control_flow=control_flow) if 'out' in x[1]],\n key=lambda x: x[1]['out'])\n\n def soft_get(self, k, default='<UNKNOWN>'):\n return self[k] if self.has_valid(k) else default\n\n def edges(self, attrs: dict = None):\n \"\"\" Get a single edge with specified set of attributes.\n\n If none or multiple edges satisfies this criteria, exception is raised\n Edge is represented as tuple (u, v, d), where u is source node,\n v is destination node and d is edge attributes.\n \"\"\"\n edges = list(self.graph.in_edges([self.id], data=True)) + list(self.graph.out_edges([self.id], data=True))\n return [(u, v, d) for u, v, d in edges if dict_includes(d, attrs)]\n\n def edge(self, attrs: dict = None):\n \"\"\" Get a single edge with specified set of attributes.\n\n If none or multiple edges satisfies this criteria, exception is raised\n Edge is represented as tuple (u, v, d), where u is source node,\n v is destination node and d is edge attributes.\n \"\"\"\n edges = self.edges(attrs)\n assert len(edges) == 1, 'edges: {}, required attributes: {}'.format(edges, attrs)\n return edges[0]\n\n def copy_node(self, new_attrs: dict = None, dst_graph=None):\n ''' Copies node with all attributes (optionally updated) within the same graph or to different graph.'''\n if new_attrs is None:\n new_attrs = {}\n if dst_graph is None:\n dst_graph = self.graph\n\n attrs = deepcopy(self.attrs())\n new_id = dst_graph.unique_id(attrs['name']) if 'name' in attrs else dst_graph.unique_id()\n attrs['name'] = new_id\n attrs.update(new_attrs)\n dst_graph.add_node(new_id, **attrs)\n return Node(dst_graph, new_id)\n\n def insert_node_with_data_before(self, inp, new_op_class: callable, op_before_params: dict = None,\n infer_current: bool = False, additional_inputs: list = None):\n \"\"\"\n Inserts operation node with op_before_params and data node before current operation\n\n :param inp: input data node of current node\n :param new_op_class: class of operation that will be inserted before current operation node\n :param op_before_params: parameters to be added to operation that will be inserted before current operation\n\n Before calling:\n [...] -> inp -> Cur_Op -> Cur_Data -> [...]\n\n After calling:\n [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> [...]\n [op_before_params]\n \"\"\"\n graph = self.graph\n node = Node(graph, self.node)\n cls_name = new_op_class.op\n op_before_params = {} if op_before_params is None else op_before_params\n\n # operating with input\n new_op_before = new_op_class(graph, op_before_params)\n edge_attrs = deepcopy(graph.get_edge_data(inp.id, node.id)[0])\n graph.remove_edge(inp.id, node.id)\n # form a list of input nodes for a new op node combining new_out and additional_inputs\n inputs = [inp] + (additional_inputs if additional_inputs else [])\n new_inp = new_op_before.create_node_with_data(inputs, {'name': node.name + cls_name + '/Before'})\n graph.add_edge(new_inp.id, node.id, **edge_attrs)\n if infer_current:\n node.infer(node)\n\n def insert_node_with_data_after(self, out, new_op_class: callable, op_after_params: dict = None,\n additional_inputs: list = None):\n \"\"\"\n Inserts operation node with op_after_params and data node after current operation\n\n :param out: output data node of current node\n :param new_op_class: class of operation that will be inserted after current operation node\n :param op_after_params: parameters to be added to operation that will be inserted after current operation\n :param additional_inputs: other parameters for a new operation node in addition to one that is created\n at the 'out' placed; new nodes are added after 0-th input\n\n TODO Allow indexing for input parameters as well as for 'out' data node to explicitly\n specify ports that are connected to.\n\n Before calling:\n [...] -> Cur_Op -> Cur_Data -> [...]\n\n After calling:\n [...] -> Cur_Op -> Cur_Data -> New_Op_aft -> New_Data_aft(==out) -> [...]\n [op_after_params]\n \"\"\"\n # we import it here because Op imports Node and unique_id from this file\n from mo.ops.op import Op\n\n graph = self.graph\n node = Node(graph, self.node)\n cls_name = new_op_class.op\n op_after_params = {} if op_after_params is None else op_after_params\n\n new_op_after = new_op_class(graph, op_after_params)\n graph.remove_edge(node.id, out.id)\n new_out = Op.create_data_node(graph, node)\n node.infer(node)\n # form a list of input nodes for a new op node combining new_out and additional_inputs\n inputs = [new_out] + (additional_inputs if additional_inputs else [])\n new_op_after.create_node_with_data(inputs, {'name': node.name + cls_name + '/After'}, data_nodes=out)\n\n def bracket_with_different_nodes_with_data(self, inp, out, new_op_class_before: callable,\n new_op_class_after: callable,\n op_before_params: dict = None, op_after_params: dict = None):\n \"\"\"\n Inserts one operation node with op_before_params and data node before current operation node and\n inserts one operation node with op_after_params and data node after current operation node\n :param inp: input data node of self.node node\n :param out: output data node of self.node node\n :param new_op_class_before: class of operation that will be inserted before current operation node\n :param new_op_class_after: class of operation that will be inserted after current operation node\n :param op_before_params: parameters to be added to operation that will be inserted before current operation\n :param op_after_params: parameters to be added to operation that will be inserted after current operation\n\n Before calling:\n [...] -> inp -> Cur_Op -> out -> [...]\n\n After calling:\n [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> New_Op_aft -> New_Data_aft(==out) -> [...]\n [op_before_params] [op_after_params]\n \"\"\"\n op_before_params = {} if op_before_params is None else op_before_params\n op_after_params = {} if op_after_params is None else op_after_params\n self.insert_node_with_data_before(inp, new_op_class_before, op_before_params)\n self.insert_node_with_data_after(out, new_op_class_after, op_after_params)\n\n def bracket_op_with_another_op(self, inp, out, new_op_class: callable,\n op_before_params: dict = None, op_after_params: dict = None):\n \"\"\"\n Covers current operation with two similar another ones of class new_op_class:\n :param inp: input data node of self.node node\n :param out: output data node of self.node node\n :param new_op_class: class of operation with which current operation will be covered\n :param op_before_params: parameters to be added to operation that will be inserted before current operation\n :param op_after_params: parameters to be added to operation that will be inserted after current operation\n\n Before calling:\n [...] -> inp -> Cur_Op -> out -> [...]\n\n After calling:\n [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> New_Op_aft -> New_Data_aft(==out) -> [...]\n [op_before_params] [op_after_params]\n \"\"\"\n self.bracket_with_different_nodes_with_data(inp=inp, out=out,\n new_op_class_before=new_op_class, new_op_class_after=new_op_class,\n op_before_params=op_before_params, op_after_params=op_after_params)\n\n def insert_node_after(self, new_node, node_out_port: int = 0):\n \"\"\"\n Insert node 'new_node' after output with index 'node_out_port' of the node 'node'. All consumers of node 'node'\n output with index 'node_out_port' will be changed to consume node 'new_node'.\n The function should be used when graph doesn't contain data nodes yet.\n :param node: node after which new node should be inserted.\n :param new_node: node to be inserted.\n :param node_out_port: the output index for the node 'node' to insert\n :return: None\n \"\"\"\n assert self.graph is new_node.graph\n assert (len([name for name in self.graph.nodes() if Node(self.graph, name).soft_get('kind') == 'data']) == 0)\n\n graph = self.graph\n old_edges = list(graph.out_edges(self.id, data=True, keys=True))\n # create new edges first and then remove all old edges. This is needed for case when 'node' has several consumers\n # getting input from 'node_out_port'.\n # save tuple (\"name of the destination edge\", \"edge key\") to be removed\n node_name_and_edge_key = []\n for _, dst_name, edge_key, edge_attrs in old_edges:\n if edge_attrs['out'] == node_out_port:\n log.debug('Create edge from \"{}\" to \"{}\"'.format(new_node.name, dst_name))\n graph.create_edge(new_node, Node(graph, dst_name), 0, edge_attrs['in'])\n node_name_and_edge_key.append((dst_name, edge_key))\n for dst_name, edge_key in node_name_and_edge_key:\n log.debug('Remove edge from \"{}\" to \"{}\"'.format(self.id, dst_name))\n graph.remove_edge(self.id, dst_name, edge_key)\n graph.create_edge(self, new_node, node_out_port, 0, {})\n\n def insert_op_on_input_port(self, in_port_idx: int, new_op_class: callable, new_op_attrs: dict,\n value: np.ndarray = None):\n \"\"\"\n Inserts new operation of new_op_class on in_port_index input port with new_op_attrs\n Connects Const operation with value to 1 input port of new node if value was passed\n\n Returns new operation node\n \"\"\"\n graph = self.graph\n name = self.soft_get('name', self.id)\n\n op_node = new_op_class(graph, new_op_attrs).create_node()\n\n assert self.has_port('in', in_port_idx), \\\n 'Node `{}` should have input port with idx `{}` but it does not'.format(name, in_port_idx)\n\n in_port_source = self.in_port(in_port_idx).get_source()\n self.in_port(in_port_idx).get_connection().set_source(op_node.out_port(0))\n op_node.in_port(0).connect(in_port_source)\n\n if value is not None:\n from mo.ops.const import Const\n constant = Const(graph, {'value': value}).create_node()\n op_node.in_port(1).connect(constant.out_port(0))\n\n return op_node\n\n def replace_node(self, new_node, new_node_out_port: int = None):\n \"\"\"\n Replaces node 'old_node' with a node 'new_node' preserving edge attributes.\n :param old_node: node to be replaced.\n :param new_node: node to replace with.\n :return: None\n \"\"\"\n assert self.graph is new_node.graph\n assert self.id != new_node.id, \"New node and replaceable node are the same\"\n graph = self.graph\n # save output edges and reconnect them to new node\n for _, dst_node_name, edge_attrs in graph.out_edges(self.id, data=True):\n new_edge_attrs = deepcopy(edge_attrs)\n if new_node_out_port is not None:\n assert 'out' not in edge_attrs or edge_attrs['out'] == 0, \\\n 'replace_node function can replace old node with a single output port only if new_node_out_port is ' \\\n 'specified'\n new_edge_attrs.update({'out': new_node_out_port})\n graph.add_edge(new_node.id, dst_node_name, **new_edge_attrs)\n\n # if the node for replace is output node then we propagate this attribute to a new node\n if len(self.out_nodes()) == 1 and self.out_node().has('op') and self.out_node().op == 'Result':\n graph.remove_node(self.out_node().id)\n add_opoutput(graph, new_node.id, 0, False)\n graph.remove_node(self.id)\n\n def input_ports_with(self, node):\n \"\"\"\n Returns a list of integers that specify input ports that connected to a given node.\n :param node: node in the graph that is expected to appear at input port for self node\n :return: a list of integers with port indices that are connected to self node\n \"\"\"\n return [i for i in range(len(self.in_nodes())) if self.in_node(i).id == node.id]\n\n def update_node(self):\n \"\"\"\n Update internal node attributes. Currently it just add input/output ports.\n :return: None\n \"\"\"\n in_ports_count = self.in_ports_count if self.has_valid('in_ports_count') else None\n out_ports_count = self.out_ports_count if self.has_valid('out_ports_count') else None\n\n if not self.has_valid('_in_ports'):\n Node(self.graph, self.id)['_in_ports'] = dict()\n if not self.has_valid('_out_ports'):\n Node(self.graph, self.id)['_out_ports'] = dict()\n\n if in_ports_count is not None:\n for idx in range(in_ports_count):\n if idx not in self._in_ports:\n self.add_input_port(idx=idx)\n\n if out_ports_count is not None:\n for idx in range(out_ports_count):\n if idx not in self._out_ports:\n self.add_output_port(idx=idx)\n\n\nclass Graph(nx.MultiDiGraph):\n def __init__(self, data=None, **attr):\n self.stage = None\n self.strict_mode = True\n super().__init__(data, **attr)\n\n if not hasattr(self, 'node'):\n self.node = self.nodes\n\n unique_id_count = 0\n\n # SAFE API DESCRIPTION\n # all provided methods below are designed to be more safe and convenient\n # be careful while using other methods from nx.MultiDiGraph\n\n def add_node(self, node_for_adding, **attrs):\n # TODO: check required attrs for node\n super().add_node(node_for_adding, **attrs)\n node = Node(self, node_for_adding)\n node.update_node()\n\n def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):\n\n # TODO: turn on strict mode\n if self.strict_mode:\n unode = Node(self, u_for_edge)\n vnode = Node(self, v_for_edge)\n\n # Check that we connect Op->Op in front phase, and data->Op or Op->data in middle(back) phase\n # Also check that all necessary ports are exists\n message = \"Attempt to connect {} to {}.\".format(u_for_edge, v_for_edge)\n if self.stage == 'front':\n assert unode.kind == 'op' and vnode.kind == 'op', \"{} Wrong add_adge usage! You can connect only two operations in front phase\".format(message)\n assert 'in' in attr and 'out' in attr, \"Missing necessary attribute in or out when adding edge between {} and {}\".format(u_for_edge, v_for_edge)\n is_control_flow = 'control_flow_edge' in attr and attr['control_flow_edge'] is True\n in_port = 'control_flow_{}'.format(attr['in']) if is_control_flow else attr['in']\n out_port = 'control_flow_{}'.format(attr['out']) if is_control_flow else attr['out']\n assert unode.has_port('out', out_port, control_flow=is_control_flow), \"{} Missing out port ({}) in {} node\".format(message, out_port, unode.name)\n assert vnode.has_port('in', in_port, control_flow=is_control_flow), \"{} Missing in port ({}) in {} node\".format(message, in_port, vnode.name)\n elif self.stage in ['middle', 'back']:\n assert (unode.kind == 'data' and vnode.kind == 'op') or (unode.kind == 'op' and vnode.kind == 'data')\n if unode.kind == 'data' and vnode.kind == 'op':\n assert 'in' in attr, \"Attribute in is missing when adding edge to {}\".format(v_for_edge)\n assert vnode.has_port('in', attr['in']), \"{} Node {} has no in port ({})\".format(message, vnode.name, attr['in'])\n if unode.kind == 'op' and vnode.kind == 'data':\n assert 'out' in attr, \"Attribute out is missing when adding edge from {}\".format(u_for_edge)\n assert unode.has_port('out', attr['out']), \"{} Node {} has no out port ({})\".format(message, unode.name, attr['out'])\n\n return super().add_edge(u_for_edge, v_for_edge, key=key, **attr)\n\n def add_edges_from(self, ebunch_to_add, **attr):\n for e in ebunch_to_add:\n ne = len(e)\n if ne == 4:\n u, v, key, dd = e\n elif ne == 3:\n u, v, dd = e\n key = None\n elif ne == 2:\n u, v = e\n dd = {}\n key = None\n else:\n raise Error(\"Edge tuple %s must be a 2-tuple, 3-tuple or 4-tuple.\" % (e,))\n ddd = attr.copy()\n ddd.update(dd)\n self.add_edge(u, v, key=key, **ddd)\n\n def remove_edge(self, u, v, key=None):\n return super().remove_edge(u, v, key=key)\n\n def erase_node(self, node: Node):\n \"\"\"\n Erases node from the graph and reconnect edges from input node(s) to output node(s)\n Produces assertion error if the node being removed has multiple inputs or outputs.\n The function can be used in the front phase only (when there are no data nodes in the graph).\n :param node: Node to erase\n \"\"\"\n node_id = node.id\n\n inputs = list(self.in_edges(node_id, data=True))\n outputs = list(self.out_edges(node_id, data=True))\n\n assert node.kind == 'op' and (len(node.out_nodes()) == 0 or list(node.out_nodes().values())[0].kind != 'data'), \\\n \"The function must be used before the partial infer when graph doesn't contain data nodes.\"\n assert len(node.out_nodes()) <= 1, \"The node {} must produce just one output tensor\".format(\n node.soft_get('name'))\n assert len(inputs) <= 1, \"The node {} must have just one input\".format(node.soft_get('name'))\n\n if len(outputs) == 0 and len(inputs) != 0:\n from mo.front.extractor import add_output_ops\n input_ids = {input_node_id: {'port': {'out': [attrs['out']]}} for input_node_id, _, attrs in inputs}\n if node.has('op') and node.op == 'Result':\n add_output_ops(self, input_ids)\n\n if len(outputs) == 0 or len(inputs) == 0:\n self.remove_node(node_id)\n return\n\n input_node_id = inputs[0][0]\n for src, dst, attrs in outputs:\n self.remove_edge(src, dst)\n # update the 'out' attribute of the edge from the node being removed\n attrs['out'] = inputs[0][2]['out']\n self.add_edge(input_node_id, dst, **attrs)\n self.remove_node(node_id)\n\n def get_edge_data(self, u, v, key=None, default=None):\n return super().get_edge_data(u, v, key=key, default=default)\n\n def get_inputs_with_ports(self, match, pattern_edges, input_names_in_pattern):\n \"\"\"\n Front replacements of multi-input nodes should specify output port to add_node-like functions\n This function is a helper to get such information out of matched nodes\n :param graph: graph to operate on\n :param match: dictionary returned by matching function\n :param pattern_edges: edges that are specified in pattern\n :param input_names_in_pattern: names of matched nodes as they were specified in pattern that should be in\n resulting list\n :return: list of tuples of node and output port\n \"\"\"\n inputs = []\n for name in input_names_in_pattern:\n assert name in match, \"node named {} not in match {}\".format(name, match)\n src = match[name]\n dst = []\n for edge in pattern_edges:\n if edge[0] == name:\n assert edge[1] in match, \"name from pattern_edges {} not in match {}\".format(edge[1], match)\n dst.append(match[edge[1]])\n if len(dst) != 1:\n raise Error('Multiple output ports detected for node {} as {} in pattern'.format(match[name].id, name))\n dst = dst[0]\n out_port = self.get_edge_data(src.id, dst.id)[0]['out']\n inputs.append((src, out_port))\n return inputs\n\n def get_node_id_by_name(self, name: str):\n nodes = self.get_nodes_with_attributes(name=name)\n if len(nodes) == 0:\n raise Error('No node with name {}. ' + refer_to_faq_msg(51), name)\n elif len(nodes) > 1:\n raise Error('Multiple nodes with name {}'.format(name))\n else:\n return nodes[0]\n\n def get_op_nodes(self, **attrs):\n nodes = self.get_nodes_with_attributes(**dict(kind='op', **attrs))\n return [Node(self, node) for node in nodes]\n\n def get_data_nodes(self, has_value=None):\n \"\"\"\n Returns list of data nodes.\n If has_value = True, returns data nodes with value\n If has_value = False, returns data nodes without value\n \"\"\"\n data_nodes = [Node(self, node) for node in self.nodes() if Node(self, node).soft_get('kind') == 'data']\n return [node for node in data_nodes if has_value is None or node.has_valid('value') == has_value]\n\n def get_nodes_with_attributes(self, **attrs: dict):\n node_attrs = self.nodes(data=True)\n return [n for n, d in node_attrs if all(a in d.items() for a in attrs.items())]\n\n def unique_id(self, prefix: str = \"\"):\n \"\"\"\n Generates a unique node id for a new node in a given graph.\n The optional string prefix can be specified.\n \"\"\"\n # TODO thread safety?\n self.unique_id_count = max(self.unique_id_count, self.number_of_nodes()) + 1\n if prefix and not self.has_node(prefix):\n return str(prefix)\n while self.has_node(prefix + str(self.unique_id_count)):\n self.unique_id_count += 1\n return prefix + str(self.unique_id_count)\n\n def check_empty_graph(self, description: str):\n if len(self.nodes()) <= 1:\n raise Error(\n \"Graph contains {} node after executing {}. It considered as error because resulting IR will be \"\n \"empty which is not usual\".format(len(self.nodes()), description))\n\n def check_shapes_consistency(self):\n data_nodes = self.get_data_nodes()\n data_nodes_with_wrong_shapes = []\n for data_node in data_nodes:\n if not data_node.has('shape'):\n data_nodes_with_wrong_shapes.append((data_node.name, \"no shape attribute\"))\n continue\n if data_node.shape is not None and not isinstance(data_node.shape, np.ndarray):\n data_nodes_with_wrong_shapes.append((data_node.name, type(data_node.shape)))\n if len(data_nodes_with_wrong_shapes) > 0:\n raise Error(\"Graph contains data nodes ({}) with inconsistent shapes: {}\".format(\n len(data_nodes_with_wrong_shapes),\n data_nodes_with_wrong_shapes\n ))\n\n def check_nodes_ports_are_consecutive(self):\n # Check that all operation nodes has consecutive ports indexes\n op_nodes = self.get_op_nodes()\n for node in op_nodes:\n for idx in range(len(node.in_ports())):\n if idx not in node.in_ports():\n raise Error(\"Node {} has not consecutive in ports indexes: {}\".format(node.name,\n list(node.in_ports().keys())))\n for idx in range(len(node.out_ports())):\n if idx not in node.out_ports():\n raise Error(\"Node {} has not consecutive out ports indexes: {}\".format(node.name,\n list(\n node.out_ports().keys())))\n\n def dump_graph_for_graphviz(self, node_attrs: list = ['kind', 'op', 'shape', 'correct_data_layout', 'nchw_layout'],\n edge_attrs: list = ['in', 'out'], nodes_to_dump: list = None,\n save_to_svg=False, highlight_nodes: list = None):\n\n from extensions.ops.tensor_iterator import _get_internal_output_node_id, _get_internal_input_node_id\n\n fill_color = {'op': 'lightblue', 'data': 'whitesmoke', 'highlight': 'firebrick'}\n fill_color_by_type = {'Const': 'lightpink', 'Parameter': 'yellowgreen', 'TensorIterator': 'lemonchiffon'}\n style = {'op': 'filled,bold', 'data': 'filled,rounded'}\n\n subgraphs = {}\n if highlight_nodes is None:\n highlight_nodes = []\n\n def _subgraph_label(node_id, node_attrs: dict, attrs_to_print: list):\n subgraphs[node_id] = \"cluster_{}\".format(node_id)\n label = 'subgraph \"cluster_{}\" '.format(node_id) + '{\\n'\n label += 'label = \"{}\"; \\n'.format(node_id)\n label += 'color={}; \\nstyle=\"filled,rounded\";\\n'.format(fill_color_by_type[node_attrs['op']])\n\n subgraph_name = node_attrs['sub_graphs']\n assert len(subgraph_name) == 1\n body = node_attrs[subgraph_name[0]].dump_graph_for_graphviz()\n body = body.split('\\n')[2:-1]\n label += '\\n'.join(body)\n label += '\\n}\\n'\n return label\n\n def _node_label(node_id, node_attrs: dict, attrs_to_print: list):\n label = str(node_id) + '\\\\n' + '\\\\n'.join([str(key) + '=' + str(node_attrs.get(key, 'None'))\n for key in attrs_to_print if key in node_attrs])\n if node_attrs.get('type', '') == 'Const':\n if 'value' not in attrs_to_print and 'value' in node_attrs:\n if node_attrs['value'] is not None:\n label += '\\\\nvalue=\\\\\"' + ','.join([str(val) for val in node_attrs['value'].flatten()])[:40] + '\\\\\"'\n else:\n label += '\\\\nvalue=None'\n return label\n\n def _dump_nodes_attrs():\n string = ''\n for node_id in nodes_to_dump:\n attrs = self.node[node_id]\n color = fill_color_by_type.get(attrs.get('type', ''), fill_color[attrs['kind']])\n\n if node_id in highlight_nodes or 'highlight' in node_attrs and node_attrs['highlight']:\n color = fill_color['highlight']\n\n if attrs.get('op') == 'TensorIterator':\n string += _subgraph_label(node_id, attrs, node_attrs)\n else:\n string += '\"{}\" [fillcolor={} style=\"{}\" shape=box label=\"{}\"];\\n'.format(\n node_id, color, style[attrs['kind']], _node_label(node_id, attrs, node_attrs))\n return string\n\n def _dump_edges_attrs():\n string = ''\n for src_node_id, dst_node_id, attrs in self.edges(data=True):\n if src_node_id not in nodes_to_dump or dst_node_id not in nodes_to_dump:\n continue\n\n if src_node_id in subgraphs:\n edge_label = subgraphs[src_node_id]\n edge_label_name = 'ltail'\n src_node_id = _get_internal_output_node_id(self, src_node_id, attrs['external_port_id'])\n elif dst_node_id in subgraphs:\n edge_label = subgraphs[dst_node_id]\n edge_label_name = 'lhead'\n dst_node_id = _get_internal_input_node_id(self, dst_node_id, attrs['external_port_id'])\n else:\n edge_label = ' '.join(\n [str(key) + '=' + str(attrs.get(key, 'None')) for key in edge_attrs if key in attrs])\n edge_label_name = 'label'\n\n string += '\"{}\" -> \"{}\" [{} = \"{}\"];\\n'.format(src_node_id, dst_node_id, edge_label_name, edge_label)\n return string\n\n log.debug(\"---- GRAPHVIZ OUTPUT STARTS ----\")\n\n if nodes_to_dump is None:\n nodes_to_dump = self.nodes()\n\n string = '\\ndigraph {\\n'\n\n string += _dump_nodes_attrs()\n string += _dump_edges_attrs()\n\n string += '}'\n# log.debug(string)\n log.debug(\"---- GRAPHVIZ OUTPUT ENDS ----\")\n\n if save_to_svg:\n try:\n import graphviz\n import os\n file_name = \"{}_{}.txt\".format(self.name.replace('/', '_'), 0)\n id = 1\n while os.path.exists(file_name):\n file_name = \"{}_{}.txt\".format(self.name.replace('/', '_'), id)\n id += 1\n with open(file_name, \"w\") as f:\n f.write(string)\n graphviz.render('dot', 'svg', file_name)\n print('Graph was saved to {}.{}'.format(file_name, 'svg'))\n except ImportError:\n raise ImportError('Can\\'t import graphviz')\n except Exception as e:\n raise Error('Can\\'t save graph to svg') from e\n\n return string\n\n def print_graph_stat(self):\n log.debug('Number of nodes in graph: {}'.format(self.number_of_nodes()))\n log.debug('Number of edges in graph: {}'.format(len(list(self.edges()))))\n ops = collections.defaultdict(int)\n for _node in self.nodes():\n node = Node(self, _node)\n kind = node.kind if node.has('kind') else '<UNDEFINED>'\n if node.has('op'):\n ops['op/' + node.op] += 1\n else:\n ops[kind] += 1\n if node.has('shape') and np.any(node.shape == 0):\n log.error(\"Found bad shape: '{}' for node '{}'\".format(node.shape, node.node))\n for k, v in ops.items():\n log.debug(' {} : {}'.format(k, v))\n\n def create_sub_graph_copy(self, nodes_to_extract: list):\n \"\"\"\n Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The\n returned sub-graph is a deep copy of the provided graph nodes.\n :param graph: graph to create a sub-graph from.\n :param nodes_to_extract: list of node names to extract.\n :return: new graph.\n \"\"\"\n return self.subgraph(nodes_to_extract).copy()\n\n def create_edge(self, src_node: Node, dst_node: Node, out_port: int = 0, in_port: int = 0, edge_attrs: dict = None):\n \"\"\"\n Creates edge from node 'src_node' from output with index 'out_port' to node 'dst_node' with input index 'in_port'.\n :param src_node: node to create edge from.\n :param dst_node: node to create edge to.\n :param out_port: the index of output tensor of the 'src_node'.\n :param in_port: the input index of the node 'dst_node'.\n :param edge_attrs: dictionary with edge attrs.\n :return: None\n \"\"\"\n # edges must belong to the same graph\n assert src_node.graph is dst_node.graph\n graph = src_node.graph\n\n if edge_attrs is None:\n edge_attrs = dict()\n else:\n edge_attrs = edge_attrs.copy()\n edge_attrs.update(\n {'in': in_port, 'out': out_port, 'in_attrs': ['in', 'permutation'], 'out_attrs': ['out', 'permutation'],\n 'data_attrs': ['fw_tensor_debug_info']})\n\n # TODO: in case if in_port do not exists, we should raise an Exception here\n graph.add_edges_from([(src_node.id, dst_node.id, edge_attrs)])\n\n def dfs(self, node_name: str, visited: set):\n \"\"\"\n Implementation of the depth-first search algorithm starting from the specific node.\n :param graph: networkx graph to operate on.\n :param node_name: node name to start search from.\n :param visited: set of already visited nodes.\n :return: list of nodes in the DFS-visit order.\n \"\"\"\n order = []\n stack = [node_name]\n while len(stack) != 0:\n node_name = stack[0]\n stack.pop(0)\n visited.add(node_name)\n has_child = False\n for _, out_node_name in self.out_edges(node_name):\n if out_node_name not in visited:\n stack.insert(0, node_name)\n stack.insert(0, out_node_name)\n has_child = True\n break\n if not has_child:\n order.append(node_name)\n return order\n\n def pseudo_topological_sort(self, reverse: bool = False):\n \"\"\"\n The function performs topological sort but doesn't check for cycle existence. So it may produce wrong nodes order\n for some applications.\n :param graph: graph to pseudo-topologically sort.\n :param reverse: flag indicating whether need to reverse nodes order.\n :return: nodes in the topological sort if cycle doesn't exist and in pseudo-topological sort if not.\n \"\"\"\n nodes_without_inputs = list()\n for node_name in self.nodes():\n if len(self.in_edges(node_name)) == 0:\n nodes_without_inputs.append(node_name)\n order = list()\n visited = set()\n for node_name in nodes_without_inputs:\n if node_name not in visited:\n order.extend(self.dfs(node_name, visited))\n\n order = [Node(self, node) for node in order]\n\n if reverse:\n return order\n else:\n return list(reversed(order))\n\n def clean_up(self, undead_node_types: list = None):\n if undead_node_types is None:\n undead_node_types = []\n\n if 'fw' in self.graph and self.graph['fw'] == 'tf':\n undead_node_types.append('TFCustomSubgraphCall')\n\n if 'cmd_params' in self.graph and getattr(self.graph['cmd_params'], 'keep_shape_ops'):\n undead_node_types.extend(['ShapeOf', 'Shape'])\n\n mark_output_reachable_nodes(self)\n shape_inference(self)\n mark_undead_nodes(self, undead_node_types)\n mark_const_producer_nodes(self)\n eliminate_dead_nodes(self)\n # Add Const op for constant data nodes\n add_constant_operations(self)\n\n\ndef create_graph_with_nodes(src_nodes, get_id: callable, get_attrs: callable):\n \"\"\"\n Go over all nodes in src_nodes that should be enumerable and create new NX nodes\n using get_id and get_attrs functions to create node id and node attributes correspondingly.\n \"\"\"\n graph = Graph()\n for node in src_nodes:\n graph.add_node(get_id(node), **get_attrs(node))\n return graph\n\n\ndef dict_includes_compare_attrs(attr, attr_probe):\n if callable(attr_probe) and not isinstance(attr_probe, type):\n return attr_probe(attr)\n else:\n res = (attr == attr_probe)\n # check if the result of comparison is a numpy scalar value which occur when attr is python scalar and\n # attr_probe is a numpy scalar\n if hasattr(res, 'ndim') and res.ndim == 0:\n return res.item()\n return res if isinstance(res, bool) else all(res)\n\n\ndef dict_includes(big: dict, sub_dict: dict, skip_attr_names=[]):\n \"\"\" Searches attributes from sub_dict in big and ensures that all values match.\n\n Entries in sub_dict can be of two types: callable or not callable. If callable is specified\n it is treated as probing function for attribute value from big dictionary by callable(attr) expression.\n If it is not callable, the values are compared with == operator.\n \"\"\"\n return all(\n dict_includes_compare_attrs(big.get(attr, None), sub_dict[attr])\n for attr in sub_dict.keys() if attr not in skip_attr_names\n )\n\n\ndef add_opoutput(graph: Graph, node_name: str, port: int, cut: bool = True):\n \"\"\"\n Creates and connects Result node to node_name port. Cuts existing port if requested.\n :param graph: graph to operate with\n :param node_name: name of existing node in the graph that we want to add Result to\n :param port: output port of node to connect Result to\n :param cut: determines way of operating with edge specified by node_name and port\n \"\"\"\n # we import it here because Op imports add_attrs_props and update_ie_fields from this file\n from mo.ops.result import Result\n node = Node(graph, node_name)\n if cut and len(node.out_edges()) != 0:\n opoutput_node = Result(graph).create_node_on_port(node, port, {'name': node_name + '/sink_port_' + str(port)})\n else:\n opoutput_node = Result(graph).create_node([(node, port)], {'name': node_name + '/sink_port_' + str(port)})\n opoutput_node.in_edge()['data_attrs'] = ['fw_tensor_debug_info']\n opoutput_node.in_edge()['fw_tensor_debug_info'] = [(node_name, port)]\n log.debug('Sink: {} for node {}'.format(opoutput_node.id, node_name))\n log.debug(str(graph.node[opoutput_node.id]))\n log.debug(\"Add edge from {} to {}\".format(node_name, opoutput_node.id))\n return opoutput_node.id\n\n\n# TODO implement merging for keys with dictionary values?\ndef merge_edge_props(attrs: dict, additional_attrs: dict):\n \"\"\"\n Update edge attributes without changing 'in' and 'out' keys.\n It is necessary to copy edge attributes during merging of nodes when\n result of one subgraph call is passed as input to another subgraph call\n \"\"\"\n result = attrs\n for (key, value) in additional_attrs.items():\n if key not in ['in', 'out']:\n if type(additional_attrs[key]) is list:\n if key not in result:\n result[key] = []\n result[key].extend(additional_attrs[key])\n result[key] = list(set(result[key])) # silly solution to find unique elements\n else:\n result[key] = value\n return result\n\n\ndef rename_node(node: Node, name):\n if not node.graph.get_nodes_with_attributes(name=name):\n node.name = name\n else:\n assert 'Node with name {} already exists'.format(name)\n\n\ndef rename_nodes(nodes: List[tuple]):\n for node, name in nodes:\n rename_node(node, name)\n\n# All functions below are deprecated and will be removed in next release\n# Please, use methods from Graph/Node classes instead\n\n\n@deprecated_api(Graph)\ndef get_node_id_by_name(graph: Graph, name: str):\n return graph.get_node_id_by_name(name=name)\n\n\n@deprecated_api(Graph)\ndef print_graph_stat(graph: Graph):\n return graph.print_graph_stat()\n\n\n@deprecated_api(Graph)\ndef get_inputs_with_ports(graph: Graph, match, pattern_edges, input_names_in_pattern):\n \"\"\"\n Front replacements of multi-input nodes should specify output port to add_node-like functions\n This function is a helper to get such information out of matched nodes\n :param graph: graph to operate on\n :param match: dictionary returned by matching function\n :param pattern_edges: edges that are specified in pattern\n :param input_names_in_pattern: names of matched nodes as they were specified in pattern that should be in\n resulting list\n :return: list of tuples of node and output port\n \"\"\"\n return graph.get_inputs_with_ports(match=match,\n pattern_edges=pattern_edges,\n input_names_in_pattern=input_names_in_pattern)\n\n\n@deprecated_api(Graph)\ndef dump_graph_for_graphviz(graph: Graph, node_attrs: list = ['kind', 'op', 'shape'],\n edge_attrs: list = ['in', 'out'],\n nodes_to_dump: list = None, save_to_svg=False):\n return graph.dump_graph_for_graphviz(node_attrs=node_attrs,\n edge_attrs=edge_attrs,\n nodes_to_dump=nodes_to_dump,\n save_to_svg=save_to_svg)\n\n\n@deprecated_api(Graph)\ndef create_sub_graph_copy(graph: Graph, nodes_to_extract: list):\n \"\"\"\n Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The\n returned sub-graph is a deep copy of the provided graph nodes.\n :param graph: graph to create a sub-graph from.\n :param nodes_to_extract: list of node names to extract.\n :return: new graph.\n \"\"\"\n return graph.create_sub_graph_copy(nodes_to_extract=nodes_to_extract)\n\n\n@deprecated_api(Graph)\ndef get_graph_ops(graph: Graph):\n return graph.get_op_nodes()\n\n\n@deprecated_api(Graph)\ndef check_empty_graph(graph: Graph, description: str):\n return graph.check_empty_graph(description=description)\n\n\n@deprecated_api(Graph)\ndef create_edge(src_node: Node, dst_node: Node, out_port: int = 0, in_port: int = 0, edge_attrs: dict = None):\n \"\"\"\n Creates edge from node 'src_node' from output with index 'out_port' to node 'dst_node' with input index 'in_port'.\n :param src_node: node to create edge from.\n :param dst_node: node to create edge to.\n :param out_port: the index of output tensor of the 'src_node'.\n :param in_port: the input index of the node 'dst_node'.\n :param edge_attrs: dictionary with edge attrs.\n :return: None\n \"\"\"\n assert src_node.graph is dst_node.graph\n graph = src_node.graph\n return graph.create_edge(src_node=src_node, dst_node=dst_node, out_port=out_port, in_port=in_port,\n edge_attrs=edge_attrs)\n\n\n@deprecated_api(Graph)\ndef erase_node(node: Node):\n \"\"\"\n Erases node from the graph and reconnect edges from input node(s) to output node(s)\n Produces assertion error if the node being removed has multiple inputs or outputs.\n The function can be used in the front phase only (when there are no data nodes in the graph).\n :param node: Node to erase\n \"\"\"\n graph = node.graph\n return graph.erase_node(node)\n\n\n@deprecated_api(Node)\ndef get_sorted_inputs(node: Node, control_flow: bool = False):\n return node.get_sorted_inputs(control_flow=control_flow)\n\n\n@deprecated_api(Node)\ndef get_sorted_outputs(node: Node, control_flow: bool = False):\n return node.get_sorted_outputs(control_flow=control_flow)\n\n\n@deprecated_api(Node)\ndef insert_node_after(node: Node, new_node: Node, node_out_port: int = 0):\n \"\"\"\n Insert node 'new_node' after output with index 'node_out_port' of the node 'node'. All consumers of node 'node'\n output with index 'node_out_port' will be changed to consume node 'new_node'.\n The function should be used when graph doesn't contain data nodes yet.\n :param node: node after which new node should be inserted.\n :param new_node: node to be inserted.\n :param node_out_port: the output index for the node 'node' to insert\n :return: None\n \"\"\"\n return node.insert_node_after(new_node=new_node, node_out_port=node_out_port)\n\n\n@deprecated_api(Node)\ndef replace_node(old_node: Node, new_node: Node, new_node_out_port: int = None):\n \"\"\"\n Replaces node 'old_node' with a node 'new_node' preserving edge attributes.\n :param old_node: node to be replaced.\n :param new_node: node to replace with.\n :return: None\n \"\"\"\n return old_node.replace_node(new_node=new_node, new_node_out_port=new_node_out_port)\n\n\n@deprecated_api(Node)\ndef copy_node(src_node: Node, new_attrs: dict = None, dst_graph: nx.MultiDiGraph = None):\n \"\"\" Copies node with all attributes (optionally updated) within the same graph or to different graph.\"\"\"\n return src_node.copy_node(new_attrs=new_attrs, dst_graph=dst_graph)\n\n\n@deprecated_api(Node)\ndef get_inputs(graph: Graph, node: str, edge_attr: dict = None, control_flow: bool = False):\n return Node(graph, node).get_inputs(edge_attr=edge_attr, control_flow=control_flow)\n\n\n@deprecated_api(Node)\ndef get_outputs(graph: Graph, node: str, edge_attr: dict = None, control_flow: bool = False):\n return Node(graph, node).get_outputs(edge_attr=edge_attr, control_flow=control_flow)\n"
] |
[
[
"numpy.any"
]
] |
wangdingkang/DiscreteMorse
|
[
"3e1dcf215d96047f0e6754a34e45057bf1a19ff5"
] |
[
"Code/DIPHA/write_dipha_file_3d.py"
] |
[
"import sys\nfrom matplotlib import image as mpimg\nimport numpy as np\nimport os\n\nDIPHA_CONST = 8067171840\nDIPHA_IMAGE_TYPE_CONST = 1\nDIM = 3\n\ninput_dir = sys.argv[1]\ndipha_output_filename = sys.argv[2]\nvert_filename = sys.argv[3]\n\ninput_filenames = [name for name in os.listdir(input_dir) if (os.path.isfile(input_dir + '/' + name)) and (name != \".DS_Store\")]\ninput_filenames.sort()\n\n\nimage = mpimg.imread(input_dir + input_filenames[1])\nnx, ny = image.shape\ndel image\nnz = len(input_filenames)\n\nprint(nx, ny, nz)\n#sys.exit()\nim_cube = np.zeros([nx, ny, nz])\n\ni = 0\nfor name in input_filenames:\n sys.stdout.flush()\n print(i, name)\n fileName = input_dir + \"/\" + name\n im_cube[:, :, i] = mpimg.imread(fileName)\n i = i + 1\n\n\nprint('writing dipha output...')\nwith open(dipha_output_filename, 'wb') as output_file:\n # this is needed to verify you are giving dipha a dipha file\n np.int64(DIPHA_CONST).tofile(output_file)\n # this tells dipha that we are giving an image as input\n np.int64(DIPHA_IMAGE_TYPE_CONST).tofile(output_file)\n # number of points\n np.int64(nx * ny * nz).tofile(output_file)\n # dimension\n np.int64(DIM).tofile(output_file)\n # pixels in each dimension\n np.int64(nx).tofile(output_file)\n np.int64(ny).tofile(output_file)\n np.int64(nz).tofile(output_file)\n # pixel values\n for k in range(nz):\n sys.stdout.flush()\n print('dipha - working on image', k)\n for j in range(ny):\n for i in range(nx):\n val = int(-im_cube[i, j, k])\n # print('val check:', val)\n np.float64(val).tofile(output_file)\n output_file.close()\n\nprint('writing vert file')\nwith open(vert_filename, 'w') as vert_file:\n for k in range(nz):\n sys.stdout.flush()\n print('verts - working on image', k)\n for j in range(ny):\n for i in range(nx):\n vert_file.write(str(i) + ' ' + str(j) + ' ' + str(k) + ' ' + str(-im_cube[i, j, k]) + '\\n')\n vert_file.close()\n\nprint(nx, ny, nz)\n"
] |
[
[
"numpy.int64",
"matplotlib.image.imread",
"numpy.zeros",
"numpy.float64"
]
] |
PinchukKPI/RGS_parasol_model
|
[
"4c0848951658d8129a0ed71b2becdeab30bf70e5"
] |
[
"main.py"
] |
[
"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\nfrom scipy.io import loadmat\n\n\ndef load_white_noise_data(cell_id):\n data = loadmat('Data/elife-38841-fig4-data1-v2.mat') # loadmat is a function in scipy.io\n # data from Figure 4 can be downloaded from https://doi.org/10.7554/eLife.38841.013\n # \"Receptive field center-surround interactions mediate context-dependent spatial contrast encoding in the retina\"\n # Maxwell H Turner, Gregory W Schwartz, Fred Rieke DOI: https://doi.org/10.7554/eLife.38841\n\n # Stimuli and corresponding responses of On and Off parasol RGCs to center-surround\n # white noise stimulation have been concatenated into vector arrays.\n # Note that the data were collected in interleaved trials.\n # This data includes excitatory conductance responses (in nS) that were\n # estimated using measured excitatory current responses and an estimate\n # of the excitatory driving force for each cell. Data are sampled at\n # 10 Khz = 1e4 Hz so 8000 items with rate 1e4 Hz gives 0.8 sec\n # 1 [nS - nanoSiemens] is equal to 10e-9 [A/V - Amper/Volt]\n\n # CenterSurroundWhiteNoise is a cell array, each entry of which is a structure that corresponds\n # to a cell in the dataset. Structure fields:\n # .stimulus = concatenated stimulus traces for .center and .surround stimuli\n # .response = concatenated excitatory conductance response traces (in nS)\n # for .center, .surround and .centerSurround stimuli\n # Note that data are concatenated and grouped for convenience, but were acquired in interleaved trials\n\n center_surround_white_noise = data['CenterSurroundWhiteNoise'] # .item extracts a scalar value\n cell_data = center_surround_white_noise[0, cell_id]\n stimulus = cell_data[0, 0]['stimulus']\n response = cell_data[0, 0]['response']\n # Extract the stimulus intensity\n s_cntr = stimulus['center'][0][0][0]\n s_srnd = stimulus['surround'][0][0][0]\n r_cntr = response['center'][0][0][0]\n r_srnd = response['surround'][0][0][0]\n r_cntr_srnd = response['centerSurround'][0][0][0]\n\n return s_cntr, s_srnd, r_cntr, r_srnd, r_cntr_srnd\n\n\ndef load_natural_data(cell_id):\n data = loadmat('Data/elife-38841-fig7-data1-v2.mat') # data from Figure 7\n # downloaded from https://doi.org/10.7554/eLife.38841.017\n # The structure contains excitatory current responses (baseline subtracted, in pA) of On and Off parasol RGCs\n # to center-surround naturalistic luminance stimuli. Data are sampled at 10 Khz.\n # In the experiments in Figure 7, we updated the intensity of a disc (annulus) in the center (surround)\n # every 200 ms, which is consistent with typical human fixation periods during free-viewing,\n # although less than the mean period (for efficient data collection).\n # To compute natural intensity stimuli for the center and surround,\n # we selected many random patches from a natural image and measured the mean intensity\n # within a circle of diameter 200 μm (for the RF center) and within an annulus\n # with inner and outer diameters 200 and 600 μm, respectively (for the RF surround).\n\n center_surround_natural_image_liminance = data['CenterSurroundNaturalImageLuminance'] # .item extracts a scalar value\n cell_data = center_surround_natural_image_liminance[0, cell_id]\n stimulus = cell_data[0, 0]['stimulus']\n response = cell_data[0, 0]['response']\n s_cntr = stimulus['controlCenter'][0][0][0]\n s_srnd = stimulus['controlSurround'][0][0][0]\n s_srnd_shffl = stimulus['shuffleSurround'][0][0][0]\n\n r_cntr = response['controlCenter'][0][0][0] # only s_cntr\n r_srnd = response['controlSurround'][0][0][0] # only s_srnd\n r_cntr_srnd = response['controlCenterSurround'][0][0][0] # s_srnd + s_srnd\n\n r_cntr_shffl = response['shuffleCenter'][0][0][0] # only s_cntr\n r_srnd_shffl = response['shuffleSurround'][0][0][0] # only s_srnd_shffl\n r_cntr_srnd_shffl = response['shuffleCenterSurround'][0][0][0] # s_srnd + s_srnd_shffl\n\n return s_cntr, s_srnd, s_srnd_shffl, r_cntr, r_srnd, r_cntr_srnd, r_cntr_shffl, r_srnd_shffl, r_cntr_srnd_shffl\n\n\ndef filter_and_spikes_detect(response):\n # hi-pass filtering\n kernel = [-0.1, -0.1, -0.1, -0.1, -0.1, 1, -0.1, -0.1, -0.1, -0.1, -0.1 ] # sum should be 0\n kernel_size = 11\n response_size = response.size\n filtered = np.zeros(response_size)\n for i in range(response_size):\n kernel_sum = 0\n for filter_index in range(6, kernel_size-7):\n #if 0 < (i + filter_index - 6) < response_size:\n kernel_sum = kernel_sum + kernel[filter_index] * response[i + filter_index - 6]\n filtered[i] = kernel_sum\n\n # detect spikes\n threshold = 0.9\n spikes = np.zeros(response_size)\n for i in range(response_size - 1):\n if filtered[i] <= threshold < filtered[i + 1]:\n spikes[i] = 1\n\n return spikes\n\nif __name__ == '__main__':\n cell = 13 # 0-7 Off-center 8-14 On-center\n #stimulus_c, stimulus_s, stimulus_s_shffl, response_c, response_s, response_cs, \\\n #response_c_shffl, response_s_shffl, response_cs_shffl = load_natural_data(cell)\n\n stimulus_c, stimulus_s, response_c, response_s, response_cs = load_white_noise_data(cell)\n spikes_c = filter_and_spikes_detect(response_c)\n # spikes_s = filter_and_spikes_detect(response_s)\n # spikes_cs = filter_and_spikes_detect(response_cs)\n\n\n\n"
] |
[
[
"scipy.io.loadmat",
"numpy.zeros"
]
] |
RacleRay/Fine-grained_TextClassification
|
[
"ffd43b576ee766dfdfefa17946592a8506eae0de",
"ffd43b576ee766dfdfefa17946592a8506eae0de",
"ffd43b576ee766dfdfefa17946592a8506eae0de"
] |
[
"multi_class_base.py",
"Albert/models/multi_class_cnn.py",
"Albert/models/awd_lstm.py"
] |
[
"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : multi_class_base.py\n'''\n\n# multi-task learning implementation of Kim's paper : Convolutional Neural Networks for Sentence Classification.\n\nimport tensorflow as tf\nimport numpy as np\n\n\nclass TextCNN(object):\n \"\"\"\n A CNN for text classification.\n Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.\n \"\"\"\n\n def __init__(self, sequence_length, num_classes, multi_size, vocab_size,\n embedding_size, filter_sizes, num_filters, hidden_units, l2_reg_lambda):\n \"\"\"\n\n :multi_size -- 多任务数量\n :filter_sizes -- 相当于n gram sizes,list;\n :num_filters -- 每个n gram filter输出特征数量,决定输出长度, int;\n :hidden_units -- softmax前的全连接层大小;\n \"\"\"\n # Placeholders for input, output and dropout\n self.input_x = tf.placeholder(\n tf.int32, [None, sequence_length], name=\"input_x\")\n\n self.input_y = []\n for i in range(multi_size):\n self.input_y.append(tf.placeholder(\n tf.float32, [None, num_classes], name=\"input_y\"+str(i)))\n\n self.dropout_keep_prob = tf.placeholder(\n tf.float32, name=\"dropout_keep_prob\")\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = []\n for i in range(multi_size):\n l2_loss.append(tf.constant(0.0, name=\"l2_loss\"+str(i)))\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n self.W = tf.Variable(\n tf.constant(0.0, shape=[vocab_size, embedding_size]),\n trainable=False, name=\"W\")\n self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)\n self.embedded_chars_expanded = tf.expand_dims(\n self.embedded_chars, -1)\n\n # Create a convolution + maxpool layer for each filter size\n pooled_outputs = []\n for i, filter_size in enumerate(filter_sizes):\n with tf.name_scope(\"conv-maxpool-%s\" % filter_size):\n # Convolution Layer\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W = tf.Variable(tf.truncated_normal(\n filter_shape, stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(\n 0.1, shape=[num_filters]), name=\"b\")\n conv = tf.nn.conv2d(\n self.embedded_chars_expanded,\n W,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n # Apply nonlinearity\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n # Maxpooling over the outputs\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n # Combine all the pooled features\n num_filters_total = num_filters * len(filter_sizes)\n self.h_pool = tf.concat(3, pooled_outputs)\n self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])\n\n # Add dropout\n with tf.name_scope(\"dropout\"):\n self.h_drop = tf.nn.dropout(\n self.h_pool_flat, self.dropout_keep_prob)\n\n # Final (unnormalized) scores and predictions\n self.scores = []\n self.predictions = []\n self.loss = []\n self.accuracy = []\n\n for i in range(multi_size):\n with tf.name_scope(\"output\" + str(i)):\n W = tf.get_variable(\n \"W\"+str(i),\n shape=[num_filters_total, hidden_units],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(\n 0.1, shape=[hidden_units]), name=\"b\"+str(i))\n l2_loss[i] += tf.nn.l2_loss(W)\n l2_loss[i] += tf.nn.l2_loss(b)\n\n inference = tf.nn.softmax(tf.nn.bias_add(\n tf.matmul(self.h_drop, W), b), name=\"softmax\"+str(i))\n inference = tf.nn.dropout(inference, self.dropout_keep_prob)\n\n W2 = tf.get_variable(\n \"W2\"+str(i),\n shape=[hidden_units, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\n b2 = tf.Variable(tf.constant(\n 0.1, shape=[num_classes]), name=\"b2\"+str(i))\n l2_loss[i] += tf.nn.l2_loss(W2)\n l2_loss[i] += tf.nn.l2_loss(b2)\n\n self.scores.append(tf.nn.xw_plus_b(\n inference, W2, b2, name=\"scores\"+str(i)))\n self.predictions.append(tf.argmax(tf.nn.softmax(\n self.scores[i]), 1, name=\"predictions\"+str(i)))\n\n for i in range(multi_size):\n with tf.name_scope(\"loss\"+str(i)):\n losses = tf.nn.softmax_cross_entropy_with_logits(\n self.scores[i], self.input_y[i])\n self.loss.append(tf.reduce_mean(losses) +\n l2_reg_lambda * l2_loss[i])\n\n # Accuracy\n for i in range(multi_size):\n with tf.name_scope(\"accuracy\"+str(i)):\n correct_predictions = tf.equal(\n self.predictions[i], tf.argmax(self.input_y[i], 1))\n self.accuracy.append(tf.reduce_mean(\n tf.cast(correct_predictions, \"float\"), name=\"accuracy\"+str(i)))",
"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : multi_class_cnn.py\n@Author : Racle\n@Version : 1.0\n@Desc : None\n'''\n\nimport torch\nfrom torch import nn\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\nfrom transformers import (\n PreTrainedModel,\n BertModel,\n BertPreTrainedModel,\n AlbertModel,\n AlbertPreTrainedModel,\n XLNetModel,\n XLNetPreTrainedModel,\n DistilBertConfig,\n DistilBertModel,\n ElectraForMaskedLM,\n ElectraForPreTraining,\n RobertaConfig,\n RobertaModel,\n ElectraConfig,\n ElectraModel,\n ElectraPreTrainedModel,\n)\nfrom transformers.modeling_roberta import RobertaClassificationHead, ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP\nfrom transformers.modeling_distilbert import DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP\nfrom transformers.modeling_electra import ELECTRA_PRETRAINED_MODEL_ARCHIVE_MAP\nfrom transformers.modeling_utils import SequenceSummary\n\n\n\"\"\"\nBert类模型加上CNN,结合multi_label_linear.py,可以轻松定义任意Bert类模型。\n\"\"\"\n\nclass BertCNN(BertPreTrainedModel):\n \"\"\"bert + cnn, multi class classification.\"\"\"\n def __init__(self,\n config,\n extra_config,\n freez_pretrained=False,\n weight=None):\n \"weight: 各个label样本中正例的比例,len==num_labels\"\n super(BertCNN, self).__init__(config)\n self.num_labels = config.num_labels\n self.bert = BertModel(config)\n self.convs = nn.ModuleList([\n nn.Conv1d(config.hidden_size, extra_config.num_filters,\n kernel_size) for kernel_size in extra_config.kernel_sizes\n ])\n self.maxpooling = nn.AdaptiveMaxPool1d(1)\n self.avgpooling = nn.AdaptiveAvgPool1d(1)\n self.linear = nn.Linear(2 * extra_config.num_filters *\n len(extra_config.kernel_sizes), self.num_labels)\n\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, self.num_labels)\n self.weight = weight\n self.init_weights()\n if freez_pretrained:\n for param in self.albert.parameters():\n param.requires_grad = False\n\n def forward(self,\n input_ids,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n labels=None):\n # outputs的组成:\n # last_hidden_state: Sequence of hidden-states at the output of the last layer of the model.\n # (batch_size, sequence_length, hidden_size)\n # pooler_output: Last layer hidden-state of the first token of the sequence (classification token)\n # processed by a Linear layer and a Tanh activation function.\n # hidden_states: one for the output of the embeddings + one for the output of each layer.\n # each is (batch_size, sequence_length, hidden_size)\n # attentions: Attentions weights after the attention softmax of each layer.\n # each is (batch_size, num_heads, sequence_length, sequence_length)\n outputs = self.bert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n # cnn\n last_hidden_state = outputs[0]\n cnn_out = torch.cat([conv(last_hidden_state) for conv in self.convs], 1)\n maxpool_out = self.maxpooling(cnn_out)\n avgpool_out = self.avgpooling(cnn_out)\n out = torch.cat([maxpool_out, avgpool_out], 1)\n out = self.linear(out)\n\n # linear\n pooled_output = outputs[1]\n pooled_output = self.dropout(pooled_output)\n linear_out = self.classifier(pooled_output)\n\n # res\n logits = linear_out + out\n\n outputs = (logits, ) + outputs[2:]\n\n if labels is not None:\n loss_fct = CrossEntropyLoss(weight=self.weight)\n labels = labels.float()\n loss = loss_fct(logits.view(-1, self.num_labels),\n labels.view(-1, self.num_labels))\n outputs = (loss, ) + outputs\n\n # (loss), logits, (hidden_states), (attentions)\n return outputs\n\n\nclass AlbertCNN(BertPreTrainedModel):\n \"\"\"bert + cnn, multi class classification.\"\"\"\n def __init__(self,\n config,\n extra_config,\n freez_pretrained=False,\n weight=None):\n \"weight: 各个label样本中正例的比例,len==num_labels\"\n super(AlbertCNN, self).__init__(config)\n self.num_labels = config.num_labels\n self.bert = AlbertModel(config)\n self.convs = nn.ModuleList([\n nn.Conv1d(config.hidden_size, extra_config.num_filters,\n kernel_size) for kernel_size in extra_config.kernel_sizes\n ])\n self.maxpooling = nn.AdaptiveMaxPool1d(1)\n self.avgpooling = nn.AdaptiveAvgPool1d(1)\n self.linear = nn.Linear(2 * extra_config.num_filters *\n len(extra_config.kernel_sizes), self.num_labels)\n\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, self.num_labels)\n self.weight = weight\n self.init_weights()\n if freez_pretrained:\n for param in self.albert.parameters():\n param.requires_grad = False\n\n def forward(self,\n input_ids,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None):\n # outputs的组成:\n # last_hidden_state: Sequence of hidden-states at the output of the last layer of the model.\n # (batch_size, sequence_length, hidden_size)\n # pooler_output: Last layer hidden-state of the first token of the sequence (classification token)\n # processed by a Linear layer and a Tanh activation function.\n # hidden_states: one for the output of the embeddings + one for the output of each layer.\n # each is (batch_size, sequence_length, hidden_size)\n # attentions: Attentions weights after the attention softmax of each layer.\n # each is (batch_size, num_heads, sequence_length, sequence_length)\n outputs = self.albert(input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask)\n # cnn\n last_hidden_state = outputs[0]\n cnn_out = torch.cat([conv(last_hidden_state) for conv in self.convs], 1)\n maxpool_out = self.maxpooling(cnn_out)\n avgpool_out = self.avgpooling(cnn_out)\n out = torch.cat([maxpool_out, avgpool_out], 1)\n out = self.linear(out)\n\n # linear\n pooled_output = outputs[1]\n pooled_output = self.dropout(pooled_output)\n linear_out = self.classifier(pooled_output)\n\n # res\n logits = linear_out + out\n\n outputs = (logits, ) + outputs[2:]\n\n if labels is not None:\n loss_fct = CrossEntropyLoss(weight=self.weight)\n labels = labels.float()\n loss = loss_fct(logits.view(-1, self.num_labels),\n labels.view(-1, self.num_labels))\n outputs = (loss, ) + outputs\n\n # (loss), logits, (hidden_states), (attentions)\n return outputs\n",
"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : awd_lstm.py\n@Author : Racle\n@Version : 1.0\n@Desc : None\n'''\n\n# 说明\n\"\"\"\nThis'll need all different kinds of dropouts.\nDropout consists into replacing some coefficients by 0 with probability p.\nTo ensure that the average of the weights remains constant,\nwe apply a correction to the weights that aren't nullified of a factor 1/(1-p).\n\"\"\"\nimport torch\nimport torch.functional as F\nfrom torch import nn\nfrom torch import Tensor\n\n\ndef dropoutMask(x, size, prob):\n \"prob -- replaced by 0 with this probability\"\n return x.new(*size).bernoulli_(1 - prob).div_(1 - prob)\n\n\n# A tensor x will have three dimensions: bs, seq_len, vocab_size.\n# This consistently apply the dropout mask across the seq_len dimension\nclass RNNDropout(nn.Module):\n def __init__(self, prob=0.5):\n super().__init__()\n self.prob = prob\n\n def forward(self, x):\n if not self.training or self.prob == 0:\n return x\n mask = dropoutMask(x.data, (x.size(0), 1, x.size(2)), self.prob)\n return x * mask\n\n\nWEIGHT_HH = 'weight_hh_l0' # single layer situation\n\n\nclass WeightDropout(nn.Module):\n \"WeightDropout is dropout applied to the weights of the inner LSTM hidden to hidden matrix.\"\n\n def __init__(self, module, weight_prob=[0.], layer_names=[WEIGHT_HH]):\n super().__init__()\n self.module = module\n self.weight_prob = weight_prob\n self.layer_names = layer_names\n for layer in self.layer_names:\n # Makes a copy of the weights of the selected layers.\n w = getattr(self.module, layer)\n self.register_parameter(f'{layer}_raw', nn.Parameter(w.data))\n self.module._parameters[layer] = F.dropout(w,\n p=self.weight_prob,\n training=False)\n\n def _setWeights(self):\n \"\"\"if we want to preserve the CuDNN speed and not reimplement the cell from scratch.\n This add a parameter that will contain the raw weights,\n and we replace the weight matrix in the LSTM at the beginning of the forward pass.\"\"\"\n for layer in self.layer_names:\n raw_w = getattr(self, f'{layer}_raw')\n self.module._parameters[layer] = F.dropout(raw_w,\n p=self.weight_pro,\n training=self.training)\n\n def forward(self, *args):\n import warnings\n self._setWeights()\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n return self.module.forward(*args)\n\n\nclass EmbeddingDropout(nn.Module):\n \"EmbeddingDropout applies dropout to full rows of the embedding matrix.\"\n\n def __init__(self, embedding, embed_prob):\n super().__init__()\n self.embedding = embedding\n self.embed_prob = embed_prob\n self.pad_idx = self.embedding.padding_idx\n if self.pad_idx is None:\n self.pad_idx = -1\n\n def forward(self, words, scale=None):\n if self.training and self.embed_p != 0:\n size = (self.embedding.weight.size(0), 1)\n mask = dropoutMask(self.embedding.weight.data, size,\n self.embed_prob)\n maskedEmbedding = self.embedding.weight * mask\n else:\n maskedEmbedding = self.embedding.weight\n if scale:\n maskedEmbedding.mul_(scale)\n return F.embedding(words, maskedEmbedding, self.pad_idx,\n self.embedding.max_norm, self.embedding.normtype,\n self.embedding.scale_grad_by_freq,\n self.embedding.sparse)\n\n\ndef to_detach(h):\n return h.detach() if type(h) == torch.Tensor else tuple(\n to_detach(v) for v in h)\n\n\nclass AWDLSTM(nn.Module):\n \"AWD-LSTM: https://arxiv.org/abs/1708.02182.\"\n initRange = 0.1\n def __init__(self,\n embed_size,\n n_hid,\n n_layers,\n hidden_p=0.2,\n input_p=0.6,\n weight_p=0.5,\n bidirectional=True):\n super().__init__()\n self.batch_size = 1\n self.embed_size = embed_size\n self.n_hid = n_hid\n self.n_layers = n_layers\n\n # Bert的输出相当于已经做了embedding,此处没有加入embedding层\n # self.embedding = nn.Embedding(vocab_size,\n # embed_size,\n # padding_idx=pad_token)\n # self.embedding_dropout = EmbeddingDropout(self.embedding, embed_p)\n # self.embedding.weight.data.uniform_(-self.initRange, self.initRange)\n self.rnns = [\n nn.LSTM(embed_size if l == 0 else n_hid,\n (n_hid if l != n_layers - 1 else embed_size),\n 1,\n batch_first=True, bidirectional=True) for l in range(n_layers)\n ]\n self.rnns = nn.ModuleList(\n [WeightDropout(rnn, weight_p) for rnn in self.rnns])\n self.input_dropout = RNNDropout(input_p)\n self.hidden_dropout = nn.ModuleList(\n [RNNDropout(hidden_p) for l in range(n_layers)])\n\n def _init_hidden(self, l):\n \"Return one hidden state.\"\n nh = self.n_hid if l != self.n_layers - 1 else self.embed_size\n return next(self.parameters()).new(1, self.batch_size, nh).zero_()\n\n def reset(self):\n \"Reset the hidden states.\"\n self.hidden = [(self._init_hidden(l), self._init_hidden(l))\n for l in range(self.n_layers)]\n\n def forward(self, input):\n batch_size, seq_len = input.size()\n if batch_size != self.batch_size:\n self.batch_size = batch_size\n self.reset()\n raw_output = self.input_dropout(input)\n new_hidden, raw_outputs, outputs = [], [], []\n for l, (rnn, hidden_dropout) in enumerate(\n zip(self.rnns, self.hidden_dropout)):\n raw_output, new_h = rnn(raw_output, self.hidden[l])\n new_hidden.append(new_h)\n raw_outputs.append(raw_output)\n if l != self.n_layers - 1:\n raw_output = hidden_dropout(raw_output)\n outputs.append(raw_output)\n self.hidden = to_detach(new_hidden)\n return raw_outputs, outputs"
] |
[
[
"tensorflow.device",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.nn.conv2d",
"tensorflow.name_scope",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.argmax",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.placeholder",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.bias_add",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.expand_dims"
],
[
"torch.nn.Dropout",
"torch.nn.AdaptiveMaxPool1d",
"torch.nn.CrossEntropyLoss",
"torch.cat",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.nn.AdaptiveAvgPool1d"
],
[
"torch.functional.dropout",
"torch.nn.Parameter",
"torch.functional.embedding",
"torch.nn.LSTM"
]
] |
GeoDaCenter/accessibility
|
[
"731ca101ca3744740ea246fd9f57e29f893e8405"
] |
[
"access/tests/test_floating_catchment_area.py"
] |
[
"import sys\nsys.path.append('../..')\n\nimport math\nimport unittest\n\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nfrom access import access, weights\nimport util as tu\n\n\nclass TestFloatingCatchmentArea(unittest.TestCase):\n\n def setUp(self):\n n = 5\n supply_grid = tu.create_nxn_grid(n)\n demand_grid = supply_grid.sample(5)\n cost_matrix = tu.create_cost_matrix(supply_grid, 'euclidean')\n\n self.model = access(demand_df = demand_grid, demand_index = 'id',\n demand_value = 'value',\n supply_df = supply_grid, supply_index = 'id',\n supply_value = 'value',\n cost_df = cost_matrix, cost_origin = 'origin',\n cost_dest = 'dest', cost_name = 'cost',\n neighbor_cost_df = cost_matrix, neighbor_cost_origin = 'origin',\n neighbor_cost_dest = 'dest', neighbor_cost_name = 'cost')\n\n\n def test_floating_catchment_area_ratio_large_catchment(self):\n result = self.model.fca_ratio()\n actual = self.model.access_df.iloc[0]['fca_value']\n\n total_demand = self.model.access_df['value'].sum()\n total_supply = self.model.supply_df['value'].sum()\n expected = total_supply/total_demand\n\n self.assertEqual(actual, expected)\n\n\n def test_floating_catchment_area_ratio_small_catchment(self):\n small_catchment = .9\n result = self.model.fca_ratio(max_cost = small_catchment)\n actual = self.model.access_df.iloc[0]['fca_value']\n\n self.assertEqual(actual, 1)\n\n\n def test_floating_catchment_area_ratio_large_catchment_normalized(self):\n result = self.model.fca_ratio(normalize=True)\n actual = self.model.access_df.iloc[0]['fca_value']\n\n self.assertEqual(actual, 5)\n\n\n def test_floating_catchment_area_ratio_warns_if_demand_supply_locs_differ_and_noise(self):\n new_dem_row = pd.DataFrame([[1,1,1,None],[1,1,1,None]], columns=['x', 'y', 'value', 'geometry'], index=[28,29])\n self.model.demand_df = self.model.demand_df.append(new_dem_row)\n self.model.demand_df.index.name = 'id'\n result = self.model.fca_ratio(noise=True)\n\n def test_floating_catchment_area_ratio_overwrites_column(self):\n small_catchment = .9\n result = self.model.fca_ratio(max_cost = small_catchment)\n small_catchment = .8\n result = self.model.fca_ratio(max_cost = small_catchment)\n\n actual = self.model.access_df.iloc[0]['fca_value']\n\n self.assertEqual(actual, 1)\n\n\n def test_floating_catchment_area_ratio_zero_catchment(self):\n zero_catchment = 0\n result = self.model.fca_ratio(max_cost = zero_catchment)\n actual = math.isnan(self.model.access_df.iloc[0]['fca_value'])\n\n self.assertEqual(actual, True)\n\n\n def test_two_stage_floating_catchment_area_large_catchment(self):\n result = self.model.two_stage_fca()\n actual = self.model.access_df.iloc[0]['2sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_two_stage_floating_catchment_area_small_catchment(self):\n small_catchment = .9\n result = self.model.two_stage_fca(max_cost = small_catchment)\n actual = self.model.access_df.iloc[0]['2sfca_value']\n\n self.assertEqual(actual, 1)\n\n\n def test_two_stage_floating_catchment_area_zero_catchment(self):\n zero_catchment = 0\n result = self.model.two_stage_fca(max_cost = zero_catchment)\n actual = math.isnan(self.model.access_df.iloc[0]['2sfca_value'])\n\n self.assertEqual(actual, True)\n\n\n def test_two_stage_floating_catchment_area_warning_default_cost_if_more_than_one(self):\n\n cost_list = ['cost', 'other_cost']\n self.model.cost_names = cost_list\n\n self.model.two_stage_fca()\n actual = self.model.default_cost\n\n self.assertEqual(actual, 'cost')\n\n\n def test_two_stage_floating_catchment_area_unavailable_cost_name_raises_ValueError(self):\n with self.assertRaises(ValueError):\n bad_cost_name = 'euclidean'\n self.model.two_stage_fca(cost = bad_cost_name)\n\n\n def test_two_stage_floating_catchment_area_large_catchment_supply_value_explicit(self):\n result = self.model.two_stage_fca(supply_values = 'value')\n actual = self.model.access_df.iloc[0]['2sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_two_stage_floating_catchment_area_run_again_and_test_overwrite(self):\n result = self.model.two_stage_fca()\n result = self.model.two_stage_fca()\n actual = self.model.access_df.iloc[0]['2sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_two_stage_floating_catchment_area_large_catchment_normalize(self):\n result = self.model.two_stage_fca(normalize=True)\n\n actual = self.model.access_df.iloc[0]['2sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_three_stage_floating_catchment_area_large_catchment(self):\n wfn = weights.step_fn({10:25})\n result = self.model.three_stage_fca(weight_fn = wfn)\n actual = self.model.access_df.iloc[0]['3sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_three_stage_floating_catchment_area_large_catchment_run_again_and_test_overwrite(self):\n wfn = weights.step_fn({10:25})\n result = self.model.three_stage_fca(weight_fn = wfn)\n result = self.model.three_stage_fca(weight_fn = wfn)\n actual = self.model.access_df.iloc[0]['3sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_three_stage_floating_catchment_area_large_catchment_normalize(self):\n wfn = weights.step_fn({10:25})\n result = self.model.three_stage_fca(weight_fn = wfn, normalize = True)\n actual = self.model.access_df.iloc[0]['3sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_three_stage_floating_catchment_area_small_catchment(self):\n small_catchment = .9\n wfn = weights.step_fn({10:25})\n result = self.model.three_stage_fca(max_cost = small_catchment,\n weight_fn = wfn)\n actual = self.model.access_df.iloc[0]['3sfca_value']\n\n self.assertEqual(actual, 1)\n\n\n def test_three_stage_floating_catchment_area_zero_catchment(self):\n zero_catchment = 0\n result = self.model.three_stage_fca(max_cost = zero_catchment)\n actual = math.isnan(self.model.access_df.iloc[0]['3sfca_value'])\n\n self.assertEqual(actual, True)\n\n\n def test_enhanced_two_stage_floating_catchment_area_large_catchment(self):\n result = self.model.enhanced_two_stage_fca()\n actual = self.model.access_df.iloc[0]['e2sfca_value']\n\n self.assertEqual(actual, 25)\n\n\n def test_enhanced_two_stage_floating_catchment_area_small_catchment(self):\n small_catchment = .9\n result = self.model.enhanced_two_stage_fca(max_cost = small_catchment)\n actual = self.model.access_df.iloc[0]['e2sfca_value']\n\n self.assertEqual(actual, 1)\n\n\n def test_enhanced_two_stage_floating_catchment_area_zero_catchment(self):\n zero_catchment = 0\n result = self.model.enhanced_two_stage_fca(max_cost = zero_catchment)\n actual = math.isnan(self.model.access_df.iloc[0]['e2sfca_value'])\n\n self.assertEqual(actual, True)\n"
] |
[
[
"pandas.DataFrame"
]
] |
pome-ta/pystaMetalStudy
|
[
"530248ad8621ec951fcbaf450ebd26ac2752e540"
] |
[
"src/everythingAboutTheMetalAPI/chapter09/__main__.py"
] |
[
"import pathlib\nimport ctypes\nimport numpy as np\n\nfrom objc_util import c, create_objc_class, ObjCClass, ObjCInstance\nimport ui\n\n#import pdbg\n\n\n\nshader_path = pathlib.Path('./Shaders.metal')\n\n\n# --- load objc classes\nMTKView = ObjCClass('MTKView')\nMTLCompileOptions = ObjCClass('MTLCompileOptions')\nMTLRenderPipelineDescriptor = ObjCClass('MTLRenderPipelineDescriptor')\n\n# --- initialize MetalDevice\nMTLCreateSystemDefaultDevice = c.MTLCreateSystemDefaultDevice\nMTLCreateSystemDefaultDevice.argtypes = []\nMTLCreateSystemDefaultDevice.restype = ctypes.c_void_p\n\nmemcpy = c.memcpy\nmemcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t]\nmemcpy.restype = ctypes.c_void_p\n\nerr_ptr = ctypes.c_void_p()\n\nnd_type = np.float32\n# --- set Vertex\nvertex_array = [\n [[-1.0, -1.0, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]],\n [[ 1.0, -1.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0]],\n [[ 1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]],\n [[-1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]],\n [[-1.0, -1.0, -1.0, 1.0], [0.0, 0.0, 1.0, 1.0]],\n [[ 1.0, -1.0, -1.0, 1.0], [1.0, 1.0, 1.0, 1.0]],\n [[ 1.0, 1.0, -1.0, 1.0], [1.0, 0.0, 0.0, 1.0]],\n [[-1.0, 1.0, -1.0, 1.0], [0.0, 1.0, 0.0, 1.0]],\n]\nVertex = (((ctypes.c_float * 4) * 2) * 8)\nnp_vertex = np.array(vertex_array, dtype=nd_type)\n\n\nindex_array = [\n 0, 1, 2, 2, 3, 0, # front\n 1, 5, 6, 6, 2, 1, # right\n 3, 2, 6, 6, 7, 3, # top\n 4, 5, 1, 1, 0, 4, # bottom\n 4, 0, 3, 3, 7, 4, # left\n 7, 6, 5, 5, 4, 7, # back\n]\nIndex = (ctypes.c_uint16 * 36)\nnp_index = np.array(index_array, dtype=np.uint16)\n\n#MatrixFloat4x4 = ((ctypes.c_float * 4) *4)\nMatrixFloat4x4 = (ctypes.c_float *16)\n\n\nclass Uniforms(ctypes.Structure):\n _fields_ = [('modelViewProjectionMatrix', MatrixFloat4x4)]\n\n\n# --- Matrix func\ndef translationMatrix(position):\n _matrix4x4 = np.identity(4, dtype=nd_type)\n _matrix4x4[3] = [position[0], position[1], position[2], 1.0]\n \n return _matrix4x4\n\ndef scalingMatrix(scale):\n _matrix4x4 = np.identity(4, dtype=nd_type)\n _matrix4x4[0, 0] = scale\n _matrix4x4[1, 1] = scale\n _matrix4x4[2, 2] = scale\n _matrix4x4[3, 3] = 1.0\n \n return _matrix4x4\n \ndef rotationMatrix(angle, axis):\n X = np.zeros(4, dtype=nd_type)\n X[0] = axis[0] * axis[0] + (1.0 - axis[0] * axis[0]) * np.cos(angle)\n X[1] = axis[0] * axis[1] * (1.0 - np.cos(angle)) - axis[2] * np.sin(angle)\n X[2] = axis[0] * axis[2] * (1.0 - np.cos(angle)) + axis[1] * np.sin(angle)\n X[3] = 0.0\n \n Y = np.zeros(4, dtype=nd_type)\n Y[0] = axis[0] * axis[1] * (1.0 - np.cos(angle)) + axis[2] * np.sin(angle)\n Y[1] = axis[1] * axis[1] + (1.0 - axis[1] * axis[1]) * np.cos(angle)\n Y[2] = axis[1] * axis[2] * (1.0 - np.cos(angle)) - axis[0] * np.sin(angle)\n Y[3] = 0.0\n \n Z = np.zeros(4, dtype=nd_type)\n Z[0] = axis[0] * axis[2] * (1.0 - np.cos(angle)) - axis[1] * np.sin(angle)\n Z[1] = axis[1] * axis[2] * (1.0 - np.cos(angle)) + axis[0] * np.sin(angle)\n Z[2] = axis[2] * axis[2] + (1.0 - axis[2] * axis[2]) * np.cos(angle)\n Z[3] = 0.0\n \n W = np.zeros(4, dtype=nd_type)\n W[3] = 1.0\n \n _matrix4x4 = np.vstack((X, Y, Z, W))\n \n return _matrix4x4\n\n\ndef projectionMatrix(near, far, aspect, fovy):\n scaleY = 1.0 / np.tan(fovy * 0.5)\n scaleX = scaleY / aspect\n scaleZ = -(far + near) / (far - near)\n scaleW = -2.0 * far * near / (far - near)\n X = np.array([scaleX, 0.0, 0.0, 0.0], dtype=np.float32)\n Y = np.array([0.0, scaleY, 0.0, 0.0], dtype=np.float32)\n Z = np.array([0.0, 0.0, scaleZ, -1.0], dtype=np.float32)\n W = np.array([0.0, 0.0, scaleW, 0.0], dtype=np.float32)\n \n _matrix4x4 = np.vstack((X, Y, Z, W))\n \n return _matrix4x4\n \n\n\n\n# todo: 無駄にキャストするテスト\n__vertexData = np_vertex.ctypes.data_as(ctypes.POINTER(Vertex)).contents\n_vertexData = np.ctypeslib.as_array(__vertexData)\nvertexData = _vertexData.ctypes.data_as(ctypes.POINTER(Vertex)).contents\n\n\nindexData = np_index.ctypes.data_as(ctypes.POINTER(Index)).contents\n\n\n\nclass MetalView(ui.View):\n def __init__(self, *args, **kwargs):\n ui.View.__init__(self, *args, **kwargs)\n self.bg_color = 'maroon'\n self.view_did_load()\n\n def view_did_load(self):\n mtkView = MTKView.alloc()\n _device = MTLCreateSystemDefaultDevice()\n\n # todo: 端末サイズにて要調整\n _uw, _uh = ui.get_window_size()\n _w = min(_uw, _uh) * 0.96\n _x = (_uw - _w) / 2\n _y = _uh / 4\n\n #_frame = ((32.0, 32.0), (300.0, 300.0))\n #_frame = ((0.0, 0.0), (300.0, 300.0))\n _frame = ((_x, _y), (_w, _w))\n\n devices = ObjCInstance(_device)\n mtkView.initWithFrame_device_(_frame, devices)\n #mtkView.setAutoresizingMask_((1 << 1) | (1 << 4))\n renderer = self.renderer_init(PyRenderer, mtkView)\n mtkView.delegate = renderer\n mtkView.framebufferOnly = False\n self.objc_instance.addSubview_(mtkView)\n\n def renderer_init(self, delegate, _mtkView):\n renderer = delegate.alloc().init()\n\n # --- createBuffer\n renderer.device = _mtkView.device()\n renderer.commandQueue = renderer.device.newCommandQueue()\n\n # xxx: length\n # vertexData.count: 256\n renderer.vertexBuffer = renderer.device.newBufferWithBytes_length_options_(vertexData, np_vertex.nbytes, 0)\n print('vertexData.count: ', np_vertex.nbytes)\n \n # indexData.count: 72\n renderer.indexBuffer = renderer.device.newBufferWithBytes_length_options_(indexData, np_index.nbytes, 0)\n print('indexData.count: ', np_index.nbytes)\n \n \n # size: 64\n renderer.uniformBuffer = renderer.device.newBufferWithLength_options_(ctypes.sizeof(Uniforms), 0)\n print('Uniforms.size: ', ctypes.sizeof(Uniforms))\n renderer.bufferPointer = renderer.uniformBuffer.contents()\n \n renderer.rotation = 0.0\n \n\n # --- registerShaders\n source = shader_path.read_text('utf-8')\n library = renderer.device.newLibraryWithSource_options_error_(source, MTLCompileOptions.new(), err_ptr)\n\n vertex_func = library.newFunctionWithName_('vertex_func')\n frag_func = library.newFunctionWithName_('fragment_func')\n\n rpld = MTLRenderPipelineDescriptor.new()\n rpld.vertexFunction = vertex_func\n rpld.fragmentFunction = frag_func\n rpld.colorAttachments().objectAtIndexedSubscript(0).pixelFormat = 80 # .bgra8Unorm\n\n renderer.rps = renderer.device.newRenderPipelineStateWithDescriptor_error_(rpld, err_ptr)\n\n return renderer\n\n\n# --- MTKViewDelegate\ndef drawInMTKView_(_self, _cmd, _view):\n self = ObjCInstance(_self)\n view = ObjCInstance(_view)\n # --- update\n scaled = scalingMatrix(0.5)\n self.rotation += 1 / 100 * np.pi / 4.0\n rotatedY = rotationMatrix(self.rotation, [0.0, 1.0, 0.0])\n rotatedX = rotationMatrix(np.pi / 4.0, [1.0, 0.0, 0.0])\n modelMatrix = np.dot(np.dot(rotatedX, rotatedY), scaled)\n cameraPosition = [0.0, 0.0, -3.0]\n viewMatrix = translationMatrix(cameraPosition)\n projMatrix = projectionMatrix(0.0, 10.0, 1.0, 1.0)\n \n _modelViewProjectionMatrix = np.dot(projMatrix, np.dot(viewMatrix, modelMatrix))\n \n # todo: ここで、`ctypes` へキャスト\n modelViewProjectionMatrix = _modelViewProjectionMatrix.ctypes.data_as(ctypes.POINTER(MatrixFloat4x4)).contents\n \n \n self.bufferPointer = self.uniformBuffer.contents()\n uniforms = Uniforms(modelViewProjectionMatrix)\n # size: 64\n ctypes.memmove(self.bufferPointer, ctypes.byref(uniforms), ctypes.sizeof(uniforms))\n \n \n drawable = view.currentDrawable()\n rpd = view.currentRenderPassDescriptor()\n rpd.colorAttachments().objectAtIndexedSubscript(0).clearColor = (0.0, 0.5, 0.5, 1.0)\n\n commandBuffer = self.commandQueue.commandBuffer()\n commandEncoder = commandBuffer.renderCommandEncoderWithDescriptor_(rpd)\n commandEncoder.setRenderPipelineState_(self.rps)\n \n # MTLWinding\n # clockwise = 0\n # counterClockwise = 1\n # MTLCullMode\n # none = 0\n # front = 1\n # back = 2\n commandEncoder.setFrontFacingWinding_(1) # .counterClockwise\n commandEncoder.setCullMode_(2) # .back\n commandEncoder.setVertexBuffer_offset_atIndex_(self.vertexBuffer, 0, 0)\n commandEncoder.setVertexBuffer_offset_atIndex_(self.uniformBuffer, 0, 1)\n\n # indexCount: 36\n # --- indexBuffer.length: 72\n # --- MemoryLayout<UInt16>.size: 2\n commandEncoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_(3, (self.indexBuffer.length() // 2), 0, self.indexBuffer, 0)\n\n commandEncoder.endEncoding()\n commandBuffer.presentDrawable_(drawable)\n commandBuffer.commit()\n commandBuffer.waitUntilCompleted()\n\n\ndef mtkView_drawableSizeWillChange_(_self, _cmd, _view, _size):\n self = ObjCInstance(_self)\n view = ObjCInstance(_view)\n\n\nPyRenderer = create_objc_class(\n name='PyRenderer',\n methods=[drawInMTKView_, mtkView_drawableSizeWillChange_],\n protocols=['MTKViewDelegate'])\n\nif __name__ == '__main__':\n view = MetalView()\n view.present(style='fullscreen', orientations=['portrait'])\n"
] |
[
[
"numpy.dot",
"numpy.ctypeslib.as_array",
"numpy.cos",
"numpy.sin",
"numpy.tan",
"numpy.identity",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] |
AdvAiLab/smart_lab
|
[
"e99d2e0129e7dba3a8847bf215b2588128fc32b1"
] |
[
"webap_tools/webap_tools/captcha_prediction.py"
] |
[
"import os\nfrom time import sleep\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.backend import clear_session\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.python.keras.backend import set_session\n\n\ndef rgb2gray(rgb):\n r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n return gray\n\n\nclass NPTUCaptcha:\n def __init__(self):\n pass\n\n def load_NN(self):\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU\n # config.log_device_placement = True # to log device placement (on which device the operation ran)\n self.sess = tf.Session(config=config)\n set_session(self.sess) # set this TensorFlow session as the default session for Keras\n self.model = load_model(os.environ[\"HOME\"] + '/nptu/lab/smart_lab/webap_tools/webap_tools/nptu_captch.h5')\n self.graph = tf.get_default_graph()\n\n def unload_NN(self):\n self.sess.close()\n\n def get_ans(self, captcha_img):\n prediction_data = np.stack(np.array(captcha_img) / 255.0) # predict img local\n prediction_data = rgb2gray(prediction_data) # 灰階\n prediction_data = prediction_data.reshape(-1, 35, 95, 1)\n with self.graph.as_default():\n try:\n prediction = self.model.predict(prediction_data)\n except:\n clear_session()\n\n captcha_ans = \"\"\n\n for digit_onehot in prediction:\n digit_ans = digit_onehot.argmax()\n captcha_ans += str(digit_ans)\n\n return captcha_ans\n\n\ndef captcha_test():\n from ailab.webap_tools.webap_login import get_captcha\n for i in range(10): # predict 份數\n img = get_captcha()\n captcha_ans = get_ans(img)\n plt.figure(captcha_ans)\n plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), \"gray\")\n sleep(3)\n plt.show()\n\n\nif __name__ == '__main__':\n captcha_test()\n"
] |
[
[
"tensorflow.keras.models.load_model",
"tensorflow.ConfigProto",
"tensorflow.keras.backend.clear_session",
"tensorflow.python.keras.backend.set_session",
"tensorflow.Session",
"tensorflow.get_default_graph",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
sidgan/ETCI-2021-Competition-on-Flood-Detection
|
[
"dbb73bef7e26f0109870be13ef4d30c15ce15a33"
] |
[
"src/etci_dataset.py"
] |
[
"\"\"\"\nReferenced from:\nhttps://medium.com/cloud-to-street/jumpstart-your-machine-learning-satellite-competition-submission-2443b40d0a5a\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom torch.utils.data import Dataset\n\n\ndef s1_to_rgb(vv_image, vh_image):\n ratio_image = np.clip(np.nan_to_num(vh_image / vv_image, 0), 0, 1)\n rgb_image = np.stack((vv_image, vh_image, 1 - ratio_image), axis=2)\n return rgb_image\n\n\nclass ETCIDataset(Dataset):\n def __init__(self, dataframe, split, transform=None):\n self.split = split\n self.dataset = dataframe\n self.transform = transform\n\n def __len__(self):\n return self.dataset.shape[0]\n\n def __getitem__(self, index):\n example = {}\n\n df_row = self.dataset.iloc[index]\n\n # load vv and vh images\n vv_image = cv2.imread(df_row[\"vv_image_path\"], 0) / 255.0\n vh_image = cv2.imread(df_row[\"vh_image_path\"], 0) / 255.0\n\n # convert vv and vh images to rgb\n rgb_image = s1_to_rgb(vv_image, vh_image)\n\n if self.split == \"test\":\n # no flood mask should be available\n example[\"image\"] = rgb_image.transpose((2, 0, 1)).astype(\"float32\")\n else:\n # load ground truth flood mask\n flood_mask = cv2.imread(df_row[\"flood_label_path\"], 0) / 255.0\n\n # apply augmentations if specified\n if self.transform:\n augmented = self.transform(image=rgb_image, mask=flood_mask)\n rgb_image = augmented[\"image\"]\n flood_mask = augmented[\"mask\"]\n\n example[\"image\"] = rgb_image.transpose((2, 0, 1)).astype(\"float32\")\n example[\"mask\"] = flood_mask.astype(\"int64\")\n\n return example\n"
] |
[
[
"numpy.nan_to_num",
"numpy.stack"
]
] |
CrazyNicolas/PyTorch-1.x-Reinforcement-Learning-Cookbook
|
[
"1cca7e0218c2683a730b1c4a66681e68023657ef"
] |
[
"Chapter03/chapter3/off_policy_mc_control_weighted_importance_sampling.py"
] |
[
"'''\nSource codes for PyTorch 1.0 Reinforcement Learning (Packt Publishing)\nChapter 3: Monte Carlo Methods For Making Numerical Estimations\nAuthor: Yuxi (Hayden) Liu\n'''\n\nimport torch\nimport gym\n\nenv = gym.make('Blackjack-v0')\n\n\ndef gen_random_policy(n_action):\n probs = torch.ones(n_action) / n_action\n def policy_function(state):\n return probs\n return policy_function\n\n\ndef run_episode(env, behavior_policy):\n \"\"\"\n Run a episode given a behavior policy\n @param env: OpenAI Gym environment\n @param behavior_policy: behavior policy\n @return: resulting states, actions and rewards for the entire episode\n \"\"\"\n state = env.reset()\n rewards = []\n actions = []\n states = []\n is_done = False\n while not is_done:\n probs = behavior_policy(state)\n action = torch.multinomial(probs, 1).item()\n actions.append(action)\n states.append(state)\n state, reward, is_done, info = env.step(action)\n rewards.append(reward)\n if is_done:\n break\n return states, actions, rewards\n\n\n\nfrom collections import defaultdict\n\n\ndef mc_control_off_policy_weighted(env, gamma, n_episode, behavior_policy):\n \"\"\"\n Obtain the optimal policy with off-policy MC control method with weighted importance sampling\n @param env: OpenAI Gym environment\n @param gamma: discount factor\n @param n_episode: number of episodes\n @param behavior_policy: behavior policy\n @return: the optimal Q-function, and the optimal policy\n \"\"\"\n n_action = env.action_space.n\n N = defaultdict(float)\n Q = defaultdict(lambda: torch.empty(n_action))\n for episode in range(n_episode):\n W = 1.\n states_t, actions_t, rewards_t = run_episode(env, behavior_policy)\n return_t = 0.\n for state_t, action_t, reward_t in zip(states_t[::-1], actions_t[::-1], rewards_t[::-1]):\n return_t = gamma * return_t + reward_t\n N[(state_t, action_t)] += W\n Q[state_t][action_t] += (W / N[(state_t, action_t)]) * (return_t - Q[state_t][action_t])\n if action_t != torch.argmax(Q[state_t]).item():\n break\n W *= 1./ behavior_policy(state_t)[action_t]\n policy = {}\n for state, actions in Q.items():\n policy[state] = torch.argmax(actions).item()\n return Q, policy\n\ngamma = 1\n\nn_episode = 500000\n\nrandom_policy = gen_random_policy(env.action_space.n)\n\noptimal_Q, optimal_policy = mc_control_off_policy_weighted(env, gamma, n_episode, random_policy)\n\n\n\n\ndef simulate_episode(env, policy):\n state = env.reset()\n is_done = False\n while not is_done:\n action = policy[state]\n state, reward, is_done, info = env.step(action)\n if is_done:\n return reward\n\n\nn_episode = 100000\nn_win_optimal = 0\nn_lose_optimal = 0\n\nfor _ in range(n_episode):\n reward = simulate_episode(env, optimal_policy)\n if reward == 1:\n n_win_optimal += 1\n elif reward == -1:\n n_lose_optimal += 1\n\n\n\nprint('Winning probability under the optimal policy: {}'.format(n_win_optimal/n_episode))\n\nprint('Losing probability under the optimal policy: {}'.format(n_lose_optimal/n_episode))\n\n"
] |
[
[
"torch.ones",
"torch.empty",
"torch.multinomial",
"torch.argmax"
]
] |
flatironinstitute/inferelator-prior
|
[
"572a8016b14d922c74f482dcfc24a83dc7efcc83"
] |
[
"inferelator_prior/motifs/homer.py"
] |
[
"import subprocess\nimport io\nimport pandas as pd\nimport numpy as np\n\nfrom inferelator_prior.motifs import chunk_motifs, homer_motif, SCAN_SCORE_COL, SCORE_PER_BASE\nfrom inferelator_prior.motifs._motif import MotifScanner\nfrom inferelator_prior import HOMER_EXECUTABLE_PATH\n\nHOMER_DATA_SUFFIX = \".homer.tsv\"\n\nHOMER_SEQ_ID = 'seqid'\nHOMER_OFFSET = 'offset'\nHOMER_MATCH = 'match'\nHOMER_MOTIF = 'motif_id'\nHOMER_STRAND = 'strand'\nHOMER_SCORE = 'score'\nHOMER_CHROMOSOME = 'sequence_name'\nHOMER_START = 'start'\nHOMER_STOP = 'stop'\n\nHOMER2_FIND_COLS = [HOMER_SEQ_ID, HOMER_OFFSET, HOMER_MATCH, HOMER_MOTIF, HOMER_STRAND, HOMER_SCORE]\nHOMER2_EXPAND_STR_COLS = [HOMER_CHROMOSOME, HOMER_START, HOMER_STOP]\n\n\nclass HOMERScanner(MotifScanner):\n\n scanner_name = \"HOMER\"\n\n def _preprocess(self, min_ic=None):\n if self.motif_file is not None:\n self.motifs = homer_motif.read(self.motif_file)\n\n return chunk_motifs(homer_motif, self.motifs, num_workers=self.num_workers, min_ic=min_ic)\n\n def _postprocess(self, motif_peaks):\n motif_peaks = motif_peaks.drop_duplicates(subset=[HOMER_MOTIF, HOMER_START, HOMER_STOP, HOMER_CHROMOSOME,\n HOMER_STRAND])\n return motif_peaks\n\n def _get_motifs(self, fasta_file, motif_file, threshold=None, parse_genomic_coord=False):\n homer_command = [HOMER_EXECUTABLE_PATH, \"find\", \"-i\", fasta_file, \"-m\", motif_file, \"-offset\", str(0)]\n proc = subprocess.run(homer_command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n\n if int(proc.returncode) != 0:\n print(\"HOMER motif scan failed for {meme}, {fa} (cmd)\".format(meme=motif_file,\n fa=fasta_file,\n cmd=\" \".join(homer_command)))\n\n return self._parse_output(io.StringIO(proc.stdout.decode(\"utf-8\")))\n\n def _parse_output(self, output_handle):\n motifs = pd.read_csv(output_handle, sep=\"\\t\", index_col=None, names=HOMER2_FIND_COLS)\n\n loc_data = motifs[HOMER_SEQ_ID].str.split(r\"[\\:\\-]\", expand=True)\n loc_data.columns = HOMER2_EXPAND_STR_COLS if loc_data.shape[1] == 3 else HOMER2_EXPAND_STR_COLS + [\"UNKNOWN\"]\n loc_data[HOMER_START] = loc_data[HOMER_START].astype(int) + motifs[HOMER_OFFSET]\n\n match_width = motifs[HOMER_MATCH].str.len()\n\n loc_data.loc[motifs[HOMER_STRAND] == \"-\", HOMER_START] -= match_width.loc[motifs[HOMER_STRAND] == \"-\"] - 1\n\n loc_data[HOMER_STOP] = loc_data[HOMER_START] + motifs[HOMER_MATCH].str.len()\n\n motifs[[HOMER_CHROMOSOME, HOMER_START, HOMER_STOP]] = loc_data[[HOMER_CHROMOSOME, HOMER_START, HOMER_STOP]]\n motifs.drop([HOMER_SEQ_ID, HOMER_OFFSET], inplace=True, axis=1)\n\n motifs[SCAN_SCORE_COL] = [self.motifs[x].score_match(y) for x, y in\n zip(motifs[HOMER_MOTIF], motifs[HOMER_MATCH])]\n motifs[SCORE_PER_BASE] = [np.array(self.motifs[x]._info_match(y)) for x, y in\n zip(motifs[HOMER_MOTIF], motifs[HOMER_MATCH])]\n\n return motifs\n"
] |
[
[
"pandas.read_csv"
]
] |
danjia21/dcp
|
[
"437c6d10f447304277115f021b8888394ef41a31"
] |
[
"model.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport os\nimport sys\nimport glob\nimport h5py\nimport copy\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom .util import quat2mat\n\n\n# Part of the code is referred from: http://nlp.seas.harvard.edu/2018/04/03/attention.html#positional-encoding\n\ndef clones(module, N):\n return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])\n\n\ndef attention(query, key, value, mask=None, dropout=None):\n d_k = query.size(-1)\n scores = torch.matmul(query, key.transpose(-2, -1).contiguous()) / math.sqrt(d_k)\n if mask is not None:\n scores = scores.masked_fill(mask == 0, -1e9)\n p_attn = F.softmax(scores, dim=-1)\n return torch.matmul(p_attn, value), p_attn\n\n\ndef nearest_neighbor(src, dst):\n inner = -2 * torch.matmul(src.transpose(1, 0).contiguous(), dst) # src, dst (num_dims, num_points)\n distances = -torch.sum(src ** 2, dim=0, keepdim=True).transpose(1, 0).contiguous() - inner - torch.sum(dst ** 2,\n dim=0,\n keepdim=True)\n distances, indices = distances.topk(k=1, dim=-1)\n return distances, indices\n\n\ndef knn(x, k):\n inner = -2 * torch.matmul(x.transpose(2, 1).contiguous(), x)\n xx = torch.sum(x ** 2, dim=1, keepdim=True)\n pairwise_distance = -xx - inner - xx.transpose(2, 1).contiguous()\n\n idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k)\n return idx\n\n\ndef get_graph_feature(x, k=20):\n # x = x.squeeze()\n idx = knn(x, k=k) # (batch_size, num_points, k)\n batch_size, num_points, _ = idx.size()\n device = torch.device('cuda')\n\n idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points\n\n idx = idx + idx_base\n\n idx = idx.view(-1)\n\n _, num_dims, _ = x.size()\n\n x = x.transpose(2,\n 1).contiguous() # (batch_size, num_points, num_dims) -> (batch_size*num_points, num_dims) # batch_size * num_points * k + range(0, batch_size*num_points)\n feature = x.view(batch_size * num_points, -1)[idx, :]\n feature = feature.view(batch_size, num_points, k, num_dims)\n x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1)\n\n feature = torch.cat((feature, x), dim=3).permute(0, 3, 1, 2)\n\n return feature\n\n\nclass EncoderDecoder(nn.Module):\n \"\"\"\n A standard Encoder-Decoder architecture. Base for this and many\n other models.\n \"\"\"\n\n def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):\n super(EncoderDecoder, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n self.src_embed = src_embed\n self.tgt_embed = tgt_embed\n self.generator = generator\n\n def forward(self, src, tgt, src_mask, tgt_mask):\n \"Take in and process masked src and target sequences.\"\n return self.decode(self.encode(src, src_mask), src_mask,\n tgt, tgt_mask)\n\n def encode(self, src, src_mask):\n return self.encoder(self.src_embed(src), src_mask)\n\n def decode(self, memory, src_mask, tgt, tgt_mask):\n return self.generator(self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask))\n\n\nclass Generator(nn.Module):\n def __init__(self, emb_dims):\n super(Generator, self).__init__()\n self.nn = nn.Sequential(nn.Linear(emb_dims, emb_dims // 2),\n nn.BatchNorm1d(emb_dims // 2),\n nn.ReLU(),\n nn.Linear(emb_dims // 2, emb_dims // 4),\n nn.BatchNorm1d(emb_dims // 4),\n nn.ReLU(),\n nn.Linear(emb_dims // 4, emb_dims // 8),\n nn.BatchNorm1d(emb_dims // 8),\n nn.ReLU())\n self.proj_rot = nn.Linear(emb_dims // 8, 4)\n self.proj_trans = nn.Linear(emb_dims // 8, 3)\n\n def forward(self, x):\n x = self.nn(x.max(dim=1)[0])\n rotation = self.proj_rot(x)\n translation = self.proj_trans(x)\n rotation = rotation / torch.norm(rotation, p=2, dim=1, keepdim=True)\n return rotation, translation\n\n\nclass Encoder(nn.Module):\n def __init__(self, layer, N):\n super(Encoder, self).__init__()\n self.layers = clones(layer, N)\n self.norm = LayerNorm(layer.size)\n\n def forward(self, x, mask):\n for layer in self.layers:\n x = layer(x, mask)\n return self.norm(x)\n\n\nclass Decoder(nn.Module):\n \"Generic N layer decoder with masking.\"\n\n def __init__(self, layer, N):\n super(Decoder, self).__init__()\n self.layers = clones(layer, N)\n self.norm = LayerNorm(layer.size)\n\n def forward(self, x, memory, src_mask, tgt_mask):\n for layer in self.layers:\n x = layer(x, memory, src_mask, tgt_mask)\n return self.norm(x)\n\n\nclass LayerNorm(nn.Module):\n def __init__(self, features, eps=1e-6):\n super(LayerNorm, self).__init__()\n self.a_2 = nn.Parameter(torch.ones(features))\n self.b_2 = nn.Parameter(torch.zeros(features))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n return self.a_2 * (x - mean) / (std + self.eps) + self.b_2\n\n\nclass SublayerConnection(nn.Module):\n def __init__(self, size, dropout=None):\n super(SublayerConnection, self).__init__()\n self.norm = LayerNorm(size)\n\n def forward(self, x, sublayer):\n return x + sublayer(self.norm(x))\n\n\nclass EncoderLayer(nn.Module):\n def __init__(self, size, self_attn, feed_forward, dropout):\n super(EncoderLayer, self).__init__()\n self.self_attn = self_attn\n self.feed_forward = feed_forward\n self.sublayer = clones(SublayerConnection(size, dropout), 2)\n self.size = size\n\n def forward(self, x, mask):\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))\n return self.sublayer[1](x, self.feed_forward)\n\n\nclass DecoderLayer(nn.Module):\n \"Decoder is made of self-attn, src-attn, and feed forward (defined below)\"\n\n def __init__(self, size, self_attn, src_attn, feed_forward, dropout):\n super(DecoderLayer, self).__init__()\n self.size = size\n self.self_attn = self_attn\n self.src_attn = src_attn\n self.feed_forward = feed_forward\n self.sublayer = clones(SublayerConnection(size, dropout), 3)\n\n def forward(self, x, memory, src_mask, tgt_mask):\n \"Follow Figure 1 (right) for connections.\"\n m = memory\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))\n x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))\n return self.sublayer[2](x, self.feed_forward)\n\n\nclass MultiHeadedAttention(nn.Module):\n def __init__(self, h, d_model, dropout=0.1):\n \"Take in model size and number of heads.\"\n super(MultiHeadedAttention, self).__init__()\n assert d_model % h == 0\n # We assume d_v always equals d_k\n self.d_k = d_model // h\n self.h = h\n self.linears = clones(nn.Linear(d_model, d_model), 4)\n self.attn = None\n self.dropout = None\n\n def forward(self, query, key, value, mask=None):\n \"Implements Figure 2\"\n if mask is not None:\n # Same mask applied to all h heads.\n mask = mask.unsqueeze(1)\n nbatches = query.size(0)\n\n # 1) Do all the linear projections in batch from d_model => h x d_k\n query, key, value = \\\n [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2).contiguous()\n for l, x in zip(self.linears, (query, key, value))]\n\n # 2) Apply attention on all the projected vectors in batch.\n x, self.attn = attention(query, key, value, mask=mask,\n dropout=self.dropout)\n\n # 3) \"Concat\" using a view and apply a final linear.\n x = x.transpose(1, 2).contiguous() \\\n .view(nbatches, -1, self.h * self.d_k)\n return self.linears[-1](x)\n\n\nclass PositionwiseFeedForward(nn.Module):\n \"Implements FFN equation.\"\n\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionwiseFeedForward, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.norm = nn.Sequential() # nn.BatchNorm1d(d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = None\n\n def forward(self, x):\n return self.w_2(self.norm(F.relu(self.w_1(x)).transpose(2, 1).contiguous()).transpose(2, 1).contiguous())\n\n\nclass PointNet(nn.Module):\n def __init__(self, emb_dims=512):\n super(PointNet, self).__init__()\n self.conv1 = nn.Conv1d(3, 64, kernel_size=1, bias=False)\n self.conv2 = nn.Conv1d(64, 64, kernel_size=1, bias=False)\n self.conv3 = nn.Conv1d(64, 64, kernel_size=1, bias=False)\n self.conv4 = nn.Conv1d(64, 128, kernel_size=1, bias=False)\n self.conv5 = nn.Conv1d(128, emb_dims, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm1d(64)\n self.bn2 = nn.BatchNorm1d(64)\n self.bn3 = nn.BatchNorm1d(64)\n self.bn4 = nn.BatchNorm1d(128)\n self.bn5 = nn.BatchNorm1d(emb_dims)\n\n def forward(self, x):\n x = F.relu(self.bn1(self.conv1(x)))\n x = F.relu(self.bn2(self.conv2(x)))\n x = F.relu(self.bn3(self.conv3(x)))\n x = F.relu(self.bn4(self.conv4(x)))\n x = F.relu(self.bn5(self.conv5(x)))\n return x\n\n\nclass DGCNN(nn.Module):\n def __init__(self, emb_dims=512):\n super(DGCNN, self).__init__()\n self.conv1 = nn.Conv2d(6, 64, kernel_size=1, bias=False)\n self.conv2 = nn.Conv2d(64, 64, kernel_size=1, bias=False)\n self.conv3 = nn.Conv2d(64, 128, kernel_size=1, bias=False)\n self.conv4 = nn.Conv2d(128, 256, kernel_size=1, bias=False)\n self.conv5 = nn.Conv2d(512, emb_dims, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.bn2 = nn.BatchNorm2d(64)\n self.bn3 = nn.BatchNorm2d(128)\n self.bn4 = nn.BatchNorm2d(256)\n self.bn5 = nn.BatchNorm2d(emb_dims)\n\n def forward(self, x):\n batch_size, num_dims, num_points = x.size()\n x = get_graph_feature(x)\n x = F.relu(self.bn1(self.conv1(x)))\n x1 = x.max(dim=-1, keepdim=True)[0]\n\n x = F.relu(self.bn2(self.conv2(x)))\n x2 = x.max(dim=-1, keepdim=True)[0]\n\n x = F.relu(self.bn3(self.conv3(x)))\n x3 = x.max(dim=-1, keepdim=True)[0]\n\n x = F.relu(self.bn4(self.conv4(x)))\n x4 = x.max(dim=-1, keepdim=True)[0]\n\n x = torch.cat((x1, x2, x3, x4), dim=1)\n\n x = F.relu(self.bn5(self.conv5(x))).view(batch_size, -1, num_points)\n return x\n\n\nclass MLPHead(nn.Module):\n def __init__(self, args):\n super(MLPHead, self).__init__()\n emb_dims = args.emb_dims\n self.emb_dims = emb_dims\n self.nn = nn.Sequential(nn.Linear(emb_dims * 2, emb_dims // 2),\n nn.BatchNorm1d(emb_dims // 2),\n nn.ReLU(),\n nn.Linear(emb_dims // 2, emb_dims // 4),\n nn.BatchNorm1d(emb_dims // 4),\n nn.ReLU(),\n nn.Linear(emb_dims // 4, emb_dims // 8),\n nn.BatchNorm1d(emb_dims // 8),\n nn.ReLU())\n self.proj_rot = nn.Linear(emb_dims // 8, 4)\n self.proj_trans = nn.Linear(emb_dims // 8, 3)\n\n def forward(self, *input):\n src_embedding = input[0]\n tgt_embedding = input[1]\n embedding = torch.cat((src_embedding, tgt_embedding), dim=1)\n embedding = self.nn(embedding.max(dim=-1)[0])\n rotation = self.proj_rot(embedding)\n rotation = rotation / torch.norm(rotation, p=2, dim=1, keepdim=True)\n translation = self.proj_trans(embedding)\n return quat2mat(rotation), translation\n\n\nclass Identity(nn.Module):\n def __init__(self):\n super(Identity, self).__init__()\n\n def forward(self, *input):\n return input\n\n\nclass Transformer(nn.Module):\n def __init__(self, args):\n super(Transformer, self).__init__()\n self.emb_dims = args.emb_dims\n self.N = args.n_blocks\n self.dropout = args.dropout\n self.ff_dims = args.ff_dims\n self.n_heads = args.n_heads\n c = copy.deepcopy\n attn = MultiHeadedAttention(self.n_heads, self.emb_dims)\n ff = PositionwiseFeedForward(self.emb_dims, self.ff_dims, self.dropout)\n self.model = EncoderDecoder(Encoder(EncoderLayer(self.emb_dims, c(attn), c(ff), self.dropout), self.N),\n Decoder(DecoderLayer(self.emb_dims, c(attn), c(attn), c(ff), self.dropout), self.N),\n nn.Sequential(),\n nn.Sequential(),\n nn.Sequential())\n\n def forward(self, *input):\n src = input[0]\n tgt = input[1]\n src = src.transpose(2, 1).contiguous()\n tgt = tgt.transpose(2, 1).contiguous()\n tgt_embedding = self.model(src, tgt, None, None).transpose(2, 1).contiguous()\n src_embedding = self.model(tgt, src, None, None).transpose(2, 1).contiguous()\n return src_embedding, tgt_embedding\n\n\nclass SVDHead(nn.Module):\n def __init__(self, args):\n super(SVDHead, self).__init__()\n self.emb_dims = args.emb_dims\n # self.reflect = nn.Parameter(torch.eye(3), requires_grad=False)\n # self.reflect[2, 2] = -1\n # NOTE Changed to 2D\n self.reflect = nn.Parameter(torch.eye(2), requires_grad=False)\n self.reflect[1, 1] = -1\n\n def forward(self, *input):\n src_embedding = input[0]\n tgt_embedding = input[1]\n src = input[2]\n tgt = input[3]\n batch_size = src.size(0)\n\n d_k = src_embedding.size(1)\n scores = torch.matmul(src_embedding.transpose(2, 1).contiguous(), tgt_embedding) / math.sqrt(d_k)\n scores = torch.softmax(scores, dim=2)\n\n src_corr = torch.matmul(tgt, scores.transpose(2, 1).contiguous())\n\n src_centered = src - src.mean(dim=2, keepdim=True)\n\n src_corr_centered = src_corr - src_corr.mean(dim=2, keepdim=True)\n\n H = torch.matmul(src_centered, src_corr_centered.transpose(2, 1).contiguous())\n\n U, S, V = [], [], []\n R = []\n\n for i in range(src.size(0)):\n u, s, v = torch.svd(H[i])\n r = torch.matmul(v, u.transpose(1, 0).contiguous())\n r_det = torch.det(r)\n if r_det < 0:\n u, s, v = torch.svd(H[i])\n v = torch.matmul(v, self.reflect)\n r = torch.matmul(v, u.transpose(1, 0).contiguous())\n # r = r * self.reflect\n R.append(r)\n\n U.append(u)\n S.append(s)\n V.append(v)\n\n U = torch.stack(U, dim=0)\n V = torch.stack(V, dim=0)\n S = torch.stack(S, dim=0)\n R = torch.stack(R, dim=0)\n\n t = torch.matmul(-R, src.mean(dim=2, keepdim=True)) + src_corr.mean(dim=2, keepdim=True)\n # return R, t.view(batch_size, 3)\n # NOTE changed to 2D, return additionally scores\n return R, t.view(batch_size, 2), scores\n\n\nclass DCP(nn.Module):\n def __init__(self, args):\n super(DCP, self).__init__()\n self.emb_dims = args.emb_dims\n self.cycle = args.cycle\n if args.emb_nn == 'pointnet':\n self.emb_nn = PointNet(emb_dims=self.emb_dims)\n elif args.emb_nn == 'dgcnn':\n self.emb_nn = DGCNN(emb_dims=self.emb_dims)\n else:\n raise Exception('Not implemented')\n\n if args.pointer == 'identity':\n self.pointer = Identity()\n elif args.pointer == 'transformer':\n self.pointer = Transformer(args=args)\n else:\n raise Exception(\"Not implemented\")\n\n if args.head == 'mlp':\n self.head = MLPHead(args=args)\n elif args.head == 'svd':\n self.head = SVDHead(args=args)\n else:\n raise Exception('Not implemented')\n\n def forward(self, *input):\n src = input[0]\n tgt = input[1]\n src_embedding = self.emb_nn(src)\n tgt_embedding = self.emb_nn(tgt)\n\n src_embedding_p, tgt_embedding_p = self.pointer(src_embedding, tgt_embedding)\n\n src_embedding = src_embedding + src_embedding_p\n tgt_embedding = tgt_embedding + tgt_embedding_p\n\n rotation_ab, translation_ab = self.head(src_embedding, tgt_embedding, src, tgt)\n if self.cycle:\n rotation_ba, translation_ba = self.head(tgt_embedding, src_embedding, tgt, src)\n\n else:\n rotation_ba = rotation_ab.transpose(2, 1).contiguous()\n translation_ba = -torch.matmul(rotation_ba, translation_ab.unsqueeze(2)).squeeze(2)\n return rotation_ab, translation_ab, rotation_ba, translation_ba\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.svd",
"torch.cat",
"torch.zeros",
"torch.sum",
"torch.device",
"torch.softmax",
"torch.norm",
"torch.ones",
"torch.eye",
"torch.arange",
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.BatchNorm2d",
"torch.nn.Conv1d",
"torch.stack",
"torch.det",
"torch.matmul",
"torch.nn.ReLU"
]
] |
claylau/genetic_algorithm
|
[
"692f995a2ca325ba94ac1656b28b651c9a861f46"
] |
[
"test_ga.py"
] |
[
"import math\nimport numpy as np\nfrom genetic_algorithm.ga import GA\n\n\ndef objective_1():\n cfg = {}\n cfg[\"name\"] = \"Sphere-2D\"\n cfg[\"dimension\"] = 2\n cfg[\"obj_func\"] = lambda x: np.sum(np.power(x, 2))\n cfg[\"fitness_func\"] = lambda x: np.sum(np.power(x, 2))\n cfg[\"lower_bounds\"] = -5.12\n cfg[\"up_bounds\"] = 5.12\n cfg[\"optimal_direction\"] = \"maximize\"\n return cfg\n\ndef objective_2():\n cfg = {}\n cfg[\"name\"] = \"De-Jong\"\n cfg[\"dimension\"] = 2\n cfg[\"obj_func\"] = lambda x: 100*(x[1] - x[0]**2)**2 + (x[0]-1)**2\n cfg[\"fitness_func\"] = lambda x: 100*(x[1] - x[0]**2)**2 + (x[0]-1)**2\n cfg[\"lower_bounds\"] = -2.048\n cfg[\"up_bounds\"] = 2.048\n cfg[\"optimal_direction\"] = \"maximize\"\n return cfg\n\ndef objective_3():\n cfg = {}\n cfg[\"name\"] = \"Himmelbaut\"\n cfg[\"dimension\"] = 2\n cfg[\"obj_func\"] = lambda x: (x[0]**2 + x[1] - 11)**2 + (x[0] + x[1]**2 - 7)**2\n cfg[\"fitness_func\"] = lambda x: (x[0]**2 + x[1] - 11)**2 + (x[0] + x[1]**2 - 7)**2\n cfg[\"lower_bounds\"] = -6\n cfg[\"up_bounds\"] = 6\n cfg[\"optimal_direction\"] = \"maximize\"\n return cfg\n\ndef objective_4():\n cfg = {}\n cfg[\"name\"] = \"Sphere-HD\"\n cfg[\"dimension\"] = 20\n cfg[\"obj_func\"] = lambda x: np.sum(np.power(x, 2))\n cfg[\"fitness_func\"] = lambda x: -1 * np.sum(np.power(x, 2))\n cfg[\"lower_bounds\"] = -100\n cfg[\"up_bounds\"] = 100\n cfg[\"optimal_direction\"] = \"minimize\"\n return cfg\n\ndef objective_5():\n cfg = {}\n cfg[\"name\"] = \"Step-HD\"\n cfg[\"dimension\"] = 20\n cfg[\"obj_func\"] = lambda x: np.sum(np.power(np.round(np.array(x)+0.5), 2))\n cfg[\"fitness_func\"] = lambda x: -1 * np.sum(np.power(np.round(np.array(x)+0.5), 2))\n cfg[\"lower_bounds\"] = -100\n cfg[\"up_bounds\"] = 100\n cfg[\"optimal_direction\"] = \"minimize\"\n return cfg\n\ndef objective_6():\n cfg = {}\n cfg[\"name\"] = \"Schwefel-HD\"\n cfg[\"dimension\"] = 20\n cfg[\"obj_func\"] = lambda x: np.sum(np.array(x) + np.absolute(x))\n cfg[\"fitness_func\"] = lambda x: -1 * np.sum(np.array(x) + np.absolute(x))\n cfg[\"lower_bounds\"] = -10\n cfg[\"up_bounds\"] = 10\n cfg[\"optimal_direction\"] = \"minimize\"\n return cfg\n\ndef low_dimension_single_objective_optimization():\n cfg = {}\n cfg[\"generation\"] = 20\n cfg[\"top_k_reserved\"] = 5\n cfg[\"population_size\"] = 50\n cfg[\"lengths\"] = 8\n cfg[\"num_point\"] = 2\n cfg[\"pc\"] = 0.8\n cfg[\"pm\"] = 0.1\n cfg[\"code_mode\"] = \"binary\"\n return cfg\n\n\ndef high_dimension_single_objective_optimization():\n cfg = {}\n cfg[\"generation\"] = 50\n cfg[\"top_k_reserved\"] = 10\n cfg[\"population_size\"] = 100\n cfg[\"lengths\"] = 16\n cfg[\"num_point\"] = 2\n cfg[\"pc\"] = 0.8\n cfg[\"pm\"] = 0.1\n cfg[\"code_mode\"] = \"binary\"\n return cfg\n\n\ndef main():\n # low/high dimension single objective optimization\n cfg = low_dimension_single_objective_optimization()\n for obj in [objective_1, objective_2, objective_3]:\n cfg.update(obj())\n ga = GA(cfg)\n ga.run(save_dir=\"low\")\n\n cfg = high_dimension_single_objective_optimization()\n for obj in [objective_4, objective_5, objective_6]:\n cfg.update(obj())\n ga = GA(cfg)\n ga.run(save_dir=\"high\")\n\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"numpy.array",
"numpy.absolute",
"numpy.power"
]
] |
jiayouff/Paddle
|
[
"dc76e4b0f1f9abe61c3886382a004c929379e870"
] |
[
"python/paddle/fluid/framework.py"
] |
[
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport re\nimport six\nimport sys\n\nimport numpy as np\n\nfrom .. import compat as cpt\nfrom .proto import framework_pb2\ntry:\n from . import core\nexcept ImportError as e:\n raise ImportError(\n \"\"\"NOTE: You may need to run \\\"export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH\\\"\n if you encounters \\\"libmkldnn.so not found\\\" errors. If you have python\n installed in other directory, replace \\\"/usr/local/lib\\\" with your own\n directory. The original error is: \\n\"\"\" + cpt.get_exception_message(e))\nexcept Exception as e:\n raise e\nfrom . import unique_name\n\n__all__ = [\n 'Program',\n 'default_startup_program',\n 'default_main_program',\n 'program_guard',\n 'name_scope',\n]\n\nEMPTY_VAR_NAME = core.kEmptyVarName()\nTEMP_VAR_NAME = core.kTempVarName()\nGRAD_VAR_SUFFIX = core.kGradVarSuffix()\nZERO_VAR_SUFFIX = core.kZeroVarSuffix()\nCONTROL_DEP_VAR_PREFIX = core.kControlDepVarName()\n\n_imperative_tracer_ = None\n\n\ndef _in_imperative_mode():\n return _imperative_tracer_ is not None\n\n\ndef _imperative_tracer():\n return _imperative_tracer_\n\n\nclass NameScope(object):\n def __init__(self, name=\"\", parent=None):\n self._children = dict()\n self._name = name\n self._parent = parent\n\n def child(self, prefix):\n if prefix not in self._children:\n new_child = NameScope(prefix, self)\n self._children[prefix] = [new_child]\n else:\n new_child = NameScope(prefix + \"_%d\" % len(self._children[prefix]),\n self)\n self._children[prefix].append(new_child)\n return new_child\n\n def parent(self):\n return self._parent\n\n def name(self):\n return self._name\n\n\n_name_scope = NameScope()\n\n\n@contextlib.contextmanager\ndef name_scope(prefix=None):\n \"\"\"\n Generate hierarchical name prefix for the operators.\n\n Note: This should only used for debugging and visualization purpose.\n Don't use it for serious analysis such as graph/program transformations.\n\n Args:\n prefix(str): prefix.\n\n Examples:\n .. code-block:: python\n\n with name_scope(\"encoder\"):\n ...\n with name_scope(\"decoder\"):\n ...\n with name_scope(\"attention\"):\n ...\n \"\"\"\n # TODO(panyx0718): Only [0-9a-z].\n assert prefix, \"namescope prefix cannot be empty.\"\n global _name_scope\n _name_scope = _name_scope.child(prefix)\n yield\n _name_scope = _name_scope.parent()\n\n\ndef _full_name_scope():\n global _name_scope\n scope = _name_scope\n name = \"\"\n while scope:\n name = scope.name() + \"/\" + name\n scope = scope.parent()\n return name\n\n\ndef generate_control_dev_var_name():\n import random\n return CONTROL_DEP_VAR_PREFIX + \"@\" + str(random.random())\n\n\ndef grad_var_name(var_name):\n \"\"\"\n Returns:\n str: gradient name for a certain var name\n \"\"\"\n return var_name + GRAD_VAR_SUFFIX\n\n\ndef convert_np_dtype_to_dtype_(np_dtype):\n \"\"\"\n Convert the data type in numpy to the data type in Paddle\n\n Args:\n np_dtype(np.dtype): the data type in numpy.\n\n Returns:\n core.VarDesc.VarType: the data type in Paddle.\n\n \"\"\"\n dtype = np.dtype(np_dtype)\n if dtype == np.float32:\n return core.VarDesc.VarType.FP32\n elif dtype == np.float64:\n return core.VarDesc.VarType.FP64\n elif dtype == np.float16:\n return core.VarDesc.VarType.FP16\n elif dtype == np.int32:\n return core.VarDesc.VarType.INT32\n elif dtype == np.int16:\n return core.VarDesc.VarType.INT16\n elif dtype == np.int64:\n return core.VarDesc.VarType.INT64\n elif dtype == np.bool:\n return core.VarDesc.VarType.BOOL\n elif dtype == np.uint16:\n return core.VarDesc.VarType.INT16\n elif dtype == np.uint8:\n return core.VarDesc.VarType.UINT8\n elif dtype == np.int8:\n return core.VarDesc.VarType.INT8\n else:\n raise ValueError(\"Not supported numpy dtype %s\" % dtype)\n\n\ndef dtype_is_floating(dtype):\n \"\"\"\n Check the data type is floating or not.\n Args:\n dtype(np.dtype|core.VarDesc.VarType): data type.\n Could be numpy format or Paddle format\n\n Returns(bool): True if data type is a float value\n\n \"\"\"\n if not isinstance(dtype, core.VarDesc.VarType):\n dtype = convert_np_dtype_to_dtype_(dtype)\n\n return dtype in [\n core.VarDesc.VarType.FP16, core.VarDesc.VarType.FP32,\n core.VarDesc.VarType.FP64\n ]\n\n\ndef _debug_string_(proto, throw_on_error=True):\n \"\"\"\n Get the debug string of a protobuf message. The message could be not\n initialized.\n Args:\n proto(google.protobuf.message.Message): The protobuf message\n throw_on_error(bool): True if raise an error when the protobuf message\n is not initialized.\n\n Returns(str): The debug string of the protobuf message\n\n \"\"\"\n error_fields = list()\n if not proto.IsInitialized(error_fields) and throw_on_error:\n raise ValueError(\"{0} are not initialized.\\nThe message is {1}:\\n\".\n format(error_fields, proto))\n return proto.__str__()\n\n\nclass Variable(object):\n \"\"\"\n In Fluid, every input and output of an operator is a variable. In most\n cases, variables are used for holding different kinds of data or training\n labels. A variable belongs to a block. All variable has its own name and\n two variables in different blocks could have the same name.\n\n There are many kinds of variables. Each kind of them has its own attributes\n and usages. Please reference the framework.proto for details.\n\n Most of a Variable's member variables can be setted to be None. It mean\n it is not available or will be specified later.\n\n Args:\n block(Block): The block that the variable belongs to.\n type(core.VarDesc.VarType): Variable type. Please reference the\n framework.proto for details.\n name(str|None): The name of the variable. If setted None, it will be\n generated automatically. Default: None\n shape(tuple|list|None): The shape of the variable. -1 means the batch size.\n Some kinds of variable do not contain shape, just set it to None.\n Default: None\n dtype(np.dtype|core.VarDesc.VarType|str|None): The data type of variable.\n Default: None\n lod_level (int|None): The level of lod tensor. 0 means it is not a time\n series data.\n Default: None\n capacity (int|None): The capacity of Channel variable. Ignored for other\n types. Default: None\n persistable (bool|None): True if the variable is persistable. A persistable\n variable will not be deleted after an iteration ending. Defaults: None.\n error_clip (BaseErrorClipAttr|None): The error clip attributes of the\n corresponding gradient variable. Default: None\n stop_gradient (bool): True if the variable will stop to calculate its\n gradients when backward. Default: False.\n is_data (bool): True if the variable is an input data. Default: False\n\n Notes:\n The constructor of Variable should not be invoked directly. Please\n use `Block.create_var` to create a variable.\n\n Examples:\n .. code-block:: python\n\n cur_program = Program()\n cur_block = cur_program.current_block()\n new_variable = cur_block.create_var(name=\"X\",\n shape=[-1, 23, 48],\n dtype='float32')\n \"\"\"\n\n def __init__(self,\n block,\n type=core.VarDesc.VarType.LOD_TENSOR,\n name=None,\n shape=None,\n dtype=None,\n lod_level=None,\n capacity=None,\n persistable=None,\n error_clip=None,\n stop_gradient=False,\n is_data=False,\n **kwargs):\n self.block = block\n self.error_clip = error_clip\n\n if name is None:\n name = unique_name.generate('_generated_var')\n is_new_var = False\n name = cpt.to_text(name)\n self.desc = self.block.desc.find_var(cpt.to_bytes(name))\n\n if self.desc is None:\n self.desc = self.block.desc.var(cpt.to_bytes(name))\n is_new_var = True\n\n if is_new_var:\n self.desc.set_type(type)\n elif self.desc.type() != type:\n raise ValueError(\"Variable {0} has been created before. The \"\n \"previous type is {1}; the new type is {2}. They\"\n \" are not matched\".format(self.name,\n self.desc.type(), type))\n\n if shape is not None:\n if is_new_var:\n self.desc.set_shape(shape)\n else:\n old_shape = self.shape\n shape = tuple(shape)\n if shape != old_shape:\n raise ValueError(\n \"Variable {0} has been created before. the previous \"\n \"shape is {1}; the new shape is {2}. They are not \"\n \"matched.\".format(self.name, old_shape, shape))\n if dtype is not None:\n if not isinstance(dtype, core.VarDesc.VarType):\n dtype = convert_np_dtype_to_dtype_(dtype)\n if is_new_var:\n self.desc.set_dtype(dtype)\n else:\n old_dtype = self.dtype\n if dtype != old_dtype:\n raise ValueError(\"Variable {0} has been created before. \"\n \"The previous data type is {1}; the new \"\n \"data type is {2}. They are not \"\n \"matched.\".format(self.name, old_dtype,\n dtype))\n\n if lod_level is not None:\n if is_new_var:\n self.desc.set_lod_level(lod_level)\n else:\n if lod_level != self.lod_level:\n raise ValueError(\"Variable {0} has been created before. \"\n \"The previous lod_level is {1}; the new \"\n \"lod_level is {2}. They are not \"\n \"matched\".format(self.name, self.lod_level,\n lod_level))\n if persistable is not None:\n if is_new_var:\n self.desc.set_persistable(persistable)\n else:\n if persistable != self.persistable:\n raise ValueError(\n \"Variable {0} has been created before.\"\n \"The previous persistable is {1}; the new \"\n \"persistable is {2}. They are not matched\".format(\n self.name, self.persistable, persistable))\n\n if capacity is not None:\n if is_new_var:\n self.desc.set_capacity(capacity)\n else:\n # TODO(abhinavarora) : Compare with set capacity once,\n # get_capacity is implemented\n pass\n\n self.block.vars[name] = self\n self.op = None\n self.stop_gradient = stop_gradient\n self.is_data = is_data\n if _in_imperative_mode():\n self._ivar = core.VarBase()\n self._ivar.desc = self.desc\n\n def _numpy(self):\n scope = _imperative_tracer().get_scope(self.block.desc)\n tensor = core.get_variable_tensor(scope, self.desc.name())\n return np.array(tensor)\n\n def _backward(self):\n scope = _imperative_tracer().get_scope(self.block.desc)\n self._ivar._run_backward(scope)\n\n def _gradient(self):\n return np.array(self._ivar._grad())\n\n def __str__(self):\n return self.to_string(True)\n\n def to_string(self, throw_on_error, with_details=False):\n \"\"\"\n Get debug string.\n\n Args:\n throw_on_error(bool): True if raise an exception when self is\n not initialized.\n with_details(bool): more details about variables and parameters\n (e.g. trainable, optimize_attr, ...) will be printed when\n with_details is True. Default False;\n\n Returns:\n str: The debug string.\n \"\"\"\n assert isinstance(throw_on_error, bool) and isinstance(with_details,\n bool)\n protostr = self.desc.serialize_to_string()\n proto = framework_pb2.VarDesc.FromString(six.binary_type(protostr))\n res_str = _debug_string_(proto, throw_on_error)\n if with_details:\n additional_attr = (\"error_clip\", \"stop_gradient\")\n for attr_name in additional_attr:\n res_str += \"%s: %s\\n\" % (\n attr_name, six.binary_type(getattr(self, attr_name)))\n return res_str\n\n __repr__ = __str__\n\n def _set_desc(self, input):\n \"\"\"\n Set the variable description.\n\n Args:\n input(core.VarDesc): The new VarDesc.\n\n Returns:\n None\n \"\"\"\n self.desc = input\n\n @property\n def persistable(self):\n return self.desc.persistable()\n\n @persistable.setter\n def persistable(self, p):\n self.desc.set_persistable(p)\n\n @property\n def name(self):\n return cpt.to_text(self.desc.name())\n\n @name.setter\n def name(self, new_name):\n self.desc.set_name(new_name)\n\n @property\n def shape(self):\n # convert to tuple, make it as same as numpy API.\n return tuple(self.desc.shape())\n\n @property\n def dtype(self):\n return self.desc.dtype()\n\n @property\n def lod_level(self):\n return self.desc.lod_level()\n\n @property\n def type(self):\n return self.desc.type()\n\n def _set_error_clip(self, error_clip):\n \"\"\"\n Set the error_clip.\n\n Args:\n error_clip(BaseErrorClipAttr) : The new error_clip.\n\n Returns:\n None\n \"\"\"\n self.error_clip = error_clip\n\n\ndef get_all_op_protos():\n \"\"\"\n Get all registered op proto from PaddlePaddle C++ end.\n\n Returns:\n list: list of OpProto.\n \"\"\"\n protostrs = core.get_all_op_protos()\n ret_values = []\n for pbstr in protostrs:\n op_proto = framework_pb2.OpProto.FromString(six.binary_type(pbstr))\n ret_values.append(op_proto)\n return ret_values\n\n\nclass OpProtoHolder(object):\n \"\"\"\n A global variable to hold all OpProtos from C++ as a map\n \"\"\"\n\n @classmethod\n def instance(cls):\n if not hasattr(cls, '_instance'):\n cls._instance = cls()\n return cls._instance\n\n def __init__(self):\n assert not hasattr(\n self.__class__,\n '_instance'), 'Please use `instance()` to get OpProtoHolder object!'\n op_protos = get_all_op_protos()\n self.op_proto_map = {}\n for proto in op_protos:\n self.op_proto_map[proto.type] = proto\n\n def get_op_proto(self, type):\n \"\"\"\n Get OpProto by a type string.\n Args:\n type(str): The type that operator registered in C++ side.\n\n Returns(framework_pb2.OpProto): The OpProto\n\n \"\"\"\n if type not in self.op_proto_map:\n raise ValueError(\"Operator \\\"%s\\\" has not been registered.\" % type)\n return self.op_proto_map[type]\n\n @staticmethod\n def generated_op_attr_names():\n return {\n core.op_proto_and_checker_maker.kOpRoleAttrName(),\n core.op_proto_and_checker_maker.kOpRoleVarAttrName(),\n core.op_proto_and_checker_maker.kOpNameScopeAttrName()\n }\n\n\nclass Operator(object):\n \"\"\"\n In Fluid, all the operation are represented by Operator, and Operator\n is regarded as a build in an instruction of a Block. Users can use the\n build in instructions to describe their neural network.\n\n Args:\n block(Block): The block has the current operator.\n desc(core.OpDesc): The protobuf description of Operator.\n type(str): The type of operator. Default None.\n inputs(dict): The input of this Operator. it is a dictionary, for every\n element, key is the input parameter name, and value is a list of\n variables. Default None.\n outputs(dict): The output of this Operator. it is a dictionary, for\n every element, key is the input parameter name, and value is a list\n of variables. Default None.\n attrs(dict): The attributes of this Operator. it is a dictionary, for\n every element, key is attribute name, and value is the attribute value.\n The attribute type should be as same as the type registered in C++ side.\n Default None.\n\n Returns:\n Operator: The initialized Operator.\n\n Raises:\n ValueError: If the passed input, output and attrs doesn't match the\n initializing Operator's that registered in C++ side.\n\n Notes:\n The constructor of operator should not be invoked directly. Use\n Block.append_op or Block._prepend_op instead.\n\n Examples:\n .. code-block:: python\n\n cur_program = Program()\n cur_block = cur_program.current_block()\n # var1 += var2 + var3\n cur_block.append_op(type=\"sum\",\n inputs={\"X\": [var1, var2, var3]},\n outputs={\"Out\": [var1]})\n \"\"\"\n OP_WITHOUT_KERNEL_SET = {\n 'feed', 'fetch', 'save', 'load', 'recurrent', 'go',\n 'rnn_memory_helper_grad', 'conditional_block', 'while', 'send', 'recv',\n 'listen_and_serv', 'parallel_do', 'save_combine', 'load_combine',\n 'ncclInit', 'select', 'checkpoint_notify', 'gen_nccl_id'\n }\n\n def __init__(self,\n block,\n desc,\n type=None,\n inputs=None,\n outputs=None,\n attrs=None):\n self.block = block\n self.desc = desc\n # note: not add self.attrs here:\n # https://github.com/PaddlePaddle/Paddle/pull/12583#pullrequestreview-145093173\n op_attrs = attrs\n if op_attrs is None:\n op_attrs = dict()\n del attrs\n\n op_maker = core.op_proto_and_checker_maker\n\n if op_maker.kOpRoleAttrName() not in op_attrs:\n op_attrs[op_maker.kOpRoleAttrName()] = self.block.program.op_role\n\n role_var_name = op_maker.kOpRoleVarAttrName()\n if len(self.block.program.\n op_role_var) != 0 and role_var_name not in op_attrs:\n op_attrs[role_var_name] = self.block.program.op_role_var\n\n if role_var_name in op_attrs and len(op_attrs[role_var_name]) == 0:\n del op_attrs[role_var_name]\n\n if len(self.desc.type()) != 0:\n return\n if type is None:\n raise ValueError(\n \"`type` to initilized an Operator can not be None.\")\n self.desc.set_type(type)\n proto = OpProtoHolder.instance().get_op_proto(type)\n\n namescope_var_name = op_maker.kOpNameScopeAttrName()\n op_attrs[namescope_var_name] = _full_name_scope()\n\n def find_name(var_list, name):\n for var_name in var_list:\n if var_list[var_name] is not None and var_name == name:\n return True\n return False\n\n if inputs is not None:\n for in_proto in proto.inputs:\n found = find_name(inputs, in_proto.name)\n assert found or in_proto.dispensable, \"Input {} not found\".format(\n in_proto.name)\n\n if found:\n in_args = inputs[in_proto.name]\n if not isinstance(in_args, list):\n in_args = [in_args]\n if not in_proto.duplicable and len(in_args) > 1:\n raise ValueError(\n \"Input %s expects only one input, but %d are given.\"\n % (in_proto.name, len(in_args)))\n in_arg_names = []\n for arg in in_args:\n if isinstance(arg, six.string_types):\n in_arg_names.append(arg)\n elif isinstance(arg, six.binary_type):\n in_arg_names.append(arg.decode())\n else:\n in_arg_names.append(cpt.to_text(arg.name))\n self.desc.set_input(in_proto.name, in_arg_names)\n else:\n self.desc.set_input(in_proto.name, [])\n\n if outputs is not None:\n given = set()\n need = set()\n for n in outputs:\n given.add(n)\n for m in proto.outputs:\n need.add(m.name)\n if not given == need:\n raise ValueError((\"Incorrect setting for output(s) of \"\n \"operator \\\"%s\\\". Need: [%s] Given: [%s]\") %\n (type,\n \", \".join(six.binary_type(e) for e in need),\n \", \".join(six.binary_type(e) for e in given)))\n\n for out_proto in proto.outputs:\n out_args = outputs[out_proto.name]\n if not isinstance(out_args, list):\n out_args = [out_args]\n if not out_proto.duplicable and len(out_args) > 1:\n raise ValueError(\n \"Output %s expects only one output, but %d are given.\" %\n (out_proto.name, len(out_args)))\n out_arg_names = []\n for arg in out_args:\n out_arg_names.append(cpt.to_text(arg.name))\n arg.op = self\n self.desc.set_output(out_proto.name, out_arg_names)\n\n if op_attrs is not None:\n if not isinstance(op_attrs, dict):\n raise TypeError(\"'attrs' should be a dict.\")\n for attr in proto.attrs:\n attr_name = attr.name\n if (attr_name not in op_attrs) or (op_attrs[attr_name] is None):\n continue\n attr_val = op_attrs[attr_name]\n self._update_desc_attr(attr_name, attr_val)\n\n self.desc.check_attrs()\n if self._has_kernel(type):\n self.desc.infer_var_type(self.block.desc)\n self.desc.infer_shape(self.block.desc)\n if _in_imperative_mode():\n self.iop = core.OpBase()\n self.iop.desc = self.desc\n self.inputs = []\n if inputs is not None:\n for inp in inputs.values():\n if isinstance(inp, Variable):\n self.inputs.append(inp)\n elif isinstance(inp, list) or isinstance(inp, tuple):\n self.inputs.extend(inp[:])\n self.outputs = []\n if outputs is not None:\n for out in outputs.values():\n if isinstance(out, Variable):\n self.outputs.append(out)\n elif isinstance(out, list) or isinstance(out, tuple):\n self.outputs.extend(out[:])\n\n def _has_kernel(self, op_type):\n return op_type not in self.OP_WITHOUT_KERNEL_SET\n\n def to_string(self, throw_on_error):\n \"\"\"\n Get debug string.\n\n Args:\n throw_on_error(bool): Whether to raise exception if self is not\n initialized.\n\n Returns:\n str: The debug string.\n\n \"\"\"\n protostr = self.desc.serialize_to_string()\n proto = framework_pb2.OpDesc.FromString(six.binary_type(protostr))\n return _debug_string_(proto, throw_on_error)\n\n def __str__(self):\n return self.to_string(True)\n\n __repr__ = __str__\n\n @property\n def type(self):\n return self.desc.type()\n\n def input(self, name):\n \"\"\"\n Get the input arguments according to the input parameter name.\n\n Args:\n name(str): The input parameter name.\n\n Returns:\n list: return the list of argument names that associated with \\\n the specific parameter name.\n \"\"\"\n return self.desc.input(name)\n\n def _rename_input(self, old_name, new_name):\n \"\"\"\n Rename the `old_name` to `new_name`.\n\n Args:\n old_name(str): The old name of the Operator's input.\n new_name(str): The new name of the Operator's input.\n\n Returns:\n None\n \"\"\"\n self.desc._rename_input(old_name, new_name)\n\n def _rename_output(self, old_name, new_name):\n \"\"\"\n Rename the `old_name` to `new_name`.\n\n Args:\n old_name(str): The old name of the Operator's output.\n new_name(str): The new name of the Operator's output.\n\n Returns:\n None\n \"\"\"\n self.desc._rename_output(old_name, new_name)\n\n @property\n def input_names(self):\n return self.desc.input_names()\n\n @property\n def input_arg_names(self):\n return self.desc.input_arg_names()\n\n @property\n def output_arg_names(self):\n return self.desc.output_arg_names()\n\n def output(self, name):\n \"\"\"\n Get output arguments by the output parameter name.\n\n Args:\n name(str): The output parameter name.\n\n Returns:\n list: return the list of argument names associated with \\\n the specific parameter name.\n \"\"\"\n return self.desc.output(name)\n\n @property\n def output_names(self):\n return self.desc.output_names()\n\n @property\n def idx(self):\n for i, op in enumerate(self.block.ops):\n if op == self:\n return i\n raise ValueError(\n \"Can't find op itself in it's block. It could be a bug of Paddle.\")\n\n def has_attr(self, name):\n \"\"\"\n Whether this Operator has the attribute with name or not.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n bool: True if has this attribute.\n\n \"\"\"\n return self.desc.has_attr(name)\n\n def attr_type(self, name):\n \"\"\"\n Get the type of attribute by attribute's name.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n core.AttrType: the attribute type.\n \"\"\"\n return self.desc.attr_type(name)\n\n def _set_attr(self, name, val):\n \"\"\"\n Set the value of attribute by attribute's name.\n\n Args:\n name(str): the attribute name.\n val(bool|int|str|float|list): the value of the attribute.\n\n Raises:\n ValueError: If the type of value doesn't match with desc.attr_type(name).\n \"\"\"\n self._update_desc_attr(name, val)\n\n def _update_desc_attr(self, name, val):\n \"\"\"\n Update the value of desc's attribute by attribute's name.\n\n Args:\n name(str): the attribute name.\n val(bool|int|str|float|list): the value of the attribute.\n\n Raises:\n ValueError: If the type of value doesn't match with desc.attr_type(name).\n \"\"\"\n if isinstance(val, Block):\n self.desc.set_block_attr(name, val.desc)\n elif isinstance(val, list) and val and all(\n isinstance(v, Block) for v in val):\n self.desc.set_blocks_attr(name, [v.desc for v in val])\n elif isinstance(val, core.BlockDesc) or \\\n isinstance(val, core.ProgramDesc):\n self.desc.set_serialized_attr(name, val.serialize_to_string())\n else:\n self.desc._set_attr(name, val)\n\n @property\n def attr_names(self):\n return self.desc.attr_names()\n\n def attr(self, name):\n \"\"\"\n Get the attribute by name.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n bool|int|str|float|list: The attribute value. The return value\n can be any valid attribute type.\n \"\"\"\n return self.desc.attr(name)\n\n def _block_attr_id(self, name):\n \"\"\"\n Get the block attribute's id by name.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n int: the block index.\n \"\"\"\n return self.desc._block_attr_id(name)\n\n def _block_attr(self, name):\n \"\"\"\n Get the block attribute by name.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n block: the block attribute.\n \"\"\"\n\n id = self._block_attr_id(name)\n assert (id >= 0 and id < len(self.block.program.blocks))\n return self.block.program.blocks[id]\n\n def _blocks_attr(self, name):\n \"\"\"\n Get the blocks attribute by name.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n list: list of the blocks attribute.\n \"\"\"\n attrs = []\n for i in self._blocks_attr_ids(name):\n assert (i >= 0 and i < len(self.block.program.blocks))\n attrs.append(self.block.program.blocks[i])\n\n return attrs\n\n def _blocks_attr_ids(self, name):\n \"\"\"\n Get the blocks attribute's ids by name.\n\n Args:\n name(str): the attribute name.\n\n Returns:\n list: list of the blocks ids.\n \"\"\"\n\n return self.desc._blocks_attr_ids(name)\n\n def all_attrs(self):\n \"\"\"\n Get the attribute dict.\n\n Returns:\n dict: The Operator's attribute dict, name->attr.\n \"\"\"\n attr_names = self.attr_names\n attr_map = {}\n for n in attr_names:\n attr_type = self.desc.attr_type(n)\n if attr_type == core.AttrType.BLOCK:\n attr_map[n] = self._block_attr(n)\n continue\n\n if attr_type == core.AttrType.BLOCKS:\n attr_map[n] = self._blocks_attr(n)\n continue\n\n attr_map[n] = self.attr(n)\n\n return attr_map\n\n\nclass Block(object):\n \"\"\"\n In Fluid, a Program is consistence of multi-Block, and Block stores\n VarDesc and OpDesc. In a specific Block, a VarDesc have a unique name.\n One block could have some child blocks, and child block's name scopes\n should inherit the parent's so that OpDesc in child block can reference\n a VarDesc that is stored in the parent block.\n Please reference the framework.proto for details.\n\n Args:\n program(Program): The Program that the Block belongs to.\n idx(int): The block's id in the Program.\n\n Notes:\n The constructor of Block should not be invoked directly. Please\n use `Program._create_block()` to create a block.\n\n Examples:\n .. code-block:: python\n\n cur_program = Program()\n cur_block = cur_program.current_block()\n var = cur_block.create_var(name=\"X\",\n shape=[-1, 23, 48],\n dtype='float32')\n cur_block.append_op(type=\"abs\",\n inputs={\"X\": [var]},\n outputs={\"Out\": [var]})\n \"\"\"\n\n def __init__(self, program, idx):\n self.desc = program.desc.block(idx)\n self.vars = collections.OrderedDict() # var_name --> var\n self.ops = list() # operator list\n self.program = program\n self.removed_vars = collections.OrderedDict()\n\n def __str__(self):\n return self.to_string(True)\n\n def to_string(self, throw_on_error, with_details=False):\n \"\"\"\n Get debug string.\n\n Args:\n throw_on_error(bool): raise exception when self is not initialized\n when throw_on_error is True.\n with_details(bool): more details about variables and parameters\n (e.g. trainable, optimize_attr, ...) will be printed when\n with_details is True. Default False.\n\n Returns:\n str: The debug string.\n \"\"\"\n assert isinstance(throw_on_error, bool) and isinstance(with_details,\n bool)\n if with_details:\n re_add_indent = re.compile(r\"\\n(.)\")\n res_str = \"blocks {\\n idx: %d\\n parent_idx: %d\" % (\n self.idx, self.parent_idx)\n for var in list(self.vars.values()):\n res_str += \"\\n vars {\\n %s }\" % re_add_indent.sub(\n r\"\\n \\1\", var.to_string(throw_on_error, with_details))\n for op in self.ops:\n res_str += \"\\n ops {\\n %s }\" % re_add_indent.sub(\n r\"\\n \\1\", op.to_string(throw_on_error))\n res_str += \"\\n}\"\n else:\n protostr = self.desc.serialize_to_string()\n proto = framework_pb2.BlockDesc.FromString(\n six.binary_type(protostr))\n res_str = _debug_string_(proto, throw_on_error)\n return res_str\n\n __repr__ = __str__\n\n @property\n def parent_idx(self):\n return self.desc.parent\n\n @property\n def forward_block_idx(self):\n return self.desc.get_forward_block_idx()\n\n def _set_forward_block_idx(self, idx):\n \"\"\"\n Set the forward block Idx.\n\n Args:\n idx(int): the block index.\n\n Returns:\n None\n \"\"\"\n self.desc._set_forward_block_idx(idx)\n\n @property\n def idx(self):\n return self.desc.id\n\n def var(self, name):\n \"\"\"\n Get a Variable by name from this block.\n\n Args:\n name(str): the Variable's name.\n\n Raises:\n ValueError: The If input's type is not str, or this block\n doesn't have a Variable with the giving name.\n\n Returns:\n Variable: the Variable with the giving name.\n \"\"\"\n if not isinstance(name, six.string_types):\n raise TypeError(\n \"var require string as parameter, but get %s instead.\" %\n (type(name)))\n v = self.vars.get(name, None)\n if v is None:\n raise ValueError(\"var %s not in this block\" % name)\n return v\n\n def _find_var_recursive(self, name):\n \"\"\"\n Get a Variable by name from this block recursively.\n\n Args:\n name(str): the Variable's name.\n\n Returns:\n Variable: the Variable with the giving name. Or None if not found.\n \"\"\"\n frontier = list()\n visited = set()\n\n frontier.append(self)\n\n prog = self.program\n\n while len(frontier) != 0: # BFS\n cur = frontier[0]\n frontier = frontier[1:]\n\n if id(cur) in visited:\n continue\n\n if cur.has_var(name):\n return cur.var(name)\n\n if cur.parent_idx != -1:\n frontier.append(prog.block(cur.parent_idx))\n\n if cur.forward_block_idx != -1:\n frontier.append(prog.block(cur.forward_block_idx))\n\n visited.add(id(cur))\n return None\n\n def _var_recursive(self, name):\n \"\"\"\n Get a Variable by name from this block recursively.\n\n Args:\n name(str): the Variable's name.\n\n Raises:\n ValueError: this block and this parent block doesn't\n have a Variable with the giving name.\n\n Returns:\n Variable: the Variable with the giving name.\n \"\"\"\n var = self._find_var_recursive(name)\n if var:\n return var\n else:\n raise ValueError(\"Var {0} is not found recursively\".format(name))\n\n def all_parameters(self):\n return list(self.iter_parameters())\n\n def iter_parameters(self):\n return (item[1] for item in six.iteritems(self.vars)\n if isinstance(item[1], Parameter))\n\n def create_var(self, *args, **kwargs):\n var = Variable(block=self, *args, **kwargs)\n if 'initializer' in kwargs:\n kwargs['initializer'](var, self)\n return var\n\n def has_var(self, name):\n return name in self.vars\n\n def _rename_var(self, name, new_name):\n \"\"\"\n Rename variable in vars and ops' inputs and outputs\n\n Args:\n name(str): the name that need to be renamed.\n new_name(str): the name that need to rename to.\n\n Raises:\n ValueError: If this block doesn't have this the giving name,\n or the type of the var with the giving name is not Parameter\n or Variable.\n\n Returns:\n Variable: the Variable with the giving name.\n \"\"\"\n name = cpt.to_text(name)\n new_name = cpt.to_text(new_name)\n\n if not self.has_var(name):\n raise ValueError(\"var %s is not in current block\" % name)\n v = self.var(name)\n if type(v) == Parameter:\n var_type = \"Parameter\"\n stop_gradient = v.stop_gradient\n trainable = v.trainable\n optimize_attr = v.optimize_attr\n regularizer = v.regularizer\n gradient_clip_attr = v.gradient_clip_attr\n error_clip = v.error_clip\n elif type(v) == Variable:\n var_type = \"Variable\"\n error_clip = v.error_clip\n stop_gradient = v.stop_gradient\n else:\n raise ValueError(\"unsupported var type: %s\", type(v))\n orig_var_type = v.type\n self.desc._rename_var(cpt.to_bytes(name), cpt.to_bytes(new_name))\n # NOTE: v is destroyed by C++ after calling _rename_var.\n d = self.desc.find_var(cpt.to_bytes(new_name))\n if var_type == \"Parameter\":\n var = Parameter(\n self,\n d.shape(),\n d.dtype(),\n type=orig_var_type,\n name=new_name,\n stop_gradient=stop_gradient,\n trainable=trainable,\n optimize_attr=optimize_attr,\n regularizer=regularizer,\n gradient_clip_attr=gradient_clip_attr,\n error_clip=error_clip)\n elif var_type == \"Variable\":\n var = Variable(\n self,\n type=orig_var_type,\n name=new_name,\n error_clip=error_clip,\n stop_gradient=stop_gradient)\n\n # rename the python side, _sync_with_cpp will only add\n # new vars/ops to python side.\n self.vars[new_name] = var\n del self.vars[name]\n self._sync_with_cpp()\n return var\n\n def _remove_var(self, name):\n self._sync_with_cpp()\n self.desc._remove_var(cpt.to_bytes(name))\n del self.vars[name]\n\n def create_parameter(self, *args, **kwargs):\n global_block = self.program.global_block()\n param = Parameter(global_block, *args, **kwargs)\n if 'initializer' in kwargs:\n\n def _is_inited_by(block, var):\n init_ops = []\n for op in block.ops:\n if var.name in op.output_arg_names:\n init_ops.append(op)\n return init_ops\n\n initializer = kwargs['initializer']\n init_ops = _is_inited_by(global_block, param)\n init_ops_len = len(init_ops)\n if init_ops_len > 1:\n raise RuntimeError(\"param \" + param.name +\n \" is inited by multiple init ops \" + str(\n init_ops))\n elif init_ops_len == 1:\n #TODO already inited, do nothing, should log a warning\n pass\n else:\n initializer(param, self)\n return param\n\n def append_op(self, *args, **kwargs):\n \"\"\"\n Appends a new Operator according to the giving arguments.\n\n Returns:\n Operator: the append Operator.\n \"\"\"\n op_desc = self.desc.append_op()\n op = Operator(block=self, desc=op_desc, *args, **kwargs)\n if _in_imperative_mode():\n _imperative_tracer().trace(op.iop, [v._ivar for v in op.inputs],\n [v._ivar for v in op.outputs], self.desc)\n self.ops.append(op)\n return op\n\n def _insert_op(self, index, *args, **kwargs):\n \"\"\"\n Insert a Operator according to the giving arguments.\n\n Args:\n index(int): the place that the operator to insert.\n\n Returns:\n Operator: the insert Operator.\n \"\"\"\n self._sync_with_cpp()\n op_desc = self.desc._insert_op(index)\n op = Operator(block=self, desc=op_desc, *args, **kwargs)\n self.ops.insert(index, op)\n return op\n\n def _remove_op(self, index):\n \"\"\"\n Remove the specific position operator.\n\n Args:\n index(int): the position that the operator to insert.\n\n Returns:\n None\n \"\"\"\n self._sync_with_cpp()\n self.desc._remove_op(index, index + 1)\n del self.ops[index]\n\n def _slice_ops(self, start, end):\n \"\"\"\n Return the Operator between start and end.\n\n Args:\n start(int): the start position.\n end(int): the end position.\n\n Returns:\n list: the Operators between start and end.\n \"\"\"\n return self.ops[start:end]\n\n def _prepend_op(self, *args, **kwargs):\n op_desc = self.desc._prepend_op()\n op = Operator(self, op_desc, *args, **kwargs)\n self.ops.insert(0, op)\n return op\n\n def _sync_with_cpp(self):\n \"\"\"\n Sync from the desc on the c++ end. This method is used to synchronize\n the c++ desc instance generated by backward.\n \"\"\"\n # sync variables from cpp\n for var in self.desc.all_vars():\n if not self.has_var(var.name()):\n self.create_var(name=var.name(), desc=var, type=var.type())\n\n # sync variables removed from c++ end\n for var in list(self.vars.keys()):\n if not self.desc.find_var(cpt.to_bytes(var)):\n self.vars.pop(var)\n\n # sync operators from cpp\n ops_in_cpp = []\n for op_idx in range(0, self.desc.op_size()):\n ops_in_cpp.append(self.desc.op(op_idx))\n\n if len(self.ops) != 0:\n first_op_in_python = self.ops[0].desc\n last_op_in_python = self.ops[len(self.ops) - 1].desc\n start_index = None\n end_index = None\n for index in range(len(ops_in_cpp)):\n if first_op_in_python == ops_in_cpp[index]:\n start_index = index\n if last_op_in_python == ops_in_cpp[index]:\n end_index = index\n assert start_index is not None\n assert end_index is not None\n assert start_index <= end_index\n else:\n start_index = 0\n end_index = -1\n\n # sync ops append to the head of cpp_ops\n for index in range((start_index - 1 - 1), -1, -1):\n op_desc = ops_in_cpp[index]\n op = Operator(self, op_desc)\n self.ops.insert(0, op)\n\n # sync ops append to the end of cpp_ops\n for index in range((end_index + 1), len(ops_in_cpp)):\n op_desc = ops_in_cpp[index]\n op = Operator(self, op_desc)\n self.ops.append(op)\n\n # sync ops removed from c++ end\n if end_index != -1 and end_index < len(self.ops):\n ops_in_cpp_index = 0\n ops_in_python_index = 0\n while ops_in_python_index < len(\n self.ops) and ops_in_cpp_index < len(ops_in_cpp):\n if self.ops[ops_in_python_index].desc != ops_in_cpp[\n ops_in_cpp_index]:\n del self.ops[ops_in_python_index]\n else:\n ops_in_cpp_index += 1\n ops_in_python_index += 1\n\n assert len(self.ops) == len(ops_in_cpp)\n for index in range(len(self.ops)):\n assert self.ops[index].desc == ops_in_cpp[index]\n\n def _copy_param_info_from(self, other):\n \"\"\"\n Copy the information of parameters from the other block.\n\n Args:\n other(Block): the other block.\n\n Raises:\n ValueError: If type of input is not Block, or the `other` and this\n block is not in the same topology.\n\n Returns:\n None\n \"\"\"\n if not isinstance(other, Block):\n raise TypeError(\n \"_copy_param_info_from should be invoked with Block\")\n for p in other.iter_parameters():\n assert isinstance(p, Parameter)\n v = self.vars.get(p.name, None)\n if v is None:\n raise ValueError(\"_copy_param_info_from should be invoked with \"\n \"same topology\")\n assert isinstance(v, Variable)\n new_p = Parameter(\n block=self,\n shape=v.shape,\n dtype=v.dtype,\n type=v.type,\n lod_level=v.lod_level,\n stop_gradient=p.stop_gradient,\n trainable=p.trainable,\n optimize_attr=p.optimize_attr,\n regularizer=p.regularizer,\n gradient_clip_attr=p.gradient_clip_attr,\n error_clip=p.error_clip,\n name=v.name)\n self.vars[new_p.name] = new_p\n\n def _clone_variable(self, var):\n \"\"\"\n Clone a variable into current block.\n\n Args:\n var: the variable to be cloned.\n\n Returns:\n Variable: the new variable cloned from 'var' in current block.\n \"\"\"\n assert isinstance(var, Variable)\n ret_var = None\n # make STEP_SCOPES var can be safely cloned.\n if var.type == core.VarDesc.VarType.STEP_SCOPES:\n ret_var = self.create_var(\n name=var.name, persistable=var.persistable, type=var.type)\n elif var.type == core.VarDesc.VarType.RAW:\n ret_var = self.create_var(\n name=var.name, persistable=var.persistable, type=var.type)\n elif var.type == core.VarDesc.VarType.SELECTED_ROWS:\n ret_var = self.create_var(\n name=var.name,\n shape=var.shape,\n dtype=var.dtype,\n type=var.type,\n persistable=True,\n is_data=var.is_data)\n else:\n ret_var = self.create_var(\n name=var.name,\n shape=var.shape,\n dtype=var.dtype,\n type=var.type,\n lod_level=var.lod_level,\n persistable=True,\n is_data=var.is_data)\n return ret_var\n\n\nclass Program(object):\n \"\"\"\n Python Program. Beneath it is a ProgramDesc, which is used for\n create c++ Program. A program is a self-contained programing\n language like container. It has at least one Block, when the\n control flow op like conditional_block, while_op is included,\n it will contains nested block.\n Please reference the framework.proto for details.\n\n Notes: we have default_startup_program and default_main_program\n by default, a pair of them will shared the parameters.\n The default_startup_program only run once to initialize parameters,\n default_main_program run in every mini batch and adjust the weights.\n\n Returns:\n A empty program.\n\n Examples:\n >>> main_program = fluid.Program()\n >>> startup_program = fluid.Program()\n >>> with fluid.program_guard(main_program=main_program, startup_program=startup_program):\n >>> fluid.layers.data(name=\"x\", shape=[-1, 784], dtype='float32')\n >>> fluid.layers.data(name=\"y\", shape=[-1, 1], dtype='int32')\n >>> fluid.layers.fc(name=\"fc\", shape=[10], dtype='float32', act=\"relu\")\n\n \"\"\"\n\n def __init__(self):\n self.desc = core.ProgramDesc()\n self.blocks = [Block(self, 0)]\n self.current_block_idx = 0\n self._seed = 0\n self._current_role = core.op_proto_and_checker_maker.OpRole.Forward\n self._op_role_var = []\n\n # for distribute\n self._is_distributed = False\n self._is_chief = False\n self._slice_vars_and_attrs = []\n self._endpoints = []\n self._trainers_endpoints = []\n self._distributed_lookup_table = None\n\n @property\n def op_role(self):\n \"\"\"\n The operator role. In a enum {Forward, Backward, Optimize}.\n\n Notes: this is a low level API. It is used only for ParallelExecutor to\n duplicate or schedule operator to devices.\n\n For example, the forward operator should be executed on every device.\n The backward operator should be executed on every device and the\n parameter gradient of backward (use :code:`op_role_var` to get this\n variable) operator should be merged to one device. The optimization\n operators should be executed on only one device and broadcast the\n optimization result, i.e., the new parameter, to every other device.\n \"\"\"\n return self._current_role\n\n @op_role.setter\n def set_op_role(self, role):\n self._current_role = role\n\n @property\n def op_role_var(self):\n \"\"\"\n The auxiliary variables for :code:`op_role` property.\n\n See Also: :code:`Program.op_role`'s documentation for details.\n\n Notes: This is a very low-level API. Users should not use it directly.\n \"\"\"\n return self._op_role_var\n\n @op_role_var.setter\n def set_op_role_var(self, var_name):\n self._op_role_var = [var_name]\n\n @contextlib.contextmanager\n def _optimized_guard(self, param_and_grads):\n \"\"\"\n A with guard to set :code:`Optimization` :code:`OpRole` and\n :code:`OpRoleVar` automatically.\n\n Notes: This is a very low level API. Users should not use it directly.\n\n Args:\n param_and_grads(list): The variables (names) to be optimized.\n\n Examples:\n\n >>> p, g = backward(...)\n >>> with program._optimized_guard([p,g]):\n >>> p = p - 0.001 * g\n \"\"\"\n tmp_role = self._current_role\n tmp_var = self._op_role_var\n\n OpRole = core.op_proto_and_checker_maker.OpRole\n self._current_role = OpRole.Optimize\n self._op_role_var = [\n var.name if isinstance(var, Variable) else var\n for var in param_and_grads\n ]\n yield\n self._op_role_var = tmp_var\n self._current_role = tmp_role\n\n @contextlib.contextmanager\n def _lr_schedule_guard(self, is_with_opt=False):\n \"\"\"\n A with guard to set :code:`LRSched` :code:`OpRole` and\n :code:`OpRoleVar` automatically. The :code:`OpRoleVar` is\n set to the target learning rate.\n\n Notes: This is a very low level API. Users should not use it directly.\n\n Args:\n is_with_opt: Only set to true if these ops a in the middle\n of a bunch of optimize ops so that it can be treated\n correctly. For example, sgd->lr_op->sgd->lr_op->sgd.\n\n Examples:\n\n >>> p, g = backward(...)\n >>> with program.lr_schedule_guard():\n >>> lr = lr * decay\n \"\"\"\n\n tmp_role = self._current_role\n tmp_var = self._op_role_var\n\n OpRole = core.op_proto_and_checker_maker.OpRole\n self._current_role = OpRole.LRSched\n if is_with_opt:\n self._current_role = int(OpRole.LRSched) | int(OpRole.Optimize)\n # TODO(typhoonzero): how to set target learning rate var\n self._op_role_var = []\n yield\n self._op_role_var = tmp_var\n self._current_role = tmp_role\n\n def __str__(self):\n \"\"\"\n Get the protobuf debug string of this Program.\n\n Returns:\n (str): The protobuf debug string.\n\n Raises:\n ValueError: If any of required fields is not set.\n \"\"\"\n return self.to_string(True)\n\n def to_string(self, throw_on_error, with_details=False):\n \"\"\"\n To debug string.\n\n Args:\n throw_on_error(bool): raise Value error when any of required fields\n is not set.\n\n with_details(bool): True if more details about variables and\n parameters, e.g., :code:`trainable`, :code:`optimize_attr`, need\n to print.\n\n Returns\n (str): The debug string.\n\n Raises:\n ValueError: If any of required fields is not set and throw_on_error is\n True.\n\n \"\"\"\n assert isinstance(throw_on_error, bool) and isinstance(with_details,\n bool)\n if with_details:\n res_str = \"\"\n for block in self.blocks:\n res_str += block.to_string(throw_on_error, with_details)\n else:\n protostr = self.desc.serialize_to_string()\n proto = framework_pb2.ProgramDesc.FromString(\n six.binary_type(protostr))\n res_str = _debug_string_(proto, throw_on_error)\n return res_str\n\n def _get_desc(self):\n \"\"\"\n Get the C++ side of `ProgramDesc` object pointer. The C++ object is\n exposed by :code:`pybind`.\n\n Notes: This is a very low level API. Users should not use this API\n directly.\n \"\"\"\n return self.desc\n\n def _version(self):\n return self.desc._version()\n\n def clone(self, for_test=False):\n \"\"\"\n Create a new, duplicated program.\n\n\n Some operators, e.g., :code:`batch_norm`, behave differently between\n training and testing. They have an attribute, :code:`is_test`, to\n control this behaviour. This method will change the :code:`is_test`\n attribute of them to :code:`True` when :code:`for_test=True`.\n\n * Set for_test to False when we want to clone the program for training.\n * Set for_test to True when we want to clone the program for testing.\n\n Notes: This API DOES NOT prune any operator. Use\n :code:`clone(for_test=True)` before backward and optimization please. e.g.\n\n >>> test_program = fluid.default_main_program().clone(for_test=True)\n >>> optimizer = fluid.optimizer.Momentum(learning_rate=0.01, momentum=0.9)\n >>> optimizer.minimize()\n\n Args:\n for_test(bool): True if change the :code:`is_test` attribute of\n operators to :code:`True`.\n\n Returns:\n Program: The new, duplicated Program object.\n\n Examples:\n\n 1. To clone a test program, the sample code is:\n\n >>> import paddle.fluid as fluid\n >>> train_program = fluid.Program()\n >>> startup_program = fluid.Program()\n >>> with fluid.program_guard(train_program, startup_program):\n >>> img = fluid.layers.data(name='image', shape=[784])\n >>> hidden = fluid.layers.fc(input=img, size=200, act='relu')\n >>> hidden = fluid.layers.dropout(hidden, dropout_prob=0.5)\n >>> loss = fluid.layers.cross_entropy(\n >>> input=fluid.layers.fc(hidden, size=10, act='softmax'),\n >>> label=fluid.layers.data(name='label', shape=[1], dtype='int64'))\n >>>\n >>> test_program = train_program.clone(for_test=True)\n >>>\n >>> sgd = fluid.optimizer.SGD(learning_rate=1e-3)\n >>> with fluid.program_guard(train_program, startup_program):\n >>> sgd.minimize(loss)\n\n 2. The :code:`clone` method can be avoid if you create program for\n training and program for testing individually.\n\n >>> import paddle.fluid as fluid\n >>>\n >>> def network(is_test):\n >>> img = fluid.layers.data(name='image', shape=[784])\n >>> hidden = fluid.layers.fc(input=img, size=200, act='relu')\n >>> hidden = fluid.layers.dropout(hidden, dropout_prob=0.5, is_test=is_test)\n >>> loss = fluid.layers.cross_entropy(\n >>> input=fluid.layers.fc(hidden, size=10, act='softmax'),\n >>> label=fluid.layers.data(name='label', shape=[1], dtype='int64'))\n >>> return loss\n >>>\n >>> train_program = fluid.Program()\n >>> startup_program = fluid.Program()\n >>> test_program = fluid.Program()\n >>>\n >>> with fluid.program_guard(train_program, startup_program):\n >>> with fluid.unique_name.guard():\n >>> loss = network(is_test=False)\n >>> sgd = fluid.optimizer.SGD(learning_rate=1e-3)\n >>> sgd.minimize(loss)\n >>>\n >>> # the test startup program is not used.\n >>> with fluid.program_guard(test_program, fluid.Program()):\n >>> with fluid.unique_name.guard():\n >>> loss = network(is_test=True)\n\n The two code snippets above will generate same programs.\n \"\"\"\n if for_test:\n p = self._inference_optimize(prune_read_op=False)\n else:\n p = Program()\n p.current_block_idx = self.current_block_idx\n p._seed = self._seed\n p.desc = core.ProgramDesc(self.desc)\n p.blocks = [\n Block(p, i) for i in six.moves.range(self.desc.num_blocks())\n ]\n\n p._current_role = self._current_role\n p._op_role_var = self._op_role_var\n\n p._sync_with_cpp()\n\n p._copy_param_info_from(self)\n p._copy_data_info_from(self)\n p._copy_dist_param_info_from(self)\n return p\n\n def _prune(self, targets):\n \"\"\"\n Prune operators and variables which are not needed to generate\n :code:`targets`.\n\n Notes: This is a very low level API. Users should not use this API\n directly. This API is in flux and not stable.\n\n Args:\n targets(list|Variable|Operator): A list of variables or operators\n need to be pruned\n\n Returns:\n Program: A new, pruned program.\n\n \"\"\"\n if not isinstance(targets, list):\n targets = [targets]\n targets_idx = []\n for t in targets:\n if not isinstance(t, Operator):\n if isinstance(t, Variable):\n # After transpiler processing, the op that output this\n # variable maybe has been changed, so t.op is not reliable\n # and we need to find the current op that generate this\n # variable here.\n t.op = None\n global_block = self.global_block()\n for idx, op in enumerate(global_block.ops):\n if t.name in op.output_arg_names:\n t.op = op\n break\n\n t = t.op\n if t is None:\n raise ValueError(\n \"The target variable must have an \"\n \"associated operator that generates it.\")\n else:\n raise ValueError(\"All targets of prune() can only be \"\n \"Variable or Operator.\")\n\n targets_idx.append([t.block.idx, t.idx])\n res = Program()\n res.desc = core.prune(self.desc, targets_idx)\n res.blocks = [\n Block(res, i) for i in six.moves.range(res.desc.num_blocks())\n ]\n res._sync_with_cpp()\n return res\n\n def _inference_optimize(self, prune_read_op=True):\n \"\"\"\n This method will create a new program and do following adjustments on it:\n 1. Remove all reader variables and their creator ops if exist.\n\n 2. Remove the :code:`read_op` if exists.\n\n 3. change the :code:`is_test`\n attribute of operators to :code:`True`. All the :code:`Parameter`\n information will be lost.\n\n Args:\n prune_read_op(bool): remove the read ops that are added by py_reader\n for cpp inference library\n\n Notes: This API is a very low level API. Use\n :code:`Program.clone(for_test=True)` instead.\n\n Returns:\n Program: The new program.\n \"\"\"\n res = Program()\n res.desc = core.ProgramDesc(self.desc)\n\n # remove all readers and the read_op if exist\n read_op_idx = 0\n root_block = res.desc.block(0)\n if prune_read_op:\n while True:\n if read_op_idx >= root_block.op_size() or root_block.op(\n read_op_idx).type() == 'read':\n break\n read_op_idx += 1\n if read_op_idx < root_block.op_size():\n root_block._remove_op(0, read_op_idx + 1)\n for var in root_block.all_vars():\n if var.type() == core.VarDesc.VarType.READER:\n root_block._remove_var(cpt.to_bytes(var.name()))\n\n # change all `is_test` attributes to True\n for i in six.moves.range(res.desc.num_blocks()):\n block = res.desc.block(i)\n for j in six.moves.range(block.op_size()):\n op = block.op(j)\n if op.has_attr('is_test'):\n op._set_attr('is_test', True)\n res.blocks = [\n Block(res, i) for i in six.moves.range(res.desc.num_blocks())\n ]\n res._sync_with_cpp()\n return res\n\n @staticmethod\n def parse_from_string(binary_str):\n \"\"\"\n Deserialize a program desc from protobuf binary string.\n\n Notes: All information about parameters will be lost after serialization\n and deserialization.\n\n Args:\n binary_str_type(str): The binary prootbuf string.\n\n Returns:\n Program: A deserialized program desc.\n \"\"\"\n p = Program()\n p.desc = core.ProgramDesc(binary_str)\n p.blocks = [Block(p, i) for i in six.moves.range(p.desc.num_blocks())]\n p._sync_with_cpp()\n return p\n\n @property\n def random_seed(self):\n \"\"\"\n The default random seed for random operators in Program. Zero means get\n the random seed from random device.\n\n Notes: It must be set before the operators have been added.\n \"\"\"\n return self._seed\n\n @property\n def num_blocks(self):\n \"\"\"\n The number of blocks in this program.\n \"\"\"\n return self.desc.num_blocks()\n\n @random_seed.setter\n def random_seed(self, seed):\n if not isinstance(seed, int):\n raise ValueError(\"Seed must be a integer.\")\n self._seed = seed\n\n def __repr__(self):\n return self.__str__()\n\n def global_block(self):\n \"\"\"\n Get the first block of this program.\n \"\"\"\n return self.blocks[0]\n\n def block(self, index):\n \"\"\"\n Get the :code:`index` block of this program\n Args:\n index(int): The index of block to get\n\n Returns:\n Block: The :code:`index` block\n \"\"\"\n return self.blocks[index]\n\n def current_block(self):\n \"\"\"\n Get the current block. The :code:`current` block is the block to append\n operators.\n \"\"\"\n return self.blocks[self.current_block_idx]\n\n def _create_block(self, parent_idx=None):\n \"\"\"\n Create a new block with the :code:`parent_idx` and change the current block\n to new block.\n\n Args:\n parent_idx(int): The parent block index.\n\n Returns:\n Block: The new block.\n \"\"\"\n new_block_idx = len(self.blocks)\n parent = self.current_block() if parent_idx is None else self.block(\n parent_idx)\n self.desc.append_block(parent.desc)\n self.current_block_idx = new_block_idx\n self.blocks.append(Block(self, self.current_block_idx))\n return self.current_block()\n\n def _rollback(self):\n \"\"\"\n Exit a code block, i.e., roll back to the parent block.\n Returns:\n None\n \"\"\"\n self.current_block_idx = self.current_block().parent_idx\n\n def _sync_with_cpp(self):\n \"\"\"\n Synchronize Python instance to its binding C++ object instance.\n If the program is modified in C++ space, this method should be invoked.\n\n Notes: This is a very low level API. Users should not invoke it\n directly.\n\n Returns:\n None\n \"\"\"\n for block_idx in range(len(self.blocks), self.desc.num_blocks()):\n self.blocks.append(Block(self, block_idx))\n for block in self.blocks:\n block._sync_with_cpp()\n\n def _copy_param_info_from(self, other):\n \"\"\"\n Copy the information of parameters from other program.\n\n Notes: This is a very low level API. Users should not invoke it\n directly.\n\n Args:\n other(Program): Other program\n\n Returns:\n None\n \"\"\"\n if not isinstance(other, Program):\n raise TypeError(\"_copy_param_info_from should be invoked with \"\n \"Program\")\n\n if len(self.blocks) != len(other.blocks):\n raise ValueError(\"_copy_param_info_from should be invoked with two \"\n \"program, with represent the same topology\")\n self.global_block()._copy_param_info_from(other.global_block())\n\n def _copy_dist_param_info_from(self, other):\n \"\"\"\n Copy the information of distributed information from other program.\n\n Args:\n other(Program): Other program\n\n Returns:\n None\n \"\"\"\n if not isinstance(other, Program):\n raise TypeError(\"_copy_dist_param_info_from should be invoked with \"\n \"Program\")\n self._is_distributed = other._is_distributed\n self._is_chief = other._is_chief\n self._slice_vars_and_attrs = other._slice_vars_and_attrs\n self._endpoints = other._endpoints\n self._distributed_lookup_table = other._distributed_lookup_table\n\n def _copy_data_info_from(self, other):\n \"\"\"\n Copy the information of data variables from other program.\n\n Notes: This is a very low level API. Users should not invoke it\n directly.\n\n Args:\n other(Program): Other program\n\n Returns:\n None\n \"\"\"\n if not isinstance(other, Program):\n raise TypeError(\"_copy_param_info_from should be invoked with \"\n \"Program\")\n\n if len(self.blocks) != len(other.blocks):\n raise ValueError(\"_copy_param_info_from should be invoked with two \"\n \"program, with represent the same topology\")\n for var in list(other.global_block().vars.values()):\n if var.is_data:\n self.global_block().var(var.name).is_data = True\n\n def list_vars(self):\n \"\"\"\n Get all variables from this Program. A iterable object is returned.\n\n Returns:\n iterable: The generator will yield every variable in this program.\n \"\"\"\n for each_block in self.blocks:\n for each_var in list(each_block.vars.values()):\n yield each_var\n\n\nclass Parameter(Variable):\n \"\"\"\n Parameter is derived from Variable. A parameter is a persistable\n Variable, and will be updated by optimizers after each iteration.\n The training of a neural network is essentially the updating of\n its parameters.\n\n Relative to a general Variable, a Parameter has several its own\n member variables:\n\n Args:\n trainable(bool): True if the parameter need to be updated after\n iterations.\n optimize_attr(map): Parameter attributes related with optimizing.\n Currently, it only contains 'learning_rate'.\n Default: {'learning_rate': 1.0}\n regularizer(WeightDecayRegularizer): The Regularizer which will\n be applied on the parameter. Default: None\n gradient_clip_attr(BaseGradientClipAttr): The gradint clip strategy\n which will be applied on the parameter. Default: None\n do_model_average(bool): True if the model average strategy will\n be applied on this parameter.\n \"\"\"\n\n def __init__(self, block, shape, dtype, **kwargs):\n if shape is None or dtype is None:\n raise ValueError(\"Parameter must set shape and dtype\")\n if len(shape) == 0:\n raise ValueError(\"Parameter shape cannot be empty\")\n\n for each in shape:\n if each < 0:\n raise ValueError(\"Parameter shape should not be related with \"\n \"batch-size\")\n\n Variable.__init__(\n self, block, persistable=True, shape=shape, dtype=dtype, **kwargs)\n self.trainable = kwargs.get('trainable', True)\n\n self.optimize_attr = kwargs.get('optimize_attr', {'learning_rate': 1.0})\n\n self.regularizer = kwargs.get('regularizer', None)\n\n self.gradient_clip_attr = kwargs.get('gradient_clip_attr', None)\n\n self.do_model_average = kwargs.get('do_model_average', None)\n\n def __str__(self):\n return self.to_string(True)\n\n def to_string(self, throw_on_error, with_details=False):\n \"\"\"\n To debug string.\n\n Args:\n throw_on_error(bool): raise exception when self is not initialized\n when throw_on_error is True\n with_details(bool): more details about variables and parameters\n (e.g. trainable, optimize_attr, ...) will be printed when with_details is True\n\n Returns(str): The debug string.\n\n \"\"\"\n assert isinstance(throw_on_error, bool) and isinstance(with_details,\n bool)\n if with_details:\n res_str = Variable.to_string(self, throw_on_error, True)\n additional_attr = (\"trainable\", \"optimize_attr\", \"regularizer\",\n \"gradient_clip_attr\", \"do_model_average\")\n for attr_name in additional_attr:\n res_str += \"%s: %s\\n\" % (\n attr_name, six.binary_type(getattr(self, attr_name)))\n else:\n res_str = Variable.to_string(self, throw_on_error, False)\n return res_str\n\n __repr__ = __str__\n\n\n# program is a global instance.\n_main_program_ = Program()\n_startup_program_ = Program()\n\n\ndef default_startup_program():\n \"\"\"\n Get default/global startup program.\n\n The layer function in :code:`fluid.layers` will create parameters, readers,\n NCCL handles as global variables. The :code:`startup_program` will\n initialize them by the operators in startup program. The layer function will\n append these initialization operators into startup program.\n\n This method will return the :code:`default` or the :code:`current` startup\n program. Users can use :code:`fluid.program_guard` to switch program.\n\n Returns:\n Program: startup program\n \"\"\"\n return _startup_program_\n\n\ndef default_main_program():\n \"\"\"\n Get default/global main program. The main program is used for training or\n testing.\n\n All layer function in :code:`fluid.layers` will append operators and\n variables to the :code:`default_main_program`.\n\n The :code:`default_main_program` is the default program in a lot of APIs.\n For example, the :code:`Executor.run()` will execute the\n :code:`default_main_program` when the program is not specified.\n\n Returns:\n Program: main program\n \"\"\"\n return _main_program_\n\n\ndef switch_main_program(program):\n \"\"\"\n Switch the main program to a new program.\n\n Args:\n program(Program): The new main program\n\n Returns:\n Program: The previous main program\n \"\"\"\n global _main_program_\n prev_program = _main_program_\n _main_program_ = program\n return prev_program\n\n\ndef switch_startup_program(program):\n \"\"\"\n Switch the startup program to a new program\n Args:\n program(Program): The new startup program\n\n Returns:\n Program: The previous startup program\n \"\"\"\n global _startup_program_\n prev_program = _startup_program_\n _startup_program_ = program\n return prev_program\n\n\n@contextlib.contextmanager\ndef program_guard(main_program, startup_program=None):\n \"\"\"\n Change the global main program and startup program with `with` statement.\n Layer functions in the Python `with` block will append operators and\n variables to the new main programs.\n\n Examples:\n\n >>> import paddle.fluid as fluid\n >>> main_program = fluid.Program()\n >>> startup_program = fluid.Program()\n >>> with fluid.program_guard(main_program, startup_program):\n >>> data = fluid.layers.data(...)\n >>> hidden = fluid.layers.fc(...)\n\n Notes: The temporary :code:`Program` can be used if the user does not need\n to construct either of startup program or main program.\n\n Examples:\n\n >>> import paddle.fluid as fluid\n >>> main_program = fluid.Program()\n >>> # does not care about startup program. Just pass a temporary value.\n >>> with fluid.program_guard(main_program, fluid.Program()):\n >>> data = ...\n\n Args:\n main_program(Program): New main program inside `with` statement.\n startup_program(Program): New startup program inside `with` statement.\n None means do not change startup program.\n \"\"\"\n if not isinstance(main_program, Program):\n raise TypeError(\"main_program should be Program\")\n main_program = switch_main_program(main_program)\n if startup_program is not None:\n if not isinstance(startup_program, Program):\n raise TypeError(\"startup_program should be Program\")\n startup_program = switch_startup_program(startup_program)\n yield\n switch_main_program(main_program)\n if startup_program is not None:\n switch_startup_program(startup_program)\n\n\ndef _get_var(name, program=None):\n \"\"\"\n Get a variable by name from the global block of a program.\n\n Args:\n name(str): name of the variable\n program(Program|None): program object.\n If None, default_global_program() will be used.\n\n Returns:\n Variable\n \"\"\"\n if program is None:\n program = default_main_program()\n assert isinstance(name, str)\n assert isinstance(program, Program)\n\n return program.global_block().var(name)\n\n\n@contextlib.contextmanager\ndef _imperative_guard(tracer):\n global _imperative_tracer_\n tmp_trace = _imperative_tracer_\n _imperative_tracer_ = tracer\n yield\n _imperative_tracer_ = tmp_trace\n"
] |
[
[
"numpy.array",
"numpy.dtype"
]
] |
qwilka/PDover2t
|
[
"4387d153228f1af20a8f5f3f368aa49c42cda2cd"
] |
[
"pdover2t/pipe/pipe.py"
] |
[
"import logging\n\nimport numpy as np\n\nfrom ..utilities.function_tools import func_call_exception_trap\n\nlogger = logging.getLogger(__name__)\n\n#π = np.pi\n\n\ndef WT_from_D(Do, Di):\n \"\"\"Calculate pipe wall thickness from outer diameter and inner diameter.\n \"\"\"\n return (Do - Di) / 2\n\ndef Di_from_WT(Do, WT):\n \"\"\"Calculate pipe inner diameter from outer diameter and wall thickness.\n \"\"\"\n return Do - 2 * WT\n\ndef Do_from_WT(Di, WT):\n \"\"\"Calculate pipe outer diameter from inner diameter and wall thickness.\n \"\"\"\n return Di + 2 * WT\n\n\n@func_call_exception_trap\ndef pipe_Do_Di_WT(*, Do=None, Di=None, WT=None):\n \"\"\"Calculate pipe wall thickness / outer diameter / inner diameter.\n \"\"\"\n if Do is not None and Di is not None and WT is not None:\n assert Do==Di+2*WT, f\"pipe_D_WT: inconsistent pipe dimensions Do={Do} Di={Di} WT={WT}.\"\n elif WT is None:\n WT = (Do - Di) / 2\n elif Di is None:\n Di = Do - 2 * WT\n elif Do is None:\n Do = Di + 2 * WT\n else:\n return False\n return Do, Di, WT\n\n\n@func_call_exception_trap\ndef pipe_CSA(Do=None, Di=None, WT=None):\n \"\"\"Calculate pipe cross sectional area.\n \"\"\"\n if Do is None or Di is None:\n Do, Di, WT = pipe_Do_Di_WT(Do=Do, Di=Di, WT=WT)\n CSA = np.pi / 4 * (Do**2 - Di**2)\n return CSA\n\n\n@func_call_exception_trap\ndef pipe_umass(pipe_ρ, *, CSA=None, Do=None, Di=None, WT=None):\n \"\"\"Calculate pipe unit mass (mass/length).\n \"\"\"\n if CSA is None:\n CSA = pipe_CSA(Do=Do, Di=Di, WT=WT)\n umass = CSA * pipe_ρ\n return umass\n\n\n@func_call_exception_trap\ndef pipe_uwgt(g=9.806650, *, umass=None, Do=None, Di=None, WT=None, pipe_ρ=None):\n \"\"\"Calculate pipe unit weight (weight/length).\n \"\"\"\n if umass is None:\n umass = pipe_umass(pipe_ρ, Do=Do, Di=Di, WT=WT)\n uwgt = umass * g\n return uwgt\n\n\n@func_call_exception_trap\ndef pipe_usubwgt(Dbuoy, seawater_ρ, g=9.806650, *, uwgt=None, \n Do=None, Di=None, WT=None, umass=None, pipe_ρ=None):\n \"\"\"Calculate pipe unit submerged weight (weight/length).\n \"\"\"\n if uwgt is None:\n uwgt = pipe_uwgt(g, Do=Do, Di=Di, WT=WT, umass=umass, pipe_ρ=pipe_ρ)\n usubwgt = uwgt - np.pi/4*Dbuoy**2 * seawater_ρ * g\n return usubwgt\n\n\n@func_call_exception_trap\ndef pipe_layers(layers, *, Di_ref=None, Do_ref=None, umass=0,\n returnDict=False):\n \"\"\"calculate equivalent properties for stacked pipe layers.\n\n :param layers: list of layer properties, each element is\n a tuple consisting of (layer_thickness, layer_mass_density)\n The first layer is the layer at Do_ref|Di_ref. Subsequent layers\n are ordered outwards (increasing D) when Di_ref is reference diameter. \n Layers are ordered inwards when Do_ref is reference diameter (decreasing D).\n :type layers: list, tuple\n :returns: tuple with equivalent properties (density, umass, Do, Di, WT)\n :rtype: tuple\n\n .. doctest::\n\n >>> layers = [(0.0003, 1450.), (0.0038, 960.), (0.045, 2250.)]\n >>> pipe_layers(layers, Di_ref=0.660, umass=337.0)\n (5232.900238245189, 0.0491)\n \"\"\"\n #if (Di is not None) and (Do is not None):\n if len([None for x in [Di_ref, Do_ref] if x is None]) != 1:\n raise ValueError(f\"pipe_layers: arguments not correctly specified: Di_ref={Di_ref}, Do_ref={Do_ref}\")\n\n #alayers = np.array(layers, dtype=[('WT', 'f4'), ('density', 'f4')])\n alayers = layers\n #print(alayers)\n if Do_ref:\n # Di_ref = Do_ref - np.sum(alayers[\"WT\"]) * 2\n # alayers = alayers[::-1]\n Di_ref = sum([x for x,y in layers])\n alayers = layers[::-1]\n WT_total = 0.0\n equiv_umass = umass\n layer_Di = Di_ref \n for layer in alayers:\n #print(layer)\n layer_Do = layer_Di + 2*layer[0]\n WT_total += layer[0]\n _csa = np.pi/4 * (np.power(layer_Do,2) - np.power(layer_Di,2))\n equiv_umass += _csa * layer[1]\n layer_Di = layer_Do\n if Do_ref is None:\n Do_ref = Di_ref + 2 * WT_total\n _csa = np.pi/4 * (np.power(Do_ref,2) - np.power(Di_ref,2))\n equiv_ρ = equiv_umass / _csa\n #return (equiv_density, equiv_umass, Do_ref, Di_ref, WT_total)\n if returnDict:\n return {\n \"equiv_ρ\": equiv_ρ,\n \"umass\": equiv_umass,\n \"Do\": Do_ref,\n \"Di\": Di_ref,\n \"WT\": WT_total\n }\n else:\n return (equiv_ρ, equiv_umass, Do_ref, Di_ref, WT_total)\n\n\nif __name__ == \"__main__\":\n \"\"\" To run doctests:\n $ python -m pdover2t.pipe.pipe\n \"\"\"\n import doctest\n doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)\n # if True:\n # Do = 0.660\n # WT = 0.0214\n # coating_layers = [(0.0003, 1450.), (0.0038, 960.), (0.045, 2250.)]\n # else:\n # Do = np.array([0.660, 0.6656])\n # WT = np.array([0.0214, 0.0242])\n # # coating_layers = [ (np.array([0.0003, 0.0003]), np.array([1450., 1450.])), \n # # (np.array([0.0038, 0.0038]), np.array([960., 960.]) ), \n # # (np.array([0.045, 0.045]), np.array([2250., 1900.]) )]\n # coating_layers = [ (0.0003, 1450.), (0.0038, 960. ), \n # (0.045, np.array([2250., 1900.]) )]\n # length = 12.2\n # pipe_ρ = 7850. \n # seawater_ρ = 1027.0\n # g = 9.81\n\n # # Do, Di, WT = pipe_Do_Di_WT(Do=Do, WT=WT)\n # # CSA = pipe_CSA(Do, Di)\n # # umass = pipe_umass(CSA, pipe_ρ)\n # # joint_mass = umass * length\n # # uwgt = pipe_uwgt(umass, g)\n # # usubwgt = pipe_usubwgt(Do, seawater_ρ, g, Do=Do, WT=WT)\n # # joint_subwgt = usubwgt * length\n\n # umass = pipe_umass(pipe_ρ, Do=Do, WT=WT)\n # layersObj = pipe_layers(coating_layers, Di_ref=Do, umass=umass, returnDict=True)\n # pl_umass = layersObj[\"umass\"]\n # pl_Do = layersObj[\"Do\"]\n # #pl_uwgt = pipe_uwgt(pl_umass, g)\n # #pl_usubwgt = pipe_usubwgt(pl_Do, seawater_ρ, g, Do=Do, WT=WT, umass=pl_umass)\n # pl_usubwgt = pipe_usubwgt(pl_Do, seawater_ρ, g, Do=Do, WT=WT)\n"
] |
[
[
"numpy.power"
]
] |
Anukriti12/PersonalizedFashionStylist
|
[
"25c45f79ad96b5b52e5dd986d9ba9d837df2d4dc"
] |
[
"Recommender-System/model/mlp_inference.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 20 15:03:38 2019\n\n@author: lee\n\"\"\"\n\nimport numpy as np\nimport keras\nfrom keras import regularizers\nfrom keras.layers import Embedding, Input, Dense, merge, Reshape, Flatten\nfrom time import time\nimport argparse\nimport json\nimport sys\nfrom keras.models import Sequential, Model, load_model, save_model\nimport heapq\n\n\"\"\"\nArgument\n\"\"\"\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Run MLP.\")\n parser.add_argument('--mlp_pretrain', nargs='?', default='../dataset/pretrain/amazon_MLP_[16,8]_1569250599.h5',\n help='pretrain path')\n \n parser.add_argument('--dataset', nargs='?', default='amazon',\n help='dataset')\n \n parser.add_argument('--topk', type=int, default=10, \n help='topk')\n \n parser.add_argument('--user', type=int, default=0,\n help='user index')\n \n parser.add_argument('--layers', nargs='?', default='[16,8]', \n help=\"embedding size, layer[0]/2\")\n \n parser.add_argument('--reg_layers', nargs='?', default='[0,0]',\n help=\"regularization\")\n \n return parser.parse_args()\n\n\n\ndef get_model(num_users, num_items, layers = [32,16], reg_layers=[0,0]):\n assert len(layers) == len(reg_layers)\n num_layer = len(layers)\n \n user_input = Input(shape=(1,), dtype='int32', name = 'user_input') \n item_input = Input(shape=(1,), dtype='int32', name = 'item_input') \n \n MLP_Embedding_User = Embedding(input_dim = num_users, output_dim = int(layers[0]/2), name = 'user_embedding',\n embeddings_initializer = 'random_normal', \n embeddings_regularizer = regularizers.l2(reg_layers[0]), \n input_length=1)\n MLP_Embedding_Item = Embedding(input_dim = num_items, output_dim = int(layers[0]/2), name = 'item_embedding',\n embeddings_initializer = 'random_normal', \n embeddings_regularizer = regularizers.l2(reg_layers[0]), \n input_length=1)\n\n user_latent = Flatten()(MLP_Embedding_User(user_input))\n item_latent = Flatten()(MLP_Embedding_Item(item_input))\n\n vector = keras.layers.concatenate([user_latent, item_latent])\n\n for idx in range(1, num_layer):\n layer = Dense(layers[idx], kernel_regularizer= regularizers.l2(reg_layers[idx]), kernel_initializer = 'he_normal',activation='relu', name = 'layer%d' %idx)\n vector = layer(vector)\n\n prediction = Dense(1, activation='sigmoid', kernel_initializer='lecun_uniform', name = 'prediction')(vector)\n \n model = Model(inputs=[user_input, item_input],\n outputs=prediction)\n\n return model\n\n\n# if user already purchsed items, extract!\n \ndef predict_item_score(user):\n map_item_score = {}\n user_index = np.full(itemnum, user, dtype = 'int32')\n items_index = np.arange(0, itemnum, 1, np.int) \n predictions = model.predict([user_index, items_index],batch_size=itemnum, verbose=0)\n \n for i in range(len(items_index)):\n map_item_score[i] = predictions[i]\n \n # top-k \n rank_cosmetic_list = heapq.nlargest(topK, map_item_score, key=map_item_score.get)\n \n # asin name\n real_rank_cosmetic_list=[]\n for i in rank_cosmetic_list:\n real_rank_cosmetic_list.append(product_name[str(i)])\n \n return real_rank_cosmetic_list\n\n\nif __name__ == '__main__':\n args = parse_args()\n layers = eval(args.layers)\n reg_layers = eval(args.reg_layers)\n mlp_pretrain = args.mlp_pretrain\n user = args.user\n topK = args.topk\n \n evaluation_threads = 1\n\n\n \"\"\" Load data \"\"\"\n \n t1 = time()\n dataset = open('../dataset/amazon_raw2inner_dict.json',encoding='utf-8-sig').read()\n js=json.loads(dataset)\n usernum,itemnum,product_name = len(js['user_dict']), len(js['product_dict']), js['product_dict']\n print(\"Load dict done [%.1f s]. #user=%d, #item=%d\"\n % (time() - t1, usernum, itemnum))\n \n\n \"\"\" Load pretrain model\"\"\"\n \n model = get_model(usernum, itemnum, layers, reg_layers)\n model.load_weights(mlp_pretrain)\n print(\"Load pretrained mlp(%s) models done. \" %(mlp_pretrain))\n\n \n print('\\t')\n print(\"User %s's top-%s recommendation\" %(user,topK))\n print('\\t')\n for i in range(topK):\n print(\"%s. %s\" %(i+1,predict_item_score(user)[i]))\n\n \n \n"
] |
[
[
"numpy.arange",
"numpy.full"
]
] |
demmojo/curve-dao-contracts
|
[
"6922cd98c7403cc7c6302f5379194c5418c5cb66"
] |
[
"scripts/stats/plot_vecrv.py"
] |
[
"from brownie import Contract, web3\n\nimport numpy as np\nimport pylab\n\nSTART_BLOCK = 10647813\n\n\ndef main():\n vecrv = Contract(\"0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2\")\n current_block = web3.eth.blockNumber\n blocks = np.linspace(START_BLOCK, current_block, 100)\n powers = [vecrv.totalSupplyAt(int(block)) / 1e18 for block in blocks]\n\n pylab.plot(blocks, powers)\n pylab.xlabel(\"Block number\")\n pylab.ylabel(\"Total veCRV\")\n pylab.show()\n"
] |
[
[
"numpy.linspace"
]
] |
ags3927/frustum-convnet
|
[
"0ccb4a8e45c9973f902aef5cbb5f776ea634ee32"
] |
[
"datasets/temp.py"
] |
[
"''' Provider class and helper functions for Frustum PointNets.\n\nAuthor: Charles R. Qi\nDate: September 2017\n\nModified by Zhixin Wang\n'''\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport time\nimport pickle\nimport sys\nimport os\nimport numpy as np\nimport json\n\nimport torch\nimport logging\nfrom torch.utils.data import Dataset\nfrom torch.utils.data.dataloader import default_collate\nfrom collections import defaultdict\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.dirname(BASE_DIR)\nif ROOT_DIR not in sys.path:\n sys.path.append(ROOT_DIR)\n\nfrom configs.config import cfg\n\nfrom datasets.data_utils import rotate_pc_along_y, project_image_to_rect, compute_box_3d, extract_pc_in_box3d, roty\n# from datasets.dataset_info import KITTICategory\nfrom datasets.dataset_info import DATASET_INFO\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProviderDataset(Dataset):\n\n def __init__(self, npoints, split,\n random_flip=False, random_shift=False,\n one_hot=True,\n from_rgb_detection=False,\n overwritten_data_path='',\n extend_from_det=False):\n\n super(ProviderDataset, self).__init__()\n self.npoints = npoints\n self.split = split\n self.random_flip = random_flip\n self.random_shift = random_shift\n\n self.one_hot = one_hot\n self.from_rgb_detection = from_rgb_detection\n # MODIFICATION START - error distribution of heuristic\n self.errorMargins = np.empty(0)\n self.ground_truth_depth = np.empty(0)\n self.estimated_depth = np.empty(0)\n self.printPercentiles = False\n # MODIFICATION END - error distribution of heuristic\n\n dataset_name = cfg.DATA.DATASET_NAME\n assert dataset_name in DATASET_INFO\n self.category_info = DATASET_INFO[dataset_name]\n\n root_data = cfg.DATA.DATA_ROOT\n car_only = cfg.DATA.CAR_ONLY\n people_only = cfg.DATA.PEOPLE_ONLY\n\n if not overwritten_data_path:\n if not from_rgb_detection:\n if car_only:\n overwritten_data_path = os.path.join(root_data, 'frustum_caronly_%s.pickle' % (split))\n elif people_only:\n overwritten_data_path = os.path.join(root_data, 'frustum_pedcyc_%s.pickle' % (split))\n else:\n overwritten_data_path = os.path.join(root_data, 'frustum_carpedcyc_%s.pickle' % (split))\n else:\n if car_only:\n overwritten_data_path = os.path.join(root_data,\n 'frustum_caronly_%s_rgb_detection.pickle' % (split))\n elif people_only:\n overwritten_data_path = os.path.join(root_data, 'frustum_pedcyc_%s_rgb_detection.pickle' % (split))\n else:\n overwritten_data_path = os.path.join(\n root_data, 'frustum_carpedcyc_%s_rgb_detection.pickle' % (split))\n\n if from_rgb_detection:\n\n with open(overwritten_data_path, 'rb') as fp:\n self.id_list = pickle.load(fp)\n self.box2d_list = pickle.load(fp)\n self.input_list = pickle.load(fp)\n self.type_list = pickle.load(fp)\n # frustum_angle is clockwise angle from positive x-axis\n self.frustum_angle_list = pickle.load(fp)\n self.prob_list = pickle.load(fp)\n self.calib_list = pickle.load(fp)\n\n else:\n with open(overwritten_data_path, 'rb') as fp:\n self.id_list = pickle.load(fp)\n self.box2d_list = pickle.load(fp)\n self.box3d_list = pickle.load(fp)\n self.input_list = pickle.load(fp)\n self.label_list = pickle.load(fp)\n self.type_list = pickle.load(fp)\n self.heading_list = pickle.load(fp)\n self.size_list = pickle.load(fp)\n # frustum_angle is clockwise angle from positive x-axis\n self.frustum_angle_list = pickle.load(fp)\n self.gt_box2d_list = pickle.load(fp)\n self.calib_list = pickle.load(fp)\n # MODIFICATION START - load ground truth centers\n self.center_3d_raw_kitti = pickle.load(fp)\n # MODIFICATION END - load ground truth centers\n\n if extend_from_det:\n extend_det_file = overwritten_data_path.replace('.', '_det.')\n assert os.path.exists(extend_det_file), extend_det_file\n with open(extend_det_file, 'rb') as fp:\n # extend\n self.id_list.extend(pickle.load(fp))\n self.box2d_list.extend(pickle.load(fp))\n self.box3d_list.extend(pickle.load(fp))\n self.input_list.extend(pickle.load(fp))\n self.label_list.extend(pickle.load(fp))\n self.type_list.extend(pickle.load(fp))\n self.heading_list.extend(pickle.load(fp))\n self.size_list.extend(pickle.load(fp))\n self.frustum_angle_list.extend(pickle.load(fp))\n self.gt_box2d_list.extend(pickle.load(fp))\n self.calib_list.extend(pickle.load(fp))\n # MODIFICATION START - load ground truth centers\n self.center_3d_raw_kitti.extend(pickle.load(fp))\n # MODIFICATION END - load ground truth centers\n logger.info('load dataset from {}'.format(extend_det_file))\n\n\n # print('Calib list P0 =', len(self.calib_list[0]['P0']))\n # print('Calib list P1 =', len(self.calib_list[0]['P1']))\n # print('Calib list P2 =', len(self.calib_list[0]['P2']))\n # print('Calib list P3 =', len(self.calib_list[0]['P3']))\n # print('Calib list = ', self.calib_list[0])\n # print('Calib list P0 =', self.calib_list[0]['P0'])\n\n center_len = len(self.center_3d_raw_kitti)\n \n # z = 0\n # o = 0\n # t = 0\n\n # for it in range(0, center_len):\n # noise = np.random.rand(1, 1)[0]*3\n\n # coin_flip = np.random.randint(0,2)\n\n # zval = self.center_3d_raw_kitti[it][2]\n\n # # Specify the noise (in meters) to add to the z axis of the center proposal to be fed into the pipeline\n # if coin_flip == 0:\n # if zval > 70 - noise:\n # self.center_3d_raw_kitti[it][2] -= noise\n # else:\n # self.center_3d_raw_kitti[it][2] += noise\n # else:\n # if zval < 0 + noise:\n # self.center_3d_raw_kitti[it][2] += noise\n # else:\n # self.center_3d_raw_kitti[it][2] -= noise \n\n # adding noise to the z value. center_3d_raw_kitti[i][2] = depth of i'th object or car in a scene\n \n # noise = np.random.normal(scale = 3, size = (center_len))\n # for it in range(0, center_len):\n # self.center_3d_raw_kitti[it][2] += noise[it]\n\n # if self.center_3d_raw_kitti[it][2] < 0:\n # self.center_3d_raw_kitti[it][2] = 0\n\n # elif self.center_3d_raw_kitti[it][2] > 70:\n # self.center_3d_raw_kitti[it][2] = 70\n\n # print('zeros = ', z)\n # print('ones = ', o)\n # print('twos = ', t)\n # print('Centers length after noise = ', len(self.center_3d_raw_kitti))\n # exit()\n\n logger.info('load dataset from {}'.format(overwritten_data_path))\n\n def __len__(self):\n return len(self.input_list)\n\n # MODIFICATION START - HEURISTIC FUNCTIONS\n\n def regress_to_find_center(self, point_cloud_arr, stride = .5):\n # print(point_cloud_arr.shape)\n # sorted_arr = point_cloud_arr[np.argsort(point_cloud_arr[:,2])]\n\n freq_dict = defaultdict(int)\n freq_dict_aggregate = defaultdict(int)\n \n for idx in range(len(point_cloud_arr)):\n bin_number = point_cloud_arr[idx][2] // stride\n freq_dict[bin_number] += 1 \n\n max_key = max(freq_dict, key=freq_dict.get)\n \n # print(float(max_key) * stride)\n return max_key * stride\n\n def regress_to_find_center_aggregate(self, point_cloud_arr, stride = 0.1, buckets_on_either_side = 2):\n freq_dict = defaultdict(int)\n # key = discrete z distance steps.\n # value = Number of pcl points that has z values at that step or bin.\n # bins are basically discrete z distance steps. Each step is separated by a stride of 0.5.\n # point_cloud_arr[idx][2] // stride finds exactly which \"step\" that certain point cloud goes to.\n # We also add that point cloud value to the steps that come just before and after too, to great a sort of weighted average.\n for idx in range(len(point_cloud_arr)):\n bin_number = np.round(point_cloud_arr[idx][2] / stride)\n freq_dict[bin_number] += 1\n for i in range(1, buckets_on_either_side + 1):\n freq_dict[bin_number - i] += 1\n freq_dict[bin_number + i] += 1\n # print(\"Aggregate dictionary\")\n # print(freq_dict)\n max_key = max(freq_dict, key=freq_dict.get)\n # find the key or \"discrete stride step\" which has the maximum value.\n # We multiply the step by the stride to get the original z value.\n return max_key * stride\n\n # MODIFICATION END - HEURISTIC FUNCTIONS\n\n\n def delta_error(self, power_i = 1):\n delta_threshold = 1.25 ** power_i\n\n total_cardinality = len(self.ground_truth_depth)\n success_case = 0\n fail_case = 0 \n\n for idx, val in enumerate(self.ground_truth_depth):\n ground_truth_instance = self.ground_truth_depth[idx]\n estimated_depth_instance = self.estimated_depth[idx]\n\n max_dif = np.maximum( (estimated_depth_instance / ground_truth_instance), (ground_truth_instance / estimated_depth_instance )) \n\n if max_dif > delta_threshold:\n fail_case += 1 \n else:\n success_case += 1\n\n delta_value = (success_case / total_cardinality) * 100\n \n return delta_value\n\n\n def __getitem__(self, index):\n\n rotate_to_center = cfg.DATA.RTC\n with_extra_feat = cfg.DATA.WITH_EXTRA_FEAT\n\n ''' Get index-th element from the picked file dataset. '''\n # ------------------------------ INPUTS ----------------------------\n rot_angle = self.get_center_view_rot_angle(index)\n\n cls_type = self.type_list[index]\n # assert cls_type in KITTICategory.CLASSES, cls_type\n # size_class = KITTICategory.CLASSES.index(cls_type)\n\n assert cls_type in self.category_info.CLASSES, '%s not in category_info' % cls_type\n size_class = self.category_info.CLASSES.index(cls_type)\n\n # Compute one hot vector\n if self.one_hot:\n one_hot_vec = np.zeros((len(self.category_info.CLASSES)))\n one_hot_vec[size_class] = 1\n\n # Get point cloud\n if rotate_to_center:\n point_set = self.get_center_view_point_set(index)\n else:\n point_set = self.input_list[index]\n\n if not with_extra_feat:\n point_set = point_set[:, :3]\n\n # MODIFICATION START - RUN HEURISTIC FUNCTION AND EVALUATE\n # z_sliding_window_regress = self.regress_to_find_center(point_set, cfg.HEURISTIC_STRIDE)\n z_sliding_window_regress = self.regress_to_find_center_aggregate(point_set, cfg.HEURISTIC_STRIDE, cfg.HEURISTIC_BUCKETS)\n\n self.estimated_depth = np.append(self.estimated_depth, z_sliding_window_regress)\n self.ground_truth_depth = np.append(self.ground_truth_depth, self.center_3d_raw_kitti[index][2])\n \n\n # z_sliding_window_regress = self.center_3d_raw_kitti[index][2]\n \n # print('Heuristic stride = ' + str(cfg.HEURISTIC_STRIDE))\n # print('Heuristic buckets = ' + str(cfg.HEURISTIC_BUCKETS))\n \n ### START CODE FOR EVALUATING HEURISTIC\n \n # self.errorMargins = np.append(self.errorMargins, np.absolute(z_sliding_window_regress - self.center_3d_raw_kitti[index][2]))\n \n if (index > 0.999 * len(self.input_list)) and (self.printPercentiles is False):\n rmse = np.sqrt((np.square(self.ground_truth_depth - self.estimated_depth)).mean())\n\n rle = np.abs(np.subtract(self.estimated_depth, self.ground_truth_depth) / self.ground_truth_depth).mean() * 100\n\n de = self.delta_error()\n\n errorFile = open('heuristic_eval/errors', 'w+')\n\n writeData = dict()\n\n writeData['rmse'] = rmse\n writeData['rel'] = rle\n writeData['del'] = de\n json.dump(writeData, errorFile)\n errorFile.close()\n\n # # print('PERCENTILES = ' + str(np.percentile(self.errorMargins, [5*x for x in range(0, 21)])))\n # self.printPercentiles = True\n # # print(os.getcwd())\n # writeData = dict()\n # writeData['heuristic_stride'] = cfg.HEURISTIC_STRIDE\n # writeData['heuristic_buckets'] = cfg.HEURISTIC_BUCKETS\n # writeData['percentiles'] = list(np.percentile(self.errorMargins, [5*x for x in range(0, 21)]))\n \n # percentileFile = open('heuristic_eval/error_percentiles_' + str(cfg.HEURISTIC_STRIDE) + '_' + str(cfg.HEURISTIC_BUCKETS) + '.json', 'w+')\n \n # json.dump(writeData, percentileFile)\n\n # # percentileFile.write('Heuristic stride = ' + str(cfg.HEURISTIC_STRIDE))\n # # percentileFile.write('\\nHeuristic buckets = ' + str(cfg.HEURISTIC_BUCKETS))\n # # percentileFile.write('\\nPERCENTILES FOR [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] = ' + str(np.percentile(self.errorMargins, [5*x for x in range(0, 21)])))\n \n # percentileFile.close()\n # # plt.plot(errorBuckets, self.errorMargins)\n # # plt.show()\n exit(69420)\n\n ### END CODE FOR EVALUATING HEURISTIC\n\n # MODIFICATION END - RUN HEURISTIC FUNCTION AND EVALUATE\n\n # Resample\n if self.npoints > 0:\n # choice = np.random.choice(point_set.shape[0], self.npoints, replace=True)\n choice = np.random.choice(point_set.shape[0], self.npoints, point_set.shape[0] < self.npoints)\n\n else:\n choice = np.random.permutation(len(point_set.shape[0]))\n\n point_set = point_set[choice, :]\n\n box = self.box2d_list[index]\n P = self.calib_list[index]['P2'].reshape(3, 4)\n\n # MODIFICATION START - PASS GENERATED Z VALUES TO GENERATE REF\n ref1, ref2, ref3, ref4 = self.generate_ref(box, P, z_sliding_window_regress)\n # MODIFICATION END - PASS GENERATED Z VALUES TO GENERATE REF\n\n if rotate_to_center:\n ref1 = self.get_center_view(ref1, index)\n ref2 = self.get_center_view(ref2, index)\n ref3 = self.get_center_view(ref3, index)\n ref4 = self.get_center_view(ref4, index)\n\n if self.from_rgb_detection:\n\n data_inputs = {\n 'point_cloud': torch.FloatTensor(point_set).transpose(1, 0),\n 'rot_angle': torch.FloatTensor([rot_angle]),\n 'rgb_prob': torch.FloatTensor([self.prob_list[index]]),\n 'center_ref1': torch.FloatTensor(ref1).transpose(1, 0),\n 'center_ref2': torch.FloatTensor(ref2).transpose(1, 0),\n 'center_ref3': torch.FloatTensor(ref3).transpose(1, 0),\n 'center_ref4': torch.FloatTensor(ref4).transpose(1, 0),\n\n }\n\n if not rotate_to_center:\n data_inputs.update({'rot_angle': torch.zeros(1)})\n\n if self.one_hot:\n data_inputs.update({'one_hot': torch.FloatTensor(one_hot_vec)})\n\n return data_inputs\n\n # ------------------------------ LABELS ----------------------------\n seg = self.label_list[index].astype(np.int64)\n seg = seg[choice]\n\n # Get center point of 3D box\n if rotate_to_center:\n box3d_center = self.get_center_view_box3d_center(index)\n else:\n box3d_center = self.get_box3d_center(index)\n\n # Heading\n if rotate_to_center:\n heading_angle = self.heading_list[index] - rot_angle\n else:\n heading_angle = self.heading_list[index]\n\n box3d_size = self.size_list[index]\n\n # Size\n if self.random_flip:\n # note: rot_angle won't be correct if we have random_flip\n # so do not use it in case of random flipping.\n if np.random.random() > 0.5: # 50% chance flipping\n point_set[:, 0] *= -1\n box3d_center[0] *= -1\n heading_angle = np.pi - heading_angle\n\n ref1[:, 0] *= -1\n ref2[:, 0] *= -1\n ref3[:, 0] *= -1\n ref4[:, 0] *= -1\n\n if self.random_shift:\n max_depth = cfg.DATA.MAX_DEPTH\n l, w, h = self.size_list[index]\n dist = np.sqrt(np.sum(l ** 2 + w ** 2))\n shift = np.clip(np.random.randn() * dist * 0.2, -0.5 * dist, 0.5 * dist)\n shift = np.clip(shift + box3d_center[2], 0, max_depth) - box3d_center[2]\n point_set[:, 2] += shift\n box3d_center[2] += shift\n\n labels_ref2 = self.generate_labels(box3d_center, box3d_size, heading_angle, ref2, P)\n\n data_inputs = {\n 'point_cloud': torch.FloatTensor(point_set).transpose(1, 0),\n 'rot_angle': torch.FloatTensor([rot_angle]),\n 'center_ref1': torch.FloatTensor(ref1).transpose(1, 0),\n 'center_ref2': torch.FloatTensor(ref2).transpose(1, 0),\n 'center_ref3': torch.FloatTensor(ref3).transpose(1, 0),\n 'center_ref4': torch.FloatTensor(ref4).transpose(1, 0),\n\n 'cls_label': torch.LongTensor(labels_ref2),\n 'box3d_center': torch.FloatTensor(box3d_center),\n 'box3d_heading': torch.FloatTensor([heading_angle]),\n 'box3d_size': torch.FloatTensor(box3d_size),\n 'size_class': torch.LongTensor([size_class]),\n 'seg_label': torch.LongTensor(seg.astype(np.int64))\n }\n\n if not rotate_to_center:\n data_inputs.update({'rot_angle': torch.zeros(1)})\n\n if self.one_hot:\n data_inputs.update({'one_hot': torch.FloatTensor(one_hot_vec)})\n\n return data_inputs\n\n # This generates labels for each point in the point cloud.\n # There are three possible labels.\n # 0 = point is outside the bounding box\n # -1 = point is inside the standard bounding box (l,w,h)\n # 1 = point is inside the reduced bounding box (l/2, w/2, h/2)\n def generate_labels(self, center, dimension, angle, ref_xyz, P):\n box_corner1 = compute_box_3d(center, dimension * 0.5, angle)\n box_corner2 = compute_box_3d(center, dimension, angle)\n\n labels = np.zeros(len(ref_xyz))\n inside1 = extract_pc_in_box3d(ref_xyz, box_corner1)\n inside2 = extract_pc_in_box3d(ref_xyz, box_corner2)\n\n labels[inside2] = -1\n labels[inside1] = 1\n # dis = np.sqrt(((ref_xyz - center)**2).sum(1))\n # print(dis.min())\n if inside1.sum() == 0:\n dis = np.sqrt(((ref_xyz - center) ** 2).sum(1))\n argmin = np.argmin(dis)\n labels[argmin] = 1\n\n return labels\n\n # MODIFICATION START - RETURN DEPTH BOUNDS TO SEARCH\n def resolve_centers_z(self, z_sliding_window_regress):\n lower = max(0, z_sliding_window_regress - cfg.DATA.SEARCH_WINDOW)\n upper = min(70, z_sliding_window_regress + cfg.DATA.SEARCH_WINDOW)\n\n if z_sliding_window_regress < cfg.DATA.SEARCH_WINDOW:\n upper += cfg.DATA.SEARCH_WINDOW - z_sliding_window_regress\n\n if z_sliding_window_regress > 70 - cfg.DATA.SEARCH_WINDOW:\n lower -= z_sliding_window_regress - (70 - cfg.DATA.SEARCH_WINDOW)\n return lower, upper\n # MODIFICATION END - RETURN DEPTH BOUNDS TO SEARCH\n\n def generate_ref(self, box, P, z_sliding_window_regress):\n\n s1, s2, s3, s4 = cfg.DATA.STRIDE\n # MODIFIATION START - GENERATE DEPTH BOUNDS FOR SEARCHING\n z_sliding_window_regress = np.floor(z_sliding_window_regress)\n lower, upper = self.resolve_centers_z(z_sliding_window_regress) # Modified z axis bounds\n # MODIFICATION END - GENERATE DEPTH BOUNDS FOR SEARCHING\n\n # MODIFICATION START - SEARCH THROUGH GENERATED DEPTH BOUNDS INSTEAD OF 70M\n z1 = np.arange(lower, upper, s1) + s1 / 2.\n z2 = np.arange(lower, upper, s2) + s2 / 2.\n z3 = np.arange(lower, upper, s3) + s3 / 2.\n z4 = np.arange(lower, upper, s4) + s4 / 2.\n # MODIFICATION END - SEARCH THROUGH GENERATED DEPTH BOUNDS INSTEAD OF 70M\n\n cx, cy = (box[0] + box[2]) / 2., (box[1] + box[3]) / 2.,\n\n xyz1 = np.zeros((len(z1), 3))\n xyz1[:, 0] = cx\n xyz1[:, 1] = cy\n xyz1[:, 2] = z1\n xyz1_rect = project_image_to_rect(xyz1, P)\n\n xyz2 = np.zeros((len(z2), 3))\n xyz2[:, 0] = cx\n xyz2[:, 1] = cy\n xyz2[:, 2] = z2\n xyz2_rect = project_image_to_rect(xyz2, P)\n\n xyz3 = np.zeros((len(z3), 3))\n xyz3[:, 0] = cx\n xyz3[:, 1] = cy\n xyz3[:, 2] = z3\n xyz3_rect = project_image_to_rect(xyz3, P)\n\n xyz4 = np.zeros((len(z4), 3))\n xyz4[:, 0] = cx\n xyz4[:, 1] = cy\n xyz4[:, 2] = z4\n xyz4_rect = project_image_to_rect(xyz4, P)\n\n return xyz1_rect, xyz2_rect, xyz3_rect, xyz4_rect\n\n def get_center_view_rot_angle(self, index):\n ''' Get the frustum rotation angle, it isshifted by pi/2 so that it\n can be directly used to adjust GT heading angle '''\n return np.pi / 2.0 + self.frustum_angle_list[index]\n\n def get_box3d_center(self, index):\n ''' Get the center (XYZ) of 3D bounding box. '''\n box3d_center = (self.box3d_list[index][0, :] +\n self.box3d_list[index][6, :]) / 2.0\n return box3d_center\n\n def get_center_view_box3d_center(self, index):\n ''' Frustum rotation of 3D bounding box center. '''\n box3d_center = (self.box3d_list[index][0, :] +\n self.box3d_list[index][6, :]) / 2.0\n return rotate_pc_along_y(np.expand_dims(box3d_center, 0),\n self.get_center_view_rot_angle(index)).squeeze()\n\n def get_center_view_box3d(self, index):\n ''' Frustum rotation of 3D bounding box corners. '''\n box3d = self.box3d_list[index]\n box3d_center_view = np.copy(box3d)\n return rotate_pc_along_y(box3d_center_view,\n self.get_center_view_rot_angle(index))\n\n def get_center_view_point_set(self, index):\n ''' Frustum rotation of point clouds.\n NxC points with first 3 channels as XYZ\n z is facing forward, x is left ward, y is downward\n '''\n # Use np.copy to avoid corrupting original data\n point_set = np.copy(self.input_list[index])\n return rotate_pc_along_y(point_set,\n self.get_center_view_rot_angle(index))\n\n def get_center_view(self, point_set, index):\n ''' Frustum rotation of point clouds.\n NxC points with first 3 channels as XYZ\n z is facing forward, x is left ward, y is downward\n '''\n # Use np.copy to avoid corrupting original data\n point_set = np.copy(point_set)\n return rotate_pc_along_y(point_set,\n self.get_center_view_rot_angle(index))\n\n\ndef from_prediction_to_label_format(center, angle, size, rot_angle, ref_center=None):\n ''' Convert predicted box parameters to label format. '''\n l, w, h = size\n ry = angle + rot_angle\n tx, ty, tz = rotate_pc_along_y(np.expand_dims(center, 0), -rot_angle).squeeze()\n\n if ref_center is not None:\n tx = tx + ref_center[0]\n ty = ty + ref_center[1]\n tz = tz + ref_center[2]\n\n ty += h / 2.0\n return h, w, l, tx, ty, tz, ry\n\ndef compute_alpha(x, z, ry):\n\n beta = np.arctan2(z, x)\n alpha = -np.sign(beta) * np.pi / 2 + beta + ry\n\n return alpha\n\ndef collate_fn(batch):\n return default_collate(batch)\n\n\nif __name__ == '__main__':\n\n cfg.DATA.DATA_ROOT = 'kitti/data/pickle_data'\n cfg.DATA.RTC = True\n dataset = ProviderDataset(1024, split='val', random_flip=True, one_hot=True, random_shift=True)\n\n for i in range(len(dataset)):\n data = dataset[i]\n\n for name, value in data.items():\n print(name, value.shape)\n\n input()\n\n '''\n train_loader = torch.utils.data.DataLoader(\n dataset, batch_size=4, shuffle=False, num_workers=4, pin_memory=True, drop_last=True)\n tic = time.time()\n for i, data_dict in enumerate(train_loader):\n\n # for key, value in data_dict.items():\n # print(key, value.shape)\n\n print(time.time() - tic)\n tic = time.time()\n\n # input()\n '''\n"
] |
[
[
"numpy.expand_dims",
"torch.zeros",
"numpy.arctan2",
"numpy.round",
"torch.FloatTensor",
"numpy.argmin",
"numpy.random.randn",
"numpy.square",
"numpy.clip",
"numpy.arange",
"numpy.subtract",
"numpy.copy",
"torch.utils.data.dataloader.default_collate",
"torch.LongTensor",
"numpy.random.choice",
"numpy.append",
"numpy.floor",
"numpy.sum",
"numpy.maximum",
"numpy.random.random",
"numpy.sign",
"numpy.empty"
]
] |
cycleke/FaceRecognition
|
[
"c7882ca88b5d7d4bb51aa0852c5225f13f20728c"
] |
[
"utils/core/recognizer.py"
] |
[
"# *-* coding: utf-8 *-*\n\nimport os\n\nimport cv2\nimport dlib\nimport numpy as np\n\n\nclass Recognizer:\n \"\"\"\n Recognise faces\n \"\"\"\n\n def __init__(\n self,\n *,\n threshold=0.6,\n predictor_path=\"static/shape_predictor_68_face_landmarks.dat\",\n face_rec_model_path=\"static/dlib_face_recognition_resnet_model_v1.dat\",\n ):\n self.detector = dlib.get_frontal_face_detector()\n self.shape_predictor = dlib.shape_predictor(predictor_path)\n self.model = dlib.face_recognition_model_v1(face_rec_model_path)\n\n self.threshold = threshold\n self.face_descriptors = {}\n\n def load_data(self, dataset=\"dataset\"):\n \"\"\"\n Load dataset with .npz files\n\n :param dataset: the path of dataset\n :return: None\n \"\"\"\n self.face_descriptors = {}\n if os.path.exists(dataset):\n for faces in os.listdir(dataset):\n file_name, extension = os.path.splitext(faces)\n if extension != \".npy\":\n continue\n descriptors = np.load(os.path.join(dataset, faces))\n if descriptors.any():\n self.face_descriptors[file_name] = descriptors.copy()\n\n def find_match_face(self, face_descriptor):\n \"\"\"\n Find the best matched face.\n :param face_descriptor: the descriptor of the face to match\n :return: the name of the face\n \"\"\"\n min_dist = self.threshold + 1\n min_dist_face = \"unknown\"\n face_descriptor = np.array(face_descriptor)\n\n for iter in self.face_descriptors.items():\n dist = np.linalg.norm(\n iter[1] - face_descriptor, axis=1, keepdims=True\n ).sum() / len(iter[1])\n\n if dist < min_dist:\n min_dist = dist\n min_dist_face = iter[0]\n\n if min_dist < self.threshold:\n return min_dist_face\n else:\n return \"unknown\"\n\n def recognise_image(self, image):\n \"\"\"\n Recognise the image\n\n :param image: the image to recognise\n :return: img the recognised image\n \"\"\"\n img = image.copy()\n dets = self.detector(img, 1)\n for k, d in enumerate(dets):\n shape = self.shape_predictor(img, d)\n face_descriptor = self.model.compute_face_descriptor(img, shape)\n\n class_pre = self.find_match_face(face_descriptor)\n cv2.rectangle(\n img, (d.left(), d.top() + 10), (d.right(), d.bottom()), (0, 255, 0), 2\n )\n cv2.putText(\n img,\n class_pre,\n (d.left(), d.top()),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.7,\n (0, 255, 0),\n 2,\n cv2.LINE_AA,\n )\n return img\n\n def add_face(self, name, count=20, dataset=\"dataset\"):\n \"\"\"\n Add some faces from camera with given name\n\n :param name: the name of adding faces\n :param count: the number of images array to save\n :param dataset: the path of the dataset\n :return: None\n \"\"\"\n\n if not os.path.exists(dataset):\n os.mkdir(dataset)\n\n capture = cv2.VideoCapture(0)\n\n if not capture.isOpened():\n raise RuntimeError(\"Unable to open the camera\")\n\n added = 0\n face_descriptors = []\n while added < count:\n success, frame = capture.read()\n\n if not success:\n continue\n\n dets = self.detector(frame, 1)\n\n if frame.shape[0] * frame.shape[1] > 500000:\n frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)\n\n max_d = None\n\n def area(rect):\n height = rect.top() - rect.bottom()\n width = rect.right() - rect.left()\n return height * width\n\n for k, d in enumerate(dets):\n if (not max_d) or (area(d) > area(max_d)):\n max_d = d\n\n # print(type(max_d))\n if max_d:\n shape = self.shape_predictor(frame, max_d)\n descriptor = self.model.compute_face_descriptor(frame, shape)\n face_descriptors.append(descriptor)\n added += 1\n cv2.rectangle(\n frame,\n (max_d.left(), max_d.top() + 10),\n (max_d.right(), max_d.bottom()),\n (0, 255, 0),\n 2,\n )\n cv2.imshow(\"Adding Faces\", frame)\n cv2.waitKey(1)\n\n self.face_descriptors[name] = face_descriptors\n\n np.save(os.path.join(dataset, name), np.array(face_descriptors))\n cv2.destroyAllWindows()\n capture.release()\n\n\nif __name__ == \"__main__\":\n recognition = Recognizer()\n recognition.add_face(\"TEST\")\n\n capture = cv2.VideoCapture(0)\n\n while True:\n success, frame = capture.read()\n image = recognition.recognise_image(frame)\n\n cv2.imshow(\"images\", image)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n"
] |
[
[
"numpy.array",
"numpy.linalg.norm"
]
] |
ahmedbesbes/character-based-cnn
|
[
"593197610498bf0b4898b3bdf2e1f6730f954613"
] |
[
"src/model.py"
] |
[
"import json\nimport torch\nimport torch.nn as nn\n\n\nclass CharacterLevelCNN(nn.Module):\n def __init__(self, args, number_of_classes):\n super(CharacterLevelCNN, self).__init__()\n\n # define conv layers\n\n self.dropout_input = nn.Dropout2d(args.dropout_input)\n\n self.conv1 = nn.Sequential(\n nn.Conv1d(\n args.number_of_characters + len(args.extra_characters),\n 256,\n kernel_size=7,\n padding=0,\n ),\n nn.ReLU(),\n nn.MaxPool1d(3),\n )\n\n self.conv2 = nn.Sequential(\n nn.Conv1d(256, 256, kernel_size=7, padding=0), nn.ReLU(), nn.MaxPool1d(3)\n )\n\n self.conv3 = nn.Sequential(\n nn.Conv1d(256, 256, kernel_size=3, padding=0), nn.ReLU()\n )\n\n self.conv4 = nn.Sequential(\n nn.Conv1d(256, 256, kernel_size=3, padding=0), nn.ReLU()\n )\n\n self.conv5 = nn.Sequential(\n nn.Conv1d(256, 256, kernel_size=3, padding=0), nn.ReLU()\n )\n\n self.conv6 = nn.Sequential(\n nn.Conv1d(256, 256, kernel_size=3, padding=0), nn.ReLU(), nn.MaxPool1d(3)\n )\n\n # compute the output shape after forwarding an input to the conv layers\n\n input_shape = (\n 128,\n args.max_length,\n args.number_of_characters + len(args.extra_characters),\n )\n self.output_dimension = self._get_conv_output(input_shape)\n\n # define linear layers\n\n self.fc1 = nn.Sequential(\n nn.Linear(self.output_dimension, 1024), nn.ReLU(), nn.Dropout(0.5)\n )\n\n self.fc2 = nn.Sequential(nn.Linear(1024, 1024), nn.ReLU(), nn.Dropout(0.5))\n\n self.fc3 = nn.Linear(1024, number_of_classes)\n\n # initialize weights\n\n self._create_weights()\n\n # utility private functions\n\n def _create_weights(self, mean=0.0, std=0.05):\n for module in self.modules():\n if isinstance(module, nn.Conv1d) or isinstance(module, nn.Linear):\n module.weight.data.normal_(mean, std)\n\n def _get_conv_output(self, shape):\n x = torch.rand(shape)\n x = x.transpose(1, 2)\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.conv5(x)\n x = self.conv6(x)\n x = x.view(x.size(0), -1)\n output_dimension = x.size(1)\n return output_dimension\n\n # forward\n\n def forward(self, x):\n x = self.dropout_input(x)\n x = x.transpose(1, 2)\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.conv5(x)\n x = self.conv6(x)\n x = x.view(x.size(0), -1)\n x = self.fc1(x)\n x = self.fc2(x)\n x = self.fc3(x)\n return x\n"
] |
[
[
"torch.nn.Dropout",
"torch.nn.Dropout2d",
"torch.nn.Linear",
"torch.nn.MaxPool1d",
"torch.rand",
"torch.nn.Conv1d",
"torch.nn.ReLU"
]
] |
bryan-flywire/openem
|
[
"1510ecbbb6b4a43b9f1f9503c87ec66216200677"
] |
[
"train/openem_train/classify.py"
] |
[
"__copyright__ = \"Copyright (C) 2018 CVision AI.\"\n__license__ = \"GPLv3\"\n# This file is part of OpenEM, released under GPLv3.\n# OpenEM is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with OpenEM. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"Functions for training classification algorithm.\n\"\"\"\n\nimport os\nimport glob\nimport sys\nimport pandas as pd\n\ndef _save_model(config, model):\n \"\"\"Loads best weights and converts to protobuf file.\n\n # Arguments\n config: ConfigInterface object.\n model: Keras Model object.\n \"\"\"\n from openem_train.util.model_utils import keras_to_tensorflow\n if config.classify_do_validation():\n best = glob.glob(os.path.join(config.checkpoints_dir('classify'), '*best*'))\n else:\n best = glob.glob(os.path.join(config.checkpoints_dir('classify'), '*periodic*'))\n latest = max(best, key=os.path.getctime)\n model.load_weights(latest)\n os.makedirs(config.classify_model_dir(), exist_ok=True)\n keras_to_tensorflow(model, ['cat_species_1', 'cat_cover_1'], config.classify_model_path())\n\ndef train(config):\n \"\"\"Trains classification model.\n\n # Arguments\n config: ConfigInterface object.\n \"\"\"\n # Import keras.\n from keras.callbacks import ModelCheckpoint\n from keras.callbacks import TensorBoard\n from keras.callbacks import LearningRateScheduler\n from openem_train.inception.inception import inception_model\n from openem_train.inception.inception_dataset import InceptionDataset\n from openem_train.util.utils import find_epoch\n\n # Create tensorboard and checkpoints directories.\n tensorboard_dir = config.tensorboard_dir('classify')\n os.makedirs(config.checkpoints_dir('classify'), exist_ok=True)\n os.makedirs(tensorboard_dir, exist_ok=True)\n\n # Build the inception model.\n model = inception_model(\n input_shape=(config.classify_height(), config.classify_width(), 3),\n num_classes=config.num_classes())\n\n # If initial epoch is nonzero we load the model from checkpoints \n # directory.\n initial_epoch = config.classify_initial_epoch()\n if initial_epoch != 0:\n checkpoint = find_epoch(\n config.checkpoints_dir('classify'),\n initial_epoch\n )\n model.load_weights(checkpoint)\n\n # Set up dataset interface.\n dataset = InceptionDataset(config)\n\n # Define learning rate schedule.\n def schedule(epoch):\n if epoch < 1:\n return 5e-4\n if epoch < 5:\n return 3e-4\n if epoch < 10:\n return 1e-4\n if epoch < 20:\n return 5e-5\n return 1e-5\n\n # Set trainable layers.\n for layer in model.layers:\n layer.trainable = True\n\n # Set up callbacks.\n checkpoint_best = ModelCheckpoint(\n config.checkpoint_best('classify'),\n verbose=1,\n save_weights_only=False,\n save_best_only=True)\n\n checkpoint_periodic = ModelCheckpoint(\n config.checkpoint_periodic('classify'),\n verbose=1,\n save_weights_only=False,\n period=1)\n\n tensorboard = TensorBoard(\n tensorboard_dir,\n histogram_freq=0,\n write_graph=False,\n write_images=True)\n\n lr_sched = LearningRateScheduler(schedule=schedule)\n\n # Determine steps per epoch.\n batch_size = config.classify_batch_size()\n steps_per_epoch = config.classify_steps_per_epoch()\n if not steps_per_epoch:\n steps_per_epoch = dataset.train_batches(config.classify_batch_size())\n\n # Set up validation generator.\n validation_gen = None\n validation_steps = None\n if config.classify_do_validation():\n validation_gen = dataset.generate_test(\n batch_size=config.classify_val_batch_size()\n )\n validation_steps = dataset.test_batches(\n config.classify_val_batch_size()\n )\n\n # Fit the model.\n model.summary()\n model.fit_generator(\n dataset.generate(batch_size=config.classify_batch_size()),\n steps_per_epoch=steps_per_epoch,\n epochs=config.classify_num_epochs(),\n verbose=1,\n callbacks=[\n checkpoint_best,\n checkpoint_periodic,\n tensorboard,\n lr_sched\n ],\n validation_data=validation_gen,\n validation_steps=validation_steps,\n initial_epoch=initial_epoch\n )\n\n # Save the model.\n _save_model(config, model)\n\ndef predict(config):\n \"\"\"Runs classification model on extracted detections.\n\n # Arguments\n config: ConfigInterface object.\n \"\"\"\n # Import deployment library.\n sys.path.append('../python')\n import openem\n\n # Make a dict to contain classification results.\n class_data = {\n 'video_id' : [],\n 'frame' : [],\n 'no_fish' : [],\n 'covered' : [],\n 'clear' : []\n }\n species_list = ['_',] + config.species()\n for spc in species_list:\n class_data['species_' + spc] = []\n\n # Initialize classifier from deployment library.\n classifier = openem.Classifier()\n status = classifier.Init(config.classify_model_path())\n if not status == openem.kSuccess:\n raise IOError(\"Failed to initialize detector!\")\n w, h = classifier.ImageSize()\n\n for img_path in config.train_dets():\n\n # Get video id from path.\n path, fname = os.path.split(img_path)\n frame, _ = os.path.splitext(fname)\n video_id = os.path.basename(os.path.normpath(path))\n\n\n # Load in image.\n img = openem.Image()\n status = img.FromFile(img_path)\n if not status == openem.kSuccess:\n raise IOError(\"Failed to load image {}\".format(img_path))\n img.Resize(w, h)\n\n # Add image to processing queue.\n status = classifier.AddImage(img)\n if not status == openem.kSuccess:\n raise RuntimeError(\"Failed to load image {}\".format(img_path))\n\n # Process loaded image.\n scores = openem.VectorClassification()\n status = classifier.Process(scores)\n if not status == openem.kSuccess:\n raise RuntimeError(\"Failed to process image {}!\".format(img_path))\n\n # Write classification results.\n for score in scores:\n class_data['video_id'].append(video_id)\n class_data['frame'].append(int(frame))\n for spc, spc_score in zip(species_list, score.species):\n class_data['species_' + spc].append(spc_score)\n class_data['no_fish'].append(score.cover[0])\n class_data['covered'].append(score.cover[1])\n class_data['clear'].append(score.cover[2])\n print(\"Finished classification on {}\".format(img_path))\n\n # Write classification results to csv.\n os.makedirs(config.inference_dir(), exist_ok=True)\n d = pd.DataFrame(class_data)\n d.to_csv(config.classify_inference_path(), index=False)\n"
] |
[
[
"pandas.DataFrame"
]
] |
JonSn0w/advent-of-code
|
[
"f62636ef975dd89d788cba66578d16e07b70d7e9"
] |
[
"2017/day10p2.py"
] |
[
"import numpy as np;\nRNG = 256;\n\ndef partOne(seq, num_lst, pos, skip):\n\tlst_len = len(num_lst)\n\tcurr_pos = pos\n\tskip_size = skip\n\tlengths = seq.split(',')\n\n\tfor leng in lengths:\n\t\tleng = int(leng.strip())\n\t\tif leng > lst_len:\n\t\t\tcontinue\n\t\trev_end = (curr_pos + leng) % lst_len\n\t\tif rev_end == 0:\n\t\t\trev_end = lst_len\n\t\tinds = list(range(curr_pos, rev_end))\n\t\tif leng > 0 and rev_end <= curr_pos:\n\t\t\tinds = list(range(curr_pos, lst_len)) + list(range(rev_end)) \n\n\t\tnum_lst[inds] = np.flipud(num_lst[inds]) \n\t\tcurr_pos = (curr_pos + leng + skip_size) % lst_len\n\t\tskip_size += 1\n\n\treturn num_lst[0] * num_lst[1], num_lst, curr_pos, skip_size\n\n\ndef partTwo(seq):\n\tsp = np.array(range(RNG))\n\tpos, skip, blockSize = 0, 0, 16;\n\tdense = []\n\tbyt = ''.join([str(ord(char)) + ',' for char in seq.strip()]);\n\tbyt += \"17,31,73,47,23\";\n\n\tfor i in range(64):\n\t\tmult, sp, pos, skip = partOne(byt, sp, pos, skip);\n\tfor block in range(0, RNG, blockSize):\n\t\txored = 0;\n\t\tfor i in range(block, block + blockSize): \n\t\t\t\txored ^= sp[i];\n\t\tdense.append(xored);\n\treturn ''.join([('0' + format(num, 'x'))[-2:] for num in dense]);"
] |
[
[
"numpy.flipud"
]
] |
dlvu/vugrad
|
[
"dabb7fba29f1727c170bc5f37dff5f52adc62536"
] |
[
"experiments/train_mlp.py"
] |
[
"from _context import vugrad\n\nimport numpy as np\n\n# for running from the command line\nfrom argparse import ArgumentParser\n\nimport vugrad as vg\n\n# Parse command line arguments\nparser = ArgumentParser()\n\nparser.add_argument('-D', '--dataset',\n dest='data',\n help='Which dataset to use. [synth, mnist]',\n default='synth', type=str)\n\nparser.add_argument('-b', '--batch-size',\n dest='batch_size',\n help='The batch size (how many instances to use for a single forward/backward pass).',\n default=128, type=int)\n\nparser.add_argument('-e', '--epochs',\n dest='epochs',\n help='The number of epochs (complete passes over the complete training data).',\n default=20, type=int)\n\nparser.add_argument('-l', '--learning-rate',\n dest='lr',\n help='The learning rate. That is, a scalar that determines the size of the steps taken by the '\n 'gradient descent algorithm. 0.1 works well for synth, 0.0001 works well for MNIST.',\n default=0.01, type=float)\n\nargs = parser.parse_args()\n\n## Load the data\nif args.data == 'synth':\n (xtrain, ytrain), (xval, yval), num_classes = vg.load_synth()\nelif args.data == 'mnist':\n (xtrain, ytrain), (xval, yval), num_classes = vg.load_mnist(final=False, flatten=True)\nelse:\n raise Exception(f'Dataset {args.data} not recognized.')\n\nprint(f'## loaded data:')\nprint(f' number of instances: {xtrain.shape[0]} in training, {xval.shape[0]} in validation')\nprint(f' training class distribution: {np.bincount(ytrain)}')\nprint(f' val. class distribution: {np.bincount(yval)}')\n\nnum_instances, num_features = xtrain.shape\n\n## Create the model.\nmlp = vg.MLP(input_size=num_features, output_size=num_classes)\n\nn, m = xtrain.shape\nb = args.batch_size\n\nprint('\\n## Starting training')\n\ncl = '...'\n\nfor epoch in range(args.epochs):\n\n print(f'epoch {epoch:03}')\n\n if epoch % 1 == 0:\n ## Compute validation accuracy\n\n o = mlp(vg.TensorNode(xval))\n oval = o.value\n\n predictions = np.argmax(oval, axis=1)\n num_correct = (predictions == yval).sum()\n acc = num_correct / yval.shape[0]\n\n o.clear() # gc the computation graph\n\n print(f' accuracy: {acc:.4}')\n\n cl = 0.0 # running sum of the training loss\n\n # We loop over the data in batches of size `b`\n for fr in range(0, n, b):\n\n # The end index of the batch\n to = min(fr + b, n)\n\n # Slice out the batch and its corresponding target values\n batch, targets = xtrain[fr:to, :], ytrain[fr:to]\n\n # Wrap the inputs in a Node\n batch = vg.TensorNode(value=batch)\n\n outputs = mlp(batch)\n loss = vg.celoss(outputs, targets)\n # -- The computation graph is now complete. It consists of the mlp, together with the computation of\n # the scalar loss.\n # -- The variable `loss` is the TreeNode at the very top of our computation graph. This means we can call\n # it to perform operations on the computation graph, like clearing the gradients, starting the backpropgation\n # and clearing the graph.\n\n cl += loss.value\n # -- We must be careful here to extract the _raw_ value for the running loss. What would happen if we kept\n # a running sum using the TensorNode?\n\n # Start the backpropagation\n loss.backward()\n\n # pply gradient descent\n for parm in mlp.parameters():\n parm.value -= args.lr * parm.grad\n # -- Note that we are directly manipulating the members of the parm TensorNode. This means that for this\n # part, we are not building up a computation graph.\n\n # -- In Pytorch, the gradient descent is abstracted away into an Optimizer. This allows us to build slightly more\n # complexoptimizers than plain graident descent.\n\n # Finally, we need to reset the gradients to zero ...\n loss.zero_grad()\n # ... and delete the parts of the computation graph we don't need to remember.\n loss.clear()\n\n print(f' running loss: {cl:.4}')\n"
] |
[
[
"numpy.argmax",
"numpy.bincount"
]
] |
jinjiaodawang/bayesmark
|
[
"4fbf52c41288ec802cc03c23372e81d2b678ecb9"
] |
[
"example_opt_root/bo/models/rf/rf.py"
] |
[
"# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\r\n\r\n# This program is free software; you can redistribute it and/or modify it under\r\n# the terms of the MIT license.\r\n\r\n# This program is distributed in the hope that it will be useful, but WITHOUT ANY\r\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\r\n# PARTICULAR PURPOSE. See the MIT License for more details.\r\n\r\nimport torch\r\nfrom ..base_model import BaseModel\r\nfrom ..layers import OneHotTransform\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom torch import FloatTensor, LongTensor\r\nimport numpy as np\r\n\r\nclass RF(BaseModel):\r\n def __init__(self, num_cont, num_enum, num_out, **conf):\r\n super().__init__(num_cont, num_enum, num_out, **conf)\r\n self.n_estimators = self.conf.get('n_estimators', 100)\r\n self.rf = RandomForestRegressor(n_estimators = self.n_estimators)\r\n self.est_noise = torch.zeros(self.num_out)\r\n if self.num_enum > 0:\r\n self.one_hot = OneHotTransform(self.conf['num_uniqs'])\r\n\r\n def xtrans(self, Xc : FloatTensor, Xe: LongTensor) -> np.ndarray:\r\n if self.num_enum == 0:\r\n return Xc.detach().numpy()\r\n else:\r\n Xe_one_hot = self.one_hot(Xe)\r\n if Xc is None:\r\n Xc = torch.zeros(Xe.shape[0], 0)\r\n return torch.cat([Xc, Xe_one_hot], dim = 1).numpy()\r\n\r\n def fit(self, Xc : torch.Tensor, Xe : torch.Tensor, y : torch.Tensor):\r\n Xtr = self.xtrans(Xc, Xe)\r\n ytr = y.numpy().reshape(-1)\r\n self.rf.fit(Xtr, ytr)\r\n mse = np.mean((self.rf.predict(Xtr).reshape(-1) - ytr)**2).reshape(self.num_out)\r\n self.est_noise = torch.FloatTensor(mse)\r\n\r\n @property\r\n def noise(self):\r\n return self.est_noise\r\n \r\n def predict(self, Xc : torch.Tensor, Xe : torch.Tensor):\r\n X = self.xtrans(Xc, Xe)\r\n mean = self.rf.predict(X).reshape(-1, 1)\r\n preds = []\r\n for estimator in self.rf.estimators_:\r\n preds.append(estimator.predict(X).reshape([-1,1]))\r\n var = np.var(np.concatenate(preds, axis=1), axis=1)\r\n return torch.FloatTensor(mean.reshape([-1,1])), torch.FloatTensor(var.reshape([-1,1]))\r\n\r\n def sample_f(self):\r\n raise RuntimeError(\"Thompson sampling is not supported\")\r\n\r\n @property\r\n def support_ts(self) -> bool:\r\n return False\r\n\r\n @property \r\n def support_grad(self) -> bool:\r\n return False\r\n\r\n @property\r\n def support_multi_output(self)->bool:\r\n return False\r\n \r\n @property\r\n def support_warm_start(self) ->bool:\r\n return False\r\n"
] |
[
[
"sklearn.ensemble.RandomForestRegressor",
"torch.cat",
"torch.zeros",
"numpy.concatenate",
"torch.FloatTensor"
]
] |
WillianEsp/RM_with_CV
|
[
"4c2cd607426c73181dc2b2b3ab5722faa42b4a68"
] |
[
"python-codes/tictactoe.py"
] |
[
"\"\"\"\r\n:File: tictactoe.py\r\n:Description: | Computer Vision for Tic-Tac-Toe\r\n | Detect board and pieces\r\n | Defines next play\r\n | Sends next play through serial communication following a protocol\r\n\r\n:Author: Willian Beraldi Esperandio\r\n:Email: willian.esperandio@gmail.com\r\n:Date: 28/03/2019\r\n:Revision: version 1\r\n:License: MIT License\r\n\"\"\"\r\n\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport random\r\nimport math\r\nimport serial\r\n\r\n\"\"\"\r\n--> Class created to break nested for\r\n\"\"\"\r\n\r\nclass BigBreak(Exception): pass\r\n\r\n\"\"\"\r\n--> Class for colored text\r\n\"\"\"\r\n\r\nclass bcolors:\r\n HEADER = '\\033[95m'\r\n OKBLUE = '\\033[94m'\r\n OKGREEN = '\\033[92m'\r\n WARNING = '\\033[93m'\r\n FAIL = '\\033[91m'\r\n ENDC = '\\033[0m'\r\n BOLD = '\\033[1m'\r\n UNDERLINE = '\\033[4m'\r\n\r\n\"\"\"\r\n--> Class containing constants used in the program\r\n\"\"\"\r\n\r\nclass ProgConst:\r\n ## Used to create relative positions\r\n computerLetter = 'W'\r\n playerLetter = 'B'\r\n numSquares = 3\r\n serialPortName = \"/dev/ttyS0\"\r\n templateBlack = [['B','-','B'],\r\n ['-','B','-'],\r\n ['B','-','B']]\r\n templateWhite = [['W','-','W'],\r\n ['-','W','-'],\r\n ['W','-','W']]\r\n\r\n\"\"\"\r\n--> Find if image has circles and return their positions\r\n--> Parameters:\r\n--> - img: RGB image to process \r\n--> Return:\r\n--> - list of positions if found any circle\r\n--> - None if didn't find any circle\r\n\"\"\"\r\n\r\ndef findCircles(img):\r\n blurImg = cv2.GaussianBlur(img, (7, 7), 0)\r\n grayImg = cv2.cvtColor(blurImg,cv2.COLOR_RGB2GRAY)\r\n #cv2.imshow('Imagem convertida',grayImg)\r\n\r\n ##Max radius of the circle is half the size of each square\r\n height, width, channel = img.shape\r\n maxRadius = width//(ProgConst.numSquares*2)\r\n \r\n circles = cv2.HoughCircles(grayImg,cv2.HOUGH_GRADIENT, 1, maxRadius,\r\n param1=maxRadius//2, param2=maxRadius,\r\n minRadius=maxRadius//2, maxRadius=maxRadius)\r\n cimg = img.copy()\r\n if(circles is not None):\r\n circles = np.uint16(np.around(circles))\r\n for i in circles[0,:]:\r\n # draw the outer circle\r\n cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)\r\n # draw the center of the circle\r\n cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)\r\n showImage('Detected circles', cimg)\r\n\r\n return circles\r\n\r\n\"\"\"\r\n--> Get average gray intensity in a circle area around a specific pixel\r\n--> Parameters:\r\n--> - img: image to process\r\n--> - height: height of the pixel\r\n--> - width: width of the pixel\r\n--> - radius: radius of the circle area\r\n--> Return:\r\n--> - int value containing average gray intensity\r\n\"\"\"\r\n\r\ndef avgGrayIntensity(img, height, width, radius=20):\r\n pixelCount = 0\r\n sumIntensity = 0\r\n imgX,imgY = img.shape[0:2]\r\n for x in range(-radius,radius+1):\r\n if(height + x > 0 and height+x < imgX):\r\n y = int(math.sqrt(radius*radius - x*x))\r\n if (width+y < imgY):\r\n sumIntensity = sumIntensity + img[height+x][width+y]\r\n pixelCount = pixelCount + 1\r\n elif (width - y > 0):\r\n sumIntensity = sumIntensity + img[height+x][width-y]\r\n pixelCount = pixelCount + 1\r\n return (sumIntensity // pixelCount)\r\n \r\n\"\"\"\r\n--> Test circles' positions and return their relative position on\r\n--> the board\r\n--> Parameters:\r\n--> - img: image to process\r\n--> - posCircles: list of circles' positions\r\n--> Return:\r\n--> - List of relative positions:\r\n--> - 'B' for black pieces\r\n--> - 'W' for white pieces\r\n--> - '-' for empty spaces\r\n--> - None if any invalid circle position\r\n\"\"\"\r\n\r\ndef getRelativePos(img, posCircles, printIntensity = True):\r\n if posCircles is None:\r\n return None\r\n grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n #cv2.imshow('gray',grayImg)\r\n height, width, channel = img.shape\r\n spaceSize = height // ProgConst.numSquares\r\n\r\n #Create matrix 3,3, 1 character unicode (True)\r\n relativePos = np.chararray((ProgConst.numSquares,ProgConst.numSquares),1,True)\r\n relativePos[:] = '-'\r\n\r\n for pos in posCircles[0,:]:\r\n height = pos[1]\r\n width = pos[0]\r\n try:\r\n for i in range(ProgConst.numSquares):\r\n for j in range(ProgConst.numSquares):\r\n if i*spaceSize < height < (i+1)*spaceSize and j*spaceSize < width < (j+1)*spaceSize:\r\n if relativePos[i][j] == '-':\r\n if avgGrayIntensity(grayImg, height, width, 20) >= 127:\r\n relativePos[i][j] = 'W'\r\n if printIntensity:\r\n print (\"Intesity of [\",i,\",\",j,\"] = \",avgGrayIntensity(grayImg, height, width, 10), \" >= 127 --> White piece\")\r\n else:\r\n relativePos[i][j] = 'B'\r\n if printIntensity:\r\n print (\"Intesity of [\",i,\",\",j,\"] = \",avgGrayIntensity(grayImg, height, width, 10), \" < 127 --> Black piece\")\r\n elif relativePos[i][j] == 'W' or relativePos[i][j] == 'B':\r\n return None\r\n raise BigBreak\r\n except:\r\n pass\r\n relativePos = np.rot90(relativePos)\r\n relativePos = np.rot90(relativePos)\r\n return relativePos\r\n\r\n\"\"\"\r\n--> Test if board is full of pieces\r\n--> Parameters:\r\n--> - board: board to be verified\r\n--> Return:\r\n--> - True if it is full\r\n--> - False if it isn't full\r\n\"\"\"\r\n\r\ndef isFull(board):\r\n return ((board[0][0] != '-' and board[0][1] != '-' and board[0][2] != '-') and\r\n (board[1][0] != '-' and board[1][1] != '-' and board[1][2] != '-') and\r\n (board[2][0] != '-' and board[2][1] != '-' and board[2][2] != '-'))\r\n\r\n\"\"\"\r\n--> Test if desired player won the game\r\n--> Parameters:\r\n--> - board: board to be verified\r\n--> - letter: letter of the player to be verified\r\n--> Return:\r\n--> - True if he won the game\r\n--> - False if the didn't win the game\r\n\"\"\"\r\n\r\ndef isWinner(board, letter):\r\n return ((board[0][0] == letter and board[0][1] == letter and board[0][2] == letter) or #top row\r\n (board[1][0] == letter and board[1][1] == letter and board[1][2] == letter) or #middle row\r\n (board[2][0] == letter and board[2][1] == letter and board[2][2] == letter) or #bottom row\r\n (board[0][0] == letter and board[1][0] == letter and board[2][0] == letter) or #left column\r\n (board[0][1] == letter and board[1][1] == letter and board[2][1] == letter) or #middle column\r\n (board[0][2] == letter and board[1][2] == letter and board[2][2] == letter) or #right column\r\n (board[0][0] == letter and board[1][1] == letter and board[2][2] == letter) or #diagonal 1\r\n (board[2][0] == letter and board[1][1] == letter and board[0][2] == letter)) #diagonal 2\r\n\r\n\"\"\"\r\n--> Discover next computer move following this rules:\r\n--> 1. Try any winning move\r\n--> 2. Block any opponent winning move\r\n--> 3. Try any corner\r\n--> 4. Try center\r\n--> 5. Try any side\r\n--> Parameters:\r\n--> - board: board to be verified\r\n--> Return:\r\n--> - Tuple with chosen space\r\n\"\"\"\r\n \r\ndef getComputerMove(board):\r\n\r\n #Check if there is any move that wins the game\r\n for i in range(ProgConst.numSquares):\r\n for j in range(ProgConst.numSquares):\r\n copy = board.copy()\r\n if copy[i][j] == '-':\r\n copy[i][j] = ProgConst.computerLetter\r\n if isWinner(copy, ProgConst.computerLetter):\r\n print('Move: Winning move - ('+str(i)+\",\"+str(j)+\")\")\r\n return i,j\r\n \r\n # Check if the player could win on his next move, and block them.\r\n for i in range(ProgConst.numSquares):\r\n for j in range(ProgConst.numSquares):\r\n copy = board.copy()\r\n if copy[i][j] == '-':\r\n copy[i][j] = ProgConst.playerLetter\r\n if isWinner(copy, ProgConst.playerLetter):\r\n print('Move: Blocking move - ('+str(i)+\",\"+str(j)+\")\")\r\n return i,j\r\n\r\n # Try to take one of the corners, if they are free.\r\n moves = [[0,0],[0,2],[2,0],[2,2]]\r\n possibleMoves = []\r\n for move in moves:\r\n if board[move[0]][move[1]] == '-':\r\n possibleMoves.append(move)\r\n if possibleMoves != []:\r\n move = random.choice(possibleMoves)\r\n print('Move: Corner move - ('+str(move[0])+\",\"+str(move[1])+\")\")\r\n return move\r\n \r\n\r\n # Try to take the center, if it is free.\r\n if board[1,1] == '':\r\n print('Move: Center move - (1,1)')\r\n return 1,1\r\n\r\n # Move on one of the sides.\r\n moves = [[0,1],[1,0],[1,2],[2,1]]\r\n possibleMoves = []\r\n for move in moves:\r\n if board[move[0]][move[1]] == '-':\r\n possibleMoves.append(move)\r\n if possibleMoves != []:\r\n move = random.choice(possibleMoves)\r\n print('Move: Side move - ('+str(move[0])+\",\"+str(move[1])+\")\")\r\n return move\r\n\r\n\"\"\"\r\n--> Computes cosine value from three points\r\n--> Parameters:\r\n--> - p0: end of x-axis point\r\n--> - p1: center point\r\n--> - p2: end of y-axis point\r\n--> Return:\r\n--> - Float value of cosine\r\n\"\"\"\r\n\r\ndef angleCos(p0, p1, p2):\r\n d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')\r\n return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )\r\n\r\n\"\"\"\r\n--> Find squares in a given image and filter them with preset parameters\r\n--> Parameters:\r\n--> - img: desired RGB image\r\n--> Return:\r\n--> - list of squares (None if fails)\r\n\"\"\"\r\n\r\ndef findSquares(img, maxCountourArea = 4000, maxAspectRatioDiff = 0.1):\r\n img = cv2.GaussianBlur(img, (5, 5), 0)\r\n img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\r\n squares = []\r\n for gray in cv2.split(img):\r\n for thrs in range(0, 255, 26):\r\n if thrs == 0:\r\n bin = cv2.Canny(gray, 0, 50, apertureSize=5)\r\n bin = cv2.dilate(bin, None)\r\n else:\r\n _retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)\r\n bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n if hierarchy is not None:\r\n for i in range(len(hierarchy[0])-1,-1,-1):\r\n if hierarchy[0][i][3] == -1:\r\n del contours[i]\r\n for cnt in contours:\r\n cnt_len = cv2.arcLength(cnt, True)\r\n cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)\r\n x,y,w,h = cv2.boundingRect(cnt)\r\n aspectRatio = float (w)/h\r\n if (len(cnt) == 4 and cv2.contourArea(cnt) > maxCountourArea and cv2.isContourConvex(cnt) and\r\n aspectRatio < (1+maxAspectRatioDiff) and aspectRatio > (1-maxAspectRatioDiff)):\r\n cnt = cnt.reshape(-1, 2)\r\n max_cos = np.max([angleCos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])\r\n if max_cos < 0.1:\r\n squares.append(cnt)\r\n if len(squares) == 0:\r\n return None\r\n else:\r\n return squares\r\n\r\n\"\"\"\r\n--> Find the position of the board in the image and return position and sizes\r\n--> Parameters:\r\n--> - img: image to be processed\r\n--> Return:\r\n--> - x: starting position on the x-axis\r\n--> - y: starting position on the y-axis\r\n--> - height: x-axis size of the board\r\n--> - width: y-axis size of the board\r\n--> - If not successful, return -1\r\n\"\"\"\r\n\r\ndef configureBoardPosition(img, areaSize = 1000):\r\n print (\"Trying to find the board with size < \" + str(areaSize) + \"... \", end=\"\", flush=True)\r\n squares = findSquares(img,areaSize)\r\n if squares is not None:\r\n contourImg = img.copy()\r\n for square in squares:\r\n #cv2.drawContours(contourImg, [square], 0, (0, 255, 0), 2 )\r\n x,y,w,h = cv2.boundingRect(square)\r\n posCircles = findCircles(img[y:y+h,x:x+w])\r\n board = getRelativePos(img[y:y+h,x:x+w], posCircles, False)\r\n \r\n if comparePresetBoard(board): \r\n ## --- Preset matched\r\n cv2.drawContours(contourImg, [square], 0, (0, 0, 255), 2 )\r\n showImage('Board detection',contourImg)\r\n return x,y,h,w\r\n \r\n ## --- Board not found, trying again or aborting\r\n print(\"FAIL\")\r\n if (img.size > areaSize*1.5):\r\n ## --- Trying with larger squares\r\n return configureBoardPosition(img, areaSize*1.5)\r\n else:\r\n ## --- Max size reached (areaSize = image size), return not found\r\n if(img.size == areaSize):\r\n return -1,-1,-1,-1\r\n ## --- Last try, trying with maximum areaSize (size of the image)\r\n else:\r\n return configureBoardPosition(img,img.size)\r\n \r\n \r\n\r\n\"\"\"\r\n--> Test if board detected have all the positions correct\r\n--> Parameters:\r\n--> - board: board to be verified\r\n--> Return:\r\n--> - True if it is equal to the mix of white and black template\r\n--> - False if it isn't\r\n\"\"\"\r\n\r\ndef comparePresetBoard(board):\r\n if board is None:\r\n return False\r\n for i in range(ProgConst.numSquares):\r\n for j in range(ProgConst.numSquares):\r\n if (board[i][j] != ProgConst.templateBlack[i][j] and board[i][j] != ProgConst.templateWhite[i][j]):\r\n return False\r\n return True\r\n \r\n\"\"\"\r\n--> Expand a single board move to all robot moves (Tic-tac-toe only)\r\n--> Parameters:\r\n--> - move: board move\r\n--> - newPiecePos: the position of the new piece array\r\n--> Return:\r\n--> - list of expanded movements\r\n\"\"\"\r\n\r\ndef expandMovements(move, newPiecePos):\r\n expandedMoves = [('n',0,newPiecePos),('p',move[0],move[1])]\r\n newPiecePos += 1\r\n return expandedMoves,newPiecePos\r\n \r\n\"\"\"\r\n--> Convert relative position move to list of commands to send to the robot\r\n--> Parameters:\r\n--> - allMoves: list of moves\r\n--> - commandList: string of commands if exists\r\n--> Return:\r\n--> - String of List of commands following the protocol #Sxy$\r\n\"\"\"\r\n\r\ndef convertCommandListToString(allMoves,commandList=None):\r\n newCommandList = \"\"\r\n for move in allMoves:\r\n newCommandList += \"#\" + move[0] + str(move[1]) + str(move[2])\r\n newCommandList += \"$\"\r\n if commandList is None:\r\n return newCommandList\r\n else:\r\n return commandList[0:len(commandList)-1]+newCommandList\r\n \r\n\"\"\"\r\n--> Send data through serial communication\r\n--> Parameters:\r\n--> - data: string of desired data\r\n--> Return:\r\n--> - None\r\n\"\"\"\r\n\r\ndef sendCommandList(serialPort, data):\r\n if(serialPort.isOpen()):\r\n serialPort.write(data.encode())\r\n return True\r\n else:\r\n return False \r\n\r\n\"\"\"\r\n--> Print a better square board with rows and columns numbers\r\n--> Parameters:\r\n--> - board: numpy matrix array\r\n--> Return:\r\n--> - None\r\n\"\"\"\r\n\r\ndef printBoard(board):\r\n size = board.shape[0]\r\n print(\"\\n\"+\"-\"*size+\" Printing board (\"+str(size)+\",\"+str(size)+\") \"+\"-\"*size+\"\\n\")\r\n for i in range(size):\r\n if i == 0:\r\n for j in range(size):\r\n if j == 0:\r\n print(\" | 0 |\",end=\"\",flush=True)\r\n else:\r\n print(\" \"+str(j)+\" |\",end=\"\",flush=True)\r\n if j == size-1:\r\n print(\"\")\r\n print(\" -\"+\"-\"*6*size)\r\n print(str(i)+\" | \"+np.array2string(board[i],separator=\" | \")[1:-1]+\" |\")\r\n print(\" -\"+\"-\"*6*size)\r\n print(\"\")\r\n\r\n\"\"\"\r\n--> Complementary version of cv2.imshow to add commands cv2.namedWindow and cv.resizeWindow\r\n--> to standardize image windows\r\n--> Parameters:\r\n--> - windowName: name of the window\r\n--> - img: image to be displayed\r\n--> Return:\r\n--> - None\r\n\"\"\"\r\n\r\ndef showImage(windowName, img):\r\n cv2.namedWindow(windowName, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_NORMAL)\r\n cv2.resizeWindow(windowName,640,360)\r\n cv2.imshow(windowName, img)\r\n\r\n\"\"\"\r\n--> Display an image with two diagonal lines from each corner of the image and crossing in the middle\r\n--> Parameters:\r\n--> - img: image to be displayed\r\n--> Return:\r\n--> - None\r\n\"\"\"\r\n\r\ndef drawCenterLine(windowName, img):\r\n centerImg = img.copy()\r\n x,y,c = centerImg.shape\r\n cv2.line(centerImg,(0,0),(y,x),(255,0,0),2)\r\n cv2.line(centerImg,(y,0),(0,x),(255,0,0),2)\r\n showImage(windowName,centerImg)\r\n\r\n\"\"\"\r\n--> Main Code\r\n\"\"\"\r\n\r\ndef main():\r\n cam = cv2.VideoCapture(0)\r\n\r\n # ---- Flags\r\n computerTurn = False\r\n centerLines = False\r\n boardConfigurated = False\r\n serialConfigurated = False\r\n executionFlag = False\r\n errorFlag = False\r\n startMessage = True\r\n \r\n \r\n # ---- New pieces list position\r\n newPiecePos = 0\r\n \r\n # ---- Position of the board\r\n xPos = yPos = eightBoard = widthBoard = -1\r\n \r\n ## --- Configuration of the serial port\r\n serialCounter = 1\r\n while not serialConfigurated:\r\n try:\r\n print(\"(Attempt \" + str(serialCounter) + \") Trying to initialize serial port: \" + ProgConst.serialPortName + \" ... \", end=\"\", flush = True)\r\n serialPort = serial.Serial(ProgConst.serialPortName,9600)\r\n if(serialPort.is_open):\r\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\r\n serialConfigurated = True\r\n executionFlag = True\r\n except (serial.SerialException, serial.SerialTimeoutException) as error:\r\n print(bcolors.FAIL +\"FAIL - \"+error.__str__()+ bcolors.ENDC)\r\n if serialCounter < 4:\r\n serialCounter += 1\r\n else:\r\n print(bcolors.FAIL + \"ERROR: Unable to open serial port!\" + bcolors.ENDC)\r\n errorFlag = True\r\n break\r\n\r\n ## --- Execution of the computer vision \r\n while executionFlag:\r\n ret_val, img = cam.read(1)\r\n showImage('Live Feed',img)\r\n\r\n ## --- Configuration of the board size\r\n if not boardConfigurated:\r\n print(bcolors.WARNING+\"\\nSetup the board and press any key to start configuration\"+bcolors.ENDC)\r\n while cv2.waitKey(1) == -1:\r\n ret_val, img = cam.read(1)\r\n showImage('Live Feed',img)\r\n drawCenterLine('Centered Image',img)\r\n print(\"\\nInitializing board configuration... \")\r\n cv2.destroyWindow('Centered Image')\r\n xPos, yPos, heightBoard, widthBoard = configureBoardPosition(img)\r\n if (xPos != -1 and yPos != -1 and heightBoard != -1 and widthBoard != -1):\r\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\r\n boardConfigurated = True\r\n else:\r\n print(bcolors.FAIL + \"FAIL\" + bcolors.ENDC)\r\n print(bcolors.FAIL + \"ERROR: Unable to find the board\" + bcolors.ENDC)\r\n executionFlag = False\r\n errorFlag = True\r\n if(errorFlag is False):\r\n print(\"\\n\"+bcolors.WARNING+\"Clear the board and press any key!\"+bcolors.ENDC)\r\n while cv2.waitKey(1) == -1:\r\n ret_val, img = cam.read(1)\r\n showImage('Live Feed',img)\r\n\r\n if startMessage:\r\n print(\"\\n--------------------------------------------\")\r\n print(\"Game started! Place a piece or press <ENTER>\")\r\n print(\"--------------------------------------------\")\r\n startMessage = False\r\n \r\n ## --- Execution of the main part of the code\r\n elif computerTurn and boardConfigurated:\r\n print(\"\\n--------------------\")\r\n print(\"---- ROBOT TURN ----\")\r\n print(\"--------------------\")\r\n boardImg = img[yPos:yPos+heightBoard,xPos:xPos+widthBoard]\r\n \r\n posCircles = findCircles(boardImg)\r\n board = getRelativePos(boardImg, posCircles, False)\r\n\r\n if board is None:\r\n board = np.chararray((3,3),1,True)\r\n board[:] = '-'\r\n \r\n printBoard(board)\r\n \r\n if isWinner(board,ProgConst.computerLetter) or isWinner(board,ProgConst.playerLetter) or isFull(board):\r\n print (\"--------------------------------\")\r\n print (\"------- THE GAME IS OVER -------\")\r\n print (\"--------------------------------\")\r\n else:\r\n move = getComputerMove(board)\r\n\r\n ## Expand, convert and send commands to the robot\r\n allMoves,newPiecePos = expandMovements(move, newPiecePos)\r\n commandList = convertCommandListToString(allMoves)\r\n print(\"Command sent to Robot: \"+commandList)\r\n \r\n print(\"\\nGAME PAUSED!\")\r\n print(\"Press <ENTER> to unpause the game\")\r\n \r\n while cv2.waitKey(1) != 13:\r\n ret_val, img = cam.read(1)\r\n showImage('Live Feed',img)\r\n\r\n print(\"Trying to send command to robot...\",end=\"\", flush = True)\r\n\r\n if(sendCommandList(serialPort,commandList)):\r\n print(bcolors.OKGREEN + \"DONE\" + bcolors.ENDC)\r\n else:\r\n print(bcolors.FAIL + \"FAIL\" + bcolors.ENDC)\r\n executionFlag = False\r\n errorFlag = True\r\n \r\n print(\"\\nGAME PAUSED!\")\r\n print(\"Press <ENTER> to unpause the game\")\r\n \r\n while cv2.waitKey(1) != 13:\r\n ret_val, img = cam.read(1)\r\n showImage('Live Feed',img)\r\n \r\n boardImg = img[yPos:yPos+heightBoard,xPos:xPos+widthBoard]\r\n posCircles = findCircles(boardImg)\r\n board = getRelativePos(boardImg, posCircles, False)\r\n printBoard(board)\r\n if isWinner(board,ProgConst.computerLetter):\r\n print (\"---------------------------------\")\r\n print (\"---- THE ROBOT IS THE WINNER ----\")\r\n print (\"---------------------------------\")\r\n print (\"\\nPlease, reset pieces and press <ENTER> to restart the game\")\r\n newPiecePos = 0\r\n startMessage = True\r\n \r\n elif isWinner(board,ProgConst.playerLetter):\r\n print (\"----------------------------------\")\r\n print (\"---- THE PLAYER IS THE WINNER ----\")\r\n print (\"----------------------------------\")\r\n print (\"\\nPlease, reset pieces and press <ENTER> to restart the game\")\r\n newPiecePos = 0\r\n startMessage = True\r\n\r\n \r\n elif isFull(board):\r\n print (\"---------------------------------\")\r\n print (\"------- THE GAME IS A TIE -------\")\r\n print (\"---------------------------------\")\r\n print (\"\\nPlease, reset pieces and press <ENTER> to restart the game\")\r\n newPiecePos = 0\r\n startMessage = True\r\n \r\n else:\r\n print(\"Waiting for the player turn\")\r\n\r\n while cv2.waitKey(1) != 13:\r\n pass\r\n \r\n computerTurn = False\r\n \r\n ## --- Keyboard inputs \r\n else:\r\n key = cv2.waitKey(1)\r\n if key == 27: # esc to quit\r\n executionFlag = False \r\n \r\n elif key == 13: # enter to computer turn\r\n computerTurn = True \r\n \r\n elif key == 32: # space to configure board\r\n boardConfigurated = False \r\n xPos = yPos = heightBoard = widthBoard = -1\r\n \r\n elif key == 8: # backspace to centerLines\r\n if centerLines == False:\r\n centerLines = True\r\n else:\r\n centerLines = False\r\n cv2.destroyWindow('Centered Image') \r\n\r\n ## --- Create a window with image and center lines\r\n if centerLines == True:\r\n drawCenterLine('Centered Image',img)\r\n \r\n if(errorFlag):\r\n print(bcolors.WARNING + \"Program finishing by error\\n\" + bcolors.ENDC)\r\n else:\r\n print(bcolors.OKBLUE + \"Program finishing by keyboard input\\n\" + bcolors.ENDC)\r\n \r\n ##END OF PROGRAM EXECUTION\r\n serialPort.close()\r\n cv2.destroyAllWindows()\r\n cam.release()\r\n \r\n \r\nif __name__ == '__main__':\r\n main()\r\n"
] |
[
[
"numpy.rot90",
"numpy.dot",
"numpy.around",
"numpy.chararray",
"numpy.array2string"
]
] |
Mehrdadj93/handyscripts
|
[
"5df9a69e17345ca5a3e42dda2424da2da0ab6f12"
] |
[
"python/filledlines.py"
] |
[
"from collections.abc import Iterable\nimport itertools as it\n\nimport tecplot as tp\nfrom tecplot.constant import AxisMode, Color, PlotType, SurfacesToPlot\n\n\ndef plot_filled_lines_3d(x, *yy, z=(-0.2, 0.2), y0=0, colors=None,\n name='Line Data', page=None):\n \"\"\"Plot a series of lines in (x, y) as 3D volumes.\n\n Parameters:\n x (array): Values along the x-axis\n *yy (arrays): One or more arrays of y-values for each x value. These\n must be the same length as ``x``.\n z (2-tuple): (min, max) around the z-coordinate for each line.\n y0 (float): Base y-value.\n colors (tecplot.plot.ContourGroup or array of Colors): The contour\n group will color each line using the full range if given.\n Otherwise, colors obtained from the enumeration\n ``tecplot.constant.Color`` will be cycled through for each line.\n The first contour group of the plot will be used by default.\n name (str): Name of the frame that will be fetched or created. Also\n used to fetch or create zones by name. Any other zones that start\n with this string will be deleted from the dataset.\n page (tecplot.layout.Page): Page on which to add or get the frame. The\n active page will be used by default.\n\n Example plotting some Legedre polynomials::\n\n import numpy as np\n from numpy.polynomial import legendre\n\n import tecplot as tp\n\n x = np.linspace(-1., 1., 100)\n yy = [legendre.Legendre(([0] * i) + [1])(x) for i in range(1, 6)]\n plot = plot_filled_lines_3d(x, *yy, y0=-1.)\n tp.save_png('line_data.png')\n \"\"\"\n if page is None:\n page = tp.active_page()\n\n # get or create a frame with the given name\n frame = page.frame(name)\n if frame is None:\n frame = page.add_frame()\n frame.name = name\n\n # use existing dataset on frame or create it\n if frame.has_dataset:\n ds = frame.dataset\n vnames = ds.variable_names\n for vname in ['x', 'y', 'z', 's']:\n if vname not in vnames:\n ds.add_variable(vname)\n else:\n ds = frame.create_dataset(name, ['x', 'y', 'z', 's'])\n\n # create or modify zones named \"{name} {i}\" based on the values in yy\n x = np.asarray(x, dtype=float)\n for i, y in enumerate(yy):\n shape = (len(x), 2, 2)\n zname = '{name} {i}'.format(name=name, i=i)\n zn = ds.zone(zname)\n\n # recreate zone if shape has changed\n if zn is None or zn.dimensions != shape:\n new_zn = ds.add_ordered_zone(zname, shape)\n if zn:\n ds.delete_zones(zn)\n zn = new_zn\n\n # prepare arrays to be pushed into tecplot\n y1 = np.array([float(y0), 1.])\n z1 = np.asarray(z, dtype=float) + i\n Z, Y, X = np.meshgrid(z1, y1, x, indexing='ij')\n Y[:,1,:] = y\n\n # fill zone with data\n zn.values('x')[:] = X\n zn.values('y')[:] = Y\n zn.values('z')[:] = Z\n zn.values('s')[:] = np.full(Z.size, i / ((len(yy) - 1) or 1))\n\n # remove any extra zones from a previous run\n zones_to_delete = []\n while True:\n i = i + 1\n zn = ds.zone('{name} {i}'.format(name=name, i=i))\n if zn is None:\n break\n zones_to_delete.append(zn)\n if zones_to_delete:\n ds.delete_zones(*zones_to_delete)\n\n # adjust plot to show the line zones\n plot = frame.plot(PlotType.Cartesian3D)\n plot.activate()\n\n # set axes variables, contour variable, hide legend\n plot.axes.x_axis.variable = ds.variable('x')\n plot.axes.y_axis.variable = ds.variable('y')\n plot.axes.z_axis.variable = ds.variable('z')\n\n if isinstance(colors, Iterable):\n # color each zone by shade color\n plot.show_contour = False\n plot.show_shade = True\n for zn, col in zip(ds.zones(name + ' *'), it.cycle(colors)):\n plot.fieldmap(zn).shade.color = Color(col)\n else:\n # color each zone by contour values over the whole contour range\n if colors is None:\n contour = plot.contour(0)\n plot.show_contour = True\n plot.show_shade = False\n contour.variable = ds.variable('s')\n contour.legend.show = False\n contour.levels.reset_levels(np.linspace(0, 1, 256))\n\n # turn on axes, contour and translucency. hide orientation axes\n plot.axes.x_axis.show = True\n plot.axes.y_axis.show = True\n plot.axes.z_axis.show = True\n plot.use_translucency = True\n plot.axes.orientation_axis.show = False\n\n # turn on surfaces and adjust translucency\n for zn in ds.zones('Line Data*'):\n fmap = plot.fieldmap(zn)\n fmap.show = True\n fmap.surfaces.surfaces_to_plot = SurfacesToPlot.BoundaryFaces\n fmap.effects.surface_translucency = 50\n\n # set the view\n plot.view.psi = 0\n plot.view.theta = 0\n plot.view.alpha = 0\n plot.view.rotate_axes(20, (1, 0, 0))\n plot.view.rotate_axes(-20, (0, 1, 0))\n\n # set axes limits\n ax = plot.axes\n ax.axis_mode = AxisMode.Independent\n ax.x_axis.min = min(x)\n ax.x_axis.max = max(x)\n ax.y_axis.min = y0\n ax.y_axis.max = 1.05 * ds.variable('y').max()\n ax.z_axis.min = z[0]\n ax.z_axis.max = z[1] + (len(yy) - 1)\n\n # adjust tick spacing for z-axis\n ax.z_axis.ticks.auto_spacing = False\n ax.z_axis.ticks.spacing = 1\n\n # fit the view and then zoom out slightly\n plot.view.fit()\n plot.view.width *= 1.05\n\n return plot\n\n\nif __name__ == '__main__':\n import sys\n import numpy as np\n from numpy import polynomial as poly\n\n from tecplot.constant import Color\n\n if '-c' in sys.argv:\n tp.session.connect()\n\n # some sample data (orthogonal polynomial series)\n x = np.linspace(-1., 1., 100)\n yy = [poly.legendre.Legendre(([0] * i) + [1])(x)\n for i in range(1, 6)]\n\n # use tecplot color palette to shade each line\n # alternatively, set colors to None to use the\n # plot's contour color values.\n colors = [Color(i + 1) for i in range(len(yy))]\n plot = plot_filled_lines_3d(x, *yy, y0=-1, colors=colors)\n\n if '-c' not in sys.argv:\n tp.save_png('line_data.png')\n"
] |
[
[
"numpy.asarray",
"numpy.meshgrid",
"numpy.polynomial.legendre.Legendre",
"numpy.linspace"
]
] |
BobAnkh/THUEE_ROBOTS
|
[
"2a302c847058a8d80d83b70b1670e1ffb6de8c57"
] |
[
"exp2/svm_canny.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @Author : BobAnkh\n# @Github : https://github.com/BobAnkh\n# @Date : 2020-10-22 19:29:56\n# @LastEditTime : 2020-10-31 11:09:44\n# @Description :\n# @Copyright 2020 BobAnkh\n\nimport cv2\nfrom sklearn import svm\nimport os\nimport random\nimport numpy as np\n# from tqdm import tqdm\nfrom sklearn.externals import joblib\nimport logging\n\n\ndef read_data(path):\n img = cv2.imread(path)\n img = cv2.resize(img, (60, 80)) # average size\n blurred = cv2.GaussianBlur(img,(5,5),0)\n fd = cv2.Canny(blurred, 10, 70).reshape(1, -1).squeeze()\n return fd\n\n\ndef SVM_HOG_TRAIN(DATA_TRAIN, model_place='exp2.model', loglevel='DEBUG'):\n '''\n 使用SVM+HOG进行训练.\n\n Args:\n DATA_TRAIN (str): 训练集地址.\n model_place (str, optional): 模型存储的位置. Defaults to 'exp2.model'.\n loglevel (str, optional): log输出的级别,'DEBUG'即全输出,'INFO'即无输出. Defaults to 'DEBUG'.\n '''\n if loglevel == 'DEBUG':\n logging.basicConfig(format=\"[%(levelname)s]%(message)s\", level=logging.DEBUG)\n else:\n logging.basicConfig(format=\"[%(levelname)s]%(message)s\", level=logging.INFO)\n \n logging.debug('-----------Train start!-----------')\n train_data = []\n categories = os.listdir(DATA_TRAIN)\n\n # load training data\n for category in categories:\n path = os.path.join(DATA_TRAIN, category)\n load_cat = 'loading category: ' + category\n logging.debug(load_cat)\n for file in os.listdir(path):\n fd = read_data(os.path.join(path, file))\n train_data.append((fd, category))\n # 随机调整数据顺序\n random.shuffle(train_data)\n logging.debug('read data success!')\n\n # divide into train and validation\n n = int(0.8 * len(train_data))\n train_set = train_data[:n]\n val_set = train_data[n:]\n TV_number = 'Train_set: ' + str(len(train_set)) + ' Val_set: ' + str(len(val_set))\n logging.debug(TV_number)\n\n # unzip dataset\n X_train, Y_train = map(list, zip(*train_set))\n X_train = np.array(X_train)\n Y_train = np.array(Y_train)\n\n X_test, Y_test = map(list, zip(*val_set))\n X_test = np.array(X_test)\n Y_test = np.array(Y_test)\n\n # SVM\n classifier = svm.SVC()\n classifier.fit(X_train, Y_train)\n\n predicted = classifier.predict(X_test)\n\n # Validation\n correct = 0\n for i, correct_result in enumerate(Y_test):\n if predicted[i] == correct_result:\n correct += 1\n acc = 'Accuracy:' + str(correct / len(X_test))\n logging.debug(acc)\n\n # save model\n joblib.dump(classifier, model_place)\n save_place = 'Model saved as ' + model_place\n logging.debug(save_place)\n logging.debug('-----------Train end!-----------')\n\n\ndef SVM_HOG_TEST(DATA_TEST, model_place='exp2.model', loglevel='DEBUG'):\n '''\n 使用训练好的模型进行测试,返回测试类别名称.\n\n Args:\n DATA_TEST (str): 测试集地址.\n model_place (str, optional): 模型存储的位置. Defaults to 'exp2.model'.\n loglevel (str, optional): log输出的级别,'DEBUG'即全输出,'INFO'即无输出. Defaults to 'DEBUG'.\n\n Returns:\n dict: 字典结构(json)的测试图片及其类别名称.\n '''\n if loglevel == 'DEBUG':\n logging.basicConfig(format=\"[%(levelname)s]%(message)s\", level=logging.DEBUG)\n else:\n logging.basicConfig(format=\"[%(levelname)s]%(message)s\", level=logging.INFO)\n logging.debug('-----------Test start!-----------')\n # Load model\n classifier = joblib.load(model_place)\n\n # Load test data\n test_data = []\n test_imgs = os.listdir(DATA_TEST)\n logging.debug('loading test images')\n for test_img in test_imgs:\n fd = read_data(os.path.join(DATA_TEST, test_img))\n test_data.append(fd)\n # test\n logging.debug('Test result:')\n test_predict = classifier.predict(test_data)\n test_result = {}\n for i, test_img in enumerate(test_imgs):\n tmp = test_img + ':' + test_predict[i]\n tmp_dic = {test_img: test_predict[i]}\n test_result.update(tmp_dic)\n logging.debug(tmp)\n logging.debug('-----------Test end!-----------')\n return test_result\n\n\nif __name__ == '__main__':\n DATA_TRAIN = 'exp2\\\\data\\\\train'\n DATA_TEST = 'exp2\\\\data\\\\test'\n SVM_HOG_TRAIN(DATA_TRAIN, loglevel='INFO')\n test_result = SVM_HOG_TEST(DATA_TEST, loglevel='INFO')\n print(test_result)\n"
] |
[
[
"sklearn.externals.joblib.dump",
"numpy.array",
"sklearn.externals.joblib.load",
"sklearn.svm.SVC"
]
] |
ohenriksson/MastersThesisData
|
[
"c657deb933d2cbbb7fd55e836e424b9b58c84aab"
] |
[
"axis-plotter/functions.py"
] |
[
"import numpy as np\n\ndef build_zero_array(n_axes,time):\n return list(map(lambda a: list(map(\n lambda t: 0 ,range(time))) ,range(n_axes) ))\n\n\ndef plot_data(axis, data, title, time):\n axis.set_title(title)\n axis.grid()\n if(len(data) > 1):\n for d in data:\n axis.plot(time, d)\n else:\n axis.plot(time,data[0])\n\ndef real_time_array(n_targets, delta_t):\n return list(map(lambda t: np.divide(t,delta_t), range(0, n_targets)))\n\ndef vel_top(data,delta_t):\n max1 = 0\n for axis in data:\n a = max(list(map(lambda d: np.abs(d),axis)))\n if a> max1: max1 = a\n return np.round(max1,4)\n\ndef acc_sum(data,delta_t):\n sum1 = 0\n for axis in data:\n sum1 += sum(map(lambda d: np.abs(d)*delta_t,axis))\n return np.round(sum1,3)\n\ndef compute_derivative(data, delta_t):\n diff = map(lambda a,b: (b-a), data[:-1],data[1:])\n derivative = map(lambda d: np.divide(d,delta_t), diff)\n return list(derivative) \n\ndef derivative_three_point(data, delta_t):\n start = derivative_end_point(data[0], data[1], data[2], delta_t)\n end = derivative_end_point(data[-1], data[-2], data[-3], delta_t)\n midpoints = map(lambda a,b: np.divide(b-a,delta_t*2), data[:-2], data[2:])\n return [start] + list(midpoints) + [end]\n\ndef derivative_end_point(y_x1,y_x2, y_x3, h):\n num = -3*y_x1 + 4*y_x2 + -y_x3\n return np.divide(num,2*h)\n\ndef derive_all(data,delta_t):\n derivatives = []\n if(len(data) > 1):\n dataT = list(map(lambda *a: list(a), *data))\n for d in dataT:\n derivatives.append(compute_derivative(d,delta_t))\n \n return list(map(lambda *a: list(a), *derivatives))\n else :\n return [compute_derivative(data[0],delta_t)]"
] |
[
[
"numpy.round",
"numpy.abs",
"numpy.divide"
]
] |
kad99kev/FGTD-Streamlit
|
[
"0dc8d2894eadf2260d5e5dcf10ead12ff62f6cd8"
] |
[
"app.py"
] |
[
"import streamlit as st\nimport torch\nimport gc\n\nfrom utils.toc import Toc\nfrom utils.model_downloader import download_models\nfrom utils.footer import footer\n\nfrom streamlit_utils.loaders import load_face_generators, load_mnist_generators\nfrom streamlit_utils.io import get_sample, read_csv, get_output, face_graph, mnist_graph\n\n\ndef main():\n\n gc.enable()\n ##### Setup #####\n toc = Toc()\n toc.title(\"Face Generation from Textual Description 👩 👨 📋 \", \"fgtd\")\n\n # Get device\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n ##### Face GANS #####\n st.markdown(\"---\")\n st.markdown(\"## Demo\")\n\n # First load the model\n dcgan, n_dcgan, sagan, n_sagan, dfgan, n_dfgan = load_face_generators(device)\n\n ##### Examples #####\n seen_df = read_csv(\"examples/seen_text.csv\")\n unseen_df = read_csv(\"examples/unseen_text.csv\")\n\n butt_col1, butt_col2, butt_col3, butt_col4, butt_col5 = st.beta_columns(5)\n\n with butt_col1:\n if st.button(\"Example 1\"):\n user_input = \"The woman has high cheekbones. She has straight hair which is black in colour. She has big lips with arched eyebrows. The smiling, young woman has rosy cheeks and heavy makeup. She is wearing lipstick.\"\n\n with butt_col2:\n if st.button(\"Example 2\"):\n user_input = \"The man sports a 5 o’clock shadow and mustache. He has a receding hairline. He has big lips and big nose, narrow eyes and a slightly open mouth. The young attractive man is smiling. He’s wearing necktie.\"\n\n with butt_col3:\n if st.button(\"Example 3\"):\n user_input = \"The man has straight hair. He has arched eyebrows. The man looks young and attractive. He’s wearing necktie.\"\n\n with butt_col4:\n if st.button(\"Trained\", help=\"Get a random example from training set.\"):\n user_input = get_sample(seen_df)\n\n with butt_col5:\n if st.button(\"Unseen\", help=\"Get a random example from untrained text.\"):\n user_input = get_sample(unseen_df)\n\n try:\n user_input = st.text_area(\"Try it yourself!\", user_input)\n except NameError:\n user_input = st.text_area(\n \"Try it yourself!\",\n \"The man sports a 5 o’clock shadow. His hair is black in colour. He has big nose with bushy and arched eyebrows. The man looks attractive.\",\n )\n\n st.markdown(\"---\")\n\n ##### Outputs #####\n\n ##### DCGAN #####\n toc.header(\"Deep Convolution GAN\", \"DCGAN\", \"face-dcgan\")\n output_dcgan = get_output(\n dcgan, device, (4, 100), user_input=user_input, input_type=\"face\"\n )\n output_ndcgan = get_output(\n n_dcgan, device, (4, 100), user_input=user_input, input_type=\"face\"\n )\n\n dc_col1, dc_col2 = st.beta_columns(2)\n\n with dc_col1:\n st.image(\n [\n output_dcgan,\n ],\n caption=[\"DCGAN\"],\n )\n\n with dc_col2:\n st.image(\n [\n output_ndcgan,\n ],\n caption=[\"N DCGAN\"],\n )\n\n dcgan_df = read_csv(\"history/face/dcgan.csv\")\n n_dcgan_df = read_csv(\"history/face/n-dcgan.csv\")\n face_graph(dcgan_df, n_dcgan_df, [\"DCGAN\", \"N DCGAN\"])\n st.markdown(\"---\")\n\n ##### SAGAN #####\n toc.header(\"Self-Attention GAN\", \"SAGAN\", \"sagan\")\n output_sagan = get_output(\n sagan, device, (4, 100), user_input=user_input, input_type=\"face\"\n )\n output_nsagan = get_output(\n n_sagan, device, (4, 100), user_input=user_input, input_type=\"face\"\n )\n\n sa_col1, sa_col2 = st.beta_columns(2)\n\n with sa_col1:\n st.image(\n [\n output_sagan,\n ],\n caption=[\"SAGAN\"],\n )\n with sa_col2:\n st.image(\n [\n output_nsagan,\n ],\n caption=[\"N SAGAN\"],\n )\n\n sagan_df = read_csv(\"history/face/sagan.csv\")\n n_sagan_df = read_csv(\"history/face/n-sagan.csv\")\n face_graph(sagan_df, n_sagan_df, [\"SAGAN\", \"N SAGAN\"])\n st.markdown(\"---\")\n\n ##### DFGAN #####\n toc.header(\"Deep Fusion GAN\", \"DFGAN\", \"dfgan\")\n output_dfgan = get_output(\n dfgan, device, (4, 100), user_input=user_input, input_type=\"face\"\n )\n output_ndfgan = get_output(\n n_dfgan, device, (4, 100), user_input=user_input, input_type=\"face\"\n )\n\n df_col1, df_col2 = st.beta_columns(2)\n\n with df_col1:\n st.image(\n [\n output_dfgan,\n ],\n caption=[\"DFGAN\"],\n )\n with df_col2:\n st.image(\n [\n output_ndfgan,\n ],\n caption=[\"N DFGAN\"],\n )\n\n dfgan_df = read_csv(\"history/face/dfgan.csv\")\n n_dfgan_df = read_csv(\"history/face/n-dfgan.csv\")\n face_graph(dfgan_df, n_dfgan_df, [\"DFGAN\", \"N DFGAN\"])\n st.markdown(\"---\")\n\n ##### MNIST GANS #####\n toc.title(\"MNIST Dataset (Digit and Fashion)\", \"mnist\")\n\n # Load models\n gan, dcgan, cgan, acgan = load_mnist_generators(device)\n\n ##### GAN #####\n toc.header(\"Vanilla GAN\", \"GAN\", \"gan\")\n st.markdown(\"Epochs : 20 \")\n\n gan_output = get_output(gan, device, (64, 100))\n st.image(gan_output)\n\n gan_df = read_csv(\"history/mnist/gan.csv\")\n mnist_graph(gan_df)\n st.markdown(\"---\")\n\n ##### DCGAN #####\n toc.header(\"Deep Convolution GAN (MNIST)\", \"DCGAN\", \"mnist-dcgan\")\n st.markdown(\"Epochs : 20 \")\n\n dcgan_output = get_output(dcgan, device, (64, 100, 1, 1))\n st.image(dcgan_output)\n\n dcgan_df = read_csv(\"history/mnist/dcgan.csv\")\n mnist_graph(dcgan_df)\n st.markdown(\"---\")\n\n ##### CGAN #####\n toc.header(\"Conditional GAN\", \"CGAN\", \"cgan\")\n st.markdown(\"Epochs : 20 \")\n\n cgan_label = st.slider(\n \"Slide for different digit images!\", min_value=0, max_value=9, value=0\n )\n cgan_output = get_output(cgan, device, (64, 100), user_input=cgan_label)\n st.image(cgan_output)\n\n cgan_df = read_csv(\"history/mnist/cgan.csv\")\n mnist_graph(cgan_df)\n st.markdown(\"---\")\n\n ##### ACGAN #####\n toc.header(\"Auxilary Conditional GAN\", \"ACGAN\", \"acgan\")\n st.markdown(\"Epochs : 20 \")\n\n acgan_label = st.slider(\n \"Slide for different fashion images!\", min_value=0, max_value=9, value=0\n )\n st.text(\n \"0: 'T-shirt/top', 1: 'Trouser', 2: 'Pullover', 3: 'Dress', 4: 'Coat', 5: 'Sandal', 6: 'Shirt', 7: 'Sneaker', 8: 'Bag', 9: 'Ankle boot'\"\n )\n acgan_output = get_output(acgan, device, (64, 100), user_input=acgan_label)\n st.image(acgan_output)\n\n acgan_df = read_csv(\"history/mnist/acgan.csv\")\n mnist_graph(acgan_df)\n st.markdown(\"---\")\n\n ##### TOC #####\n toc.placeholder()\n toc.generate()\n\n ##### Footer #####\n footer()\n\n gc.collect()\n\n\nif __name__ == \"__main__\":\n download_models()\n main()\n"
] |
[
[
"torch.cuda.is_available"
]
] |
MSU-MLSys-Lab/CATE
|
[
"654c393d7df888d2c3f3b90f9e6752faa061157e"
] |
[
"darts/cnn/utils.py"
] |
[
"import os\nimport numpy as np\nimport torch\nimport shutil\nimport torchvision.transforms as transforms\n\n\nclass AvgrageMeter(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.avg = 0\n self.sum = 0\n self.cnt = 0\n\n def update(self, val, n=1):\n self.sum += val * n\n self.cnt += n\n self.avg = self.sum / self.cnt\n\n\ndef accuracy(output, target, topk=(1,)):\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].reshape(-1).float().sum(0)\n res.append(correct_k.mul_(100.0/batch_size))\n return res\n\n\nclass Cutout(object):\n def __init__(self, length):\n self.length = length\n\n def __call__(self, img):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\n\ndef _data_transforms_cifar10(cutout, cutout_length):\n CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124]\n CIFAR_STD = [0.24703233, 0.24348505, 0.26158768]\n\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n if cutout:\n train_transform.transforms.append(Cutout(cutout_length))\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n return train_transform, valid_transform\n\n\ndef count_parameters_in_MB(model):\n return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if \"auxiliary\" not in name)/1e6\n\n\ndef save_checkpoint(state, is_best, save):\n filename = os.path.join(save, 'checkpoint.pth.tar')\n torch.save(state, filename)\n if is_best:\n best_filename = os.path.join(save, 'model_best.pth.tar')\n shutil.copyfile(filename, best_filename)\n\n\ndef save(model, model_path):\n torch.save(model.state_dict(), model_path)\n\n\ndef load(model, model_path, gpu_id):\n ml = 'cuda:{}'.format(gpu_id) if torch.cuda.is_available() else 'cpu'\n model.load_state_dict(torch.load(model_path, map_location = ml), strict=False)\n\n\n\ndef drop_path(x, drop_prob):\n if drop_prob > 0.:\n keep_prob = 1.-drop_prob\n mask = torch.cuda.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob)\n x.div_(keep_prob)\n x.mul_(mask)\n return x\n\n\ndef create_exp_dir(path, scripts_to_save=None):\n if not os.path.exists(path):\n os.mkdir(path)\n #print('Experiment dir : {}'.format(path))\n\n if scripts_to_save is not None:\n os.mkdir(os.path.join(path, 'scripts'))\n for script in scripts_to_save:\n dst_file = os.path.join(path, 'scripts', os.path.basename(script))\n shutil.copyfile(script, dst_file)\n\n"
] |
[
[
"numpy.clip",
"torch.load",
"torch.from_numpy",
"numpy.ones",
"torch.save",
"torch.cuda.is_available",
"numpy.random.randint"
]
] |
giuscri/TensorFlow-Tutorials
|
[
"309f7afc803126e882ad185a32f3b39e18452044"
] |
[
"eleven.py"
] |
[
"import tensorflow as tf\nimport inception\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom sys import argv, stderr\nfrom PIL import Image\nfrom PIL import ImageFilter\n\n\"\"\"\nexercises:\n Try using some of your own images.\n > ✔\n\n Try other arguments for adversary_example().\n Try another target-class, noise-limit and\n required score. What is the result?\n > I've tested few classes: it doesn't seem\n to change how good this trick is. Changing\n required score doesn't seem to speed gradient\n descent too much. Reducing the noise limit\n makes harder to reach the needed score, as\n expected.\n\n Do you think it is possible to generate\n adversarial noise that would cause\n mis-classification for any desired\n target-class? How would you prove your theory?\n > - \n\n Try another formula for calculating the\n step-size in find_adversary_noise(). Can you\n make the optimization converge faster?\n > Fastest I got was `20 / max(1e-10, np.abs(g).max())`\n\n Try blurring the noisy input-image right\n before it is input into the neural network.\n Does it remove the adversarial noise and cause\n correct classification again?\n > No, seems there's no relation.\n\n Try lowering the bit-depth of the noisy input\n image instead of blurring it. Does it remove\n the adversarial noise and result in correct\n classification? For example if you only allow\n 16 or 32 colour-levels for Red, Green and\n Blue, whereas normally there are 255 levels.\n > This seems to improve the result.\n\n Do you think your noise-removal also works for\n hand-written digits in the MNIST data-set, or\n for strange geometric shapes? These are\n sometimes called 'fooling images', do an\n internet search.\n > Yes.\n\n Can you find adversarial noise that would work\n for all images, so you don't have to find\n adversarial noise specifically for each image?\n How would you do this?\n > Don't know. Feels too good to be true. \n\n Can you implement the optimization in\n find_adversary_noise() directly in TensorFlow\n instead of using NumPy? You would need to make\n the noise a variable in the TensorFlow graph\n as well, so it can be optimized by TensorFlow.\n > -\n\n Explain to a friend what Adversarial Examples\n are and how the program finds them. \n > Instead of training a model to recognize a\n class of images, you can use gradient descent\n (or anything that can minimize a function\n iteratively I guess) to minimize the loss\n function between a target output and what's\n classified by the model, by changing the\n image. This is interesting as the resulting\n image that _fools_ the classifier it's\n indistinguishable from the original image by a\n human.\n\"\"\"\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\ndef minmax_scale(x):\n return (x - x.min()) / (x.max() - x.min())\n\ndef show_images(img, noisy_img, noise, clsname_source, clsname_target,\n sourcescore, original_sourcescore, targetscore):\n \"\"\"Shows img, noisy_img, noise in a single figure.\"\"\"\n\n figure, axes = plt.subplots(1, 3)\n\n a = axes.flat[0]\n a.imshow(img / 255.0)\n a.set_xlabel('Original image:\\n{} ({:.2%})'.format(\n clsname_source, original_sourcescore\n ))\n\n a = axes.flat[1]\n a.imshow(noisy_img / 255.0)\n a.set_xlabel('Image + Noise:\\n{} ({:.2%})'.format(\n clsname_target, targetscore\n ))\n\n a = axes.flat[2]\n a.imshow(minmax_scale(noise))\n a.set_xlabel('Amplified noise')\n\n for a in axes.flat:\n a.set_xticks([])\n a.set_yticks([])\n\n figure.show()\n\ndef adversary_noise(model, session, image_path, cls_target,\n score=0.99, iterations=100, noiselim=3.0, blur=False, depth=255):\n \"\"\"\n Computes adversary noise.\n \n This allows to fool Inception `model`\n in classifying image at `img_path`\n as being in class `cls_target` with\n a score of `score`.\n\n It basically applies gradient descent\n on the loss function computed between\n the neural network output and one-hot\n encoded `cls_target` in respect to\n the image loaded from `img_path`.\n \"\"\"\n\n feed_dict = model._create_feed_dict(image_path=image_path)\n predicted, image = session.run([\n model.y_pred,\n model.resized_image\n ], feed_dict=feed_dict)\n\n if blur:\n image = image.squeeze()\n image = image.astype('uint8')\n image = Image.fromarray(image)\n image = image.filter(ImageFilter.GaussianBlur(radius=3))\n image = np.array(image)\n image = image.reshape((1, 299, 299, 3))\n\n assert depth > 0, \"minimum depth is 1\"\n if depth < 255:\n image = image.squeeze()\n image = np.ceil(image / (255 / depth)) * 255 / depth\n image = image.reshape((1, 299, 299, 3))\n # Reduce range of values per channel\n # by playing with ceils.\n\n predicted = np.squeeze(predicted)\n original_sourcescore = predicted.max()\n cls_source = np.argmax(predicted)\n\n clsname_source = model.name_lookup.cls_to_name(\n cls_source, only_first_name=True)\n clsname_target = model.name_lookup.cls_to_name(\n cls_target, only_first_name=True)\n\n with model.graph.as_default():\n # You need to take tensors from the Inception graph.\n\n cls_target_pholder = tf.placeholder(dtype=tf.int32)\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=model.y_logits, labels=[cls_target_pholder])\n\n gradient = tf.gradients(loss, model.resized_image)\n # You want to apply gradient descent on\n # the loss between nn output and one-hot\n # encoded target. In order to modify\n # `image` you'll leverage the noise that\n # gets added to the img.\n\n noise = 0\n for _ in range(iterations):\n noisy_image = image + noise\n noisy_image = np.clip(a=noisy_image, a_min=0.0, a_max=255.0)\n feed_dict = {\n model.tensor_name_resized_image: noisy_image,\n cls_target_pholder: cls_target\n }\n predicted, g = session.run([model.y_pred, gradient],\n feed_dict=feed_dict)\n\n predicted = np.squeeze(predicted)\n sourcescore = predicted[cls_source]\n targetscore = predicted[cls_target]\n\n g = np.array(g).squeeze()\n\n stepsize = 7 / max(1e-10, np.abs(g).max())\n\n if targetscore >= score: break\n\n noise = noise - stepsize * g\n noise = np.clip(a=noise, a_min=-noiselim, a_max=noiselim)\n\n return (\n image.squeeze(),\n noisy_image.squeeze(),\n noise,\n clsname_source,\n clsname_target,\n sourcescore,\n original_sourcescore,\n targetscore,\n )\n\nif __name__ == '__main__':\n if len(argv) < 2:\n image_path = './images/parrot_cropped1.jpg'\n else:\n image_path = argv[1]\n\n print(f\"using {image_path}\", file=stderr)\n\n model = inception.Inception()\n\n with tf.Session(graph=model.graph) as session:\n n = adversary_noise(model, session, image_path, 400, 0.90, depth=10)\n show_images(*n)\n\n model.close()\n"
] |
[
[
"numpy.abs",
"numpy.clip",
"numpy.squeeze",
"tensorflow.gradients",
"tensorflow.placeholder",
"matplotlib.pyplot.subplots",
"numpy.ceil",
"numpy.argmax",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.Session",
"numpy.array"
]
] |
praveenck06/Hippocampal-Volume-Quantification-in-Alzheimer-s-Progression
|
[
"6944ebdf681b35e78b84cd676227f0c396c6a770"
] |
[
"ModelTraining/src/experiments/UNetExperiment.py"
] |
[
"\"\"\"\nThis module represents a UNet experiment and contains a class that handles\nthe experiment lifecycle\n\"\"\"\nimport os\nimport time\n\nimport numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom data_prep.SlicesDataset import SlicesDataset\nfrom utils.utils import log_to_tensorboard\nfrom utils.volume_stats import Dice3d, Jaccard3d,Specificity,Sensitivity\nfrom networks.RecursiveUNet import UNet\nfrom inference.UNetInferenceAgent import UNetInferenceAgent\n\nclass UNetExperiment:\n \"\"\"\n This class implements the basic life cycle for a segmentation task with UNet(https://arxiv.org/abs/1505.04597).\n The basic life cycle of a UNetExperiment is:\n\n run():\n for epoch in n_epochs:\n train()\n validate()\n test()\n \"\"\"\n def __init__(self, config, split, dataset):\n self.n_epochs = config.n_epochs\n self.split = split\n self._time_start = \"\"\n self._time_end = \"\"\n self.epoch = 0\n self.name = config.name\n\n # Create output folders\n dirname = f'{time.strftime(\"%Y-%m-%d_%H%M\", time.gmtime())}_{self.name}'\n self.out_dir = os.path.join(config.test_results_dir, dirname)\n os.makedirs(self.out_dir, exist_ok=True)\n\n # Create data loaders\n # TASK: SlicesDataset class is not complete. Go to the file and complete it. \n # Note that we are using a 2D version of UNet here, which means that it will expect\n # batches of 2D slices.\n self.train_loader = DataLoader(SlicesDataset(dataset[split[\"train\"]]),\n batch_size=config.batch_size, shuffle=True, num_workers=0)\n self.val_loader = DataLoader(SlicesDataset(dataset[split[\"val\"]]),\n batch_size=config.batch_size, shuffle=True, num_workers=0)\n\n # we will access volumes directly for testing\n self.test_data = dataset[split[\"test\"]]\n\n # Do we have CUDA available?\n if not torch.cuda.is_available():\n print(\"WARNING: No CUDA device is found. This may take significantly longer!\")\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Configure our model and other training implements\n # We will use a recursive UNet model from German Cancer Research Center, \n # Division of Medical Image Computing. It is quite complicated and works \n # very well on this task. Feel free to explore it or plug in your own model\n self.model = UNet(num_classes=3)\n self.model.to(self.device)\n\n # We are using a standard cross-entropy loss since the model output is essentially\n # a tensor with softmax'd prediction of each pixel's probability of belonging \n # to a certain class\n self.loss_function = torch.nn.CrossEntropyLoss()\n\n # We are using standard SGD method to optimize our weights\n self.optimizer = optim.Adam(self.model.parameters(), lr=config.learning_rate)\n # Scheduler helps us update learning rate automatically\n self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min')\n\n # Set up Tensorboard. By default it saves data into runs folder. You need to launch\n self.tensorboard_train_writer = SummaryWriter(comment=\"_train\")\n self.tensorboard_val_writer = SummaryWriter(comment=\"_val\")\n\n def train(self):\n \"\"\"\n This method is executed once per epoch and takes \n care of model weight update cycle\n \"\"\"\n print(f\"Training epoch {self.epoch}...\")\n self.model.train()\n\n # Loop over our minibatches\n for i, batch in enumerate(self.train_loader):\n self.optimizer.zero_grad()\n\n # TASK: You have your data in batch variable. Put the slices as 4D Torch Tensors of \n # shape [BATCH_SIZE, 1, PATCH_SIZE, PATCH_SIZE] into variables data and target. \n # Feed data to the model and feed target to the loss function\n# print(\"batch shape:\",batch.shape)\n data = batch['image'].to(device=self.device, dtype=torch.float)\n target = batch['seg'].to(device=self.device)\n# print(\"data shape:\",data.shape)\n# print(\"target shape:\",target.shape)\n prediction = self.model(data)\n\n # We are also getting softmax'd version of prediction to output a probability map\n # so that we can see how the model converges to the solution\n prediction_softmax = F.softmax(prediction, dim=1)\n\n loss = self.loss_function(prediction, target[:, 0, :, :])\n\n # TASK: What does each dimension of variable prediction represent?\n # ANSWER: dim 0: batch size \n #dim 1: x axis of segmented mask \n #dim 2: y axis of segmented mask, \n #dim 3: z axis of segmented mask\n\n loss.backward()\n self.optimizer.step()\n\n if (i % 10) == 0:\n # Output to console on every 10th batch\n print(f\"\\nEpoch: {self.epoch} Train loss: {loss}, {100*(i+1)/len(self.train_loader):.1f}% complete\")\n\n counter = 100*self.epoch + 100*(i/len(self.train_loader))\n\n # You don't need to do anything with this function, but you are welcome to \n # check it out if you want to see how images are logged to Tensorboard\n # or if you want to output additional debug data\n log_to_tensorboard(\n self.tensorboard_train_writer,\n loss,\n data,\n target,\n prediction_softmax,\n prediction,\n counter)\n\n print(\".\", end='')\n\n print(\"\\nTraining complete\")\n\n def validate(self):\n \"\"\"\n This method runs validation cycle, using same metrics as \n Train method. Note that model needs to be switched to eval\n mode and no_grad needs to be called so that gradients do not \n propagate\n \"\"\"\n print(f\"Validating epoch {self.epoch}...\")\n\n # Turn off gradient accumulation by switching model to \"eval\" mode\n self.model.eval()\n loss_list = []\n\n with torch.no_grad():\n for i, batch in enumerate(self.val_loader):\n \n # TASK: Write validation code that will compute loss on a validation sample\n # <YOUR CODE HERE>\n data = batch['image'].to(device=self.device, dtype=torch.float)\n target = batch['seg'].to(device=self.device)\n prediction = self.model(data)\n prediction_softmax = F.softmax(prediction, dim=1)\n loss = self.loss_function(prediction, target[:, 0, :, :])\n# inference_agent = UNetInferenceAgent(model=self.model, device=self.device)\n \n# image_volume = np.squeeze(batch[\"image\"].detach().cpu().numpy())\n# segment_volume = np.squeeze(batch[\"seg\"].detach().cpu().numpy())\n# pred_label = inference_agent.single_volume_inference(image_volume)\n# dc = Dice3d(pred_label, segment_volume)\n# jc = Jaccard3d(pred_label, segment_volume)\n# sensitivity = Sensitivity(pred_label,segment_volume)\n# specificity = Specificity(pred_label, segment_volume)\n \n print(f\"Batch {i}. Data shape {data.shape} Loss {loss}\")\n# Dice {round(dc,2)} Jaccard {round(jc,2)} Sensi {round(sensitivity,2)} Speci {round(specificity,2)}\")\n\n # We report loss that is accumulated across all of validation set\n loss_list.append(loss.item())\n\n self.scheduler.step(np.mean(loss_list))\n\n log_to_tensorboard(\n self.tensorboard_val_writer,\n np.mean(loss_list),\n data,\n target,\n prediction_softmax, \n prediction,\n (self.epoch+1) * 100)\n print(f\"Validation complete\")\n\n def save_model_parameters(self):\n \"\"\"\n Saves model parameters to a file in results directory\n \"\"\"\n path = os.path.join(self.out_dir, \"model.pth\")\n\n torch.save(self.model.state_dict(), path)\n\n def load_model_parameters(self, path=''):\n \"\"\"\n Loads model parameters from a supplied path or a\n results directory\n \"\"\"\n if not path:\n model_path = os.path.join(self.out_dir, \"model.pth\")\n else:\n model_path = path\n\n if os.path.exists(model_path):\n self.model.load_state_dict(torch.load(model_path))\n else:\n raise Exception(f\"Could not find path {model_path}\")\n\n def run_test(self):\n \"\"\"\n This runs test cycle on the test dataset.\n Note that process and evaluations are quite different\n Here we are computing a lot more metrics and returning\n a dictionary that could later be persisted as JSON\n \"\"\"\n print(\"Testing...\")\n self.model.eval()\n\n # In this method we will be computing metrics that are relevant to the task of 3D volume\n # segmentation. Therefore, unlike train and validation methods, we will do inferences\n # on full 3D volumes, much like we will be doing it when we deploy the model in the \n # clinical environment. \n\n # TASK: Inference Agent is not complete. Go and finish it. Feel free to test the class\n # in a module of your own by running it against one of the data samples\n inference_agent = UNetInferenceAgent(model=self.model, device=self.device)\n\n out_dict = {}\n out_dict[\"volume_stats\"] = []\n dc_list = []\n jc_list = []\n sensitivity_list = []\n specificity_list = []\n\n # for every in test set\n for i, x in enumerate(self.test_data):\n pred_label = inference_agent.single_volume_inference(x[\"image\"])\n \n # We compute and report Dice and Jaccard similarity coefficients which \n # assess how close our volumes are to each other\n\n # TASK: Dice3D and Jaccard3D functions are not implemented. \n # Complete the implementation as we discussed\n # in one of the course lessons, you can look up definition of Jaccard index \n # on Wikipedia. If you completed it\n # correctly (and if you picked your train/val/test split right ;)),\n # your average Jaccard on your test set should be around 0.80\n\n dc = Dice3d(pred_label, x[\"seg\"])\n jc = Jaccard3d(pred_label, x[\"seg\"])\n sensitivity = Sensitivity(pred_label, x[\"seg\"])\n specificity = Specificity(pred_label, x[\"seg\"])\n dc_list.append(dc)\n jc_list.append(jc)\n sensitivity_list.append(sensitivity)\n specificity_list.append(specificity)\n \n\n # STAND-OUT SUGGESTION: By way of exercise, consider also outputting:\n # * Sensitivity and specificity (and explain semantic meaning in terms of \n # under/over segmenting)\n # * Dice-per-slice and render combined slices with lowest and highest DpS\n # * Dice per class (anterior/posterior)\n\n out_dict[\"volume_stats\"].append({\n \"filename\": x['filename'],\n \"dice\": dc,\n \"jaccard\": jc,\n \"sensitivity\":sensitivity,\n \"specificity\":specificity\n })\n print(f\"{x['filename']} Dice {dc:.4f}. {100*(i+1)/len(self.test_data):.2f}% complete\")\n\n out_dict[\"overall\"] = {\n \"mean_dice\": np.mean(dc_list),\n \"mean_jaccard\": np.mean(jc_list),\n \"mean_sensitivity\": np.mean(sensitivity_list),\n \"mean_specificity\": np.mean(specificity_list)\n }\n print(out_dict[\"overall\"])\n print(\"\\nTesting complete.\")\n return out_dict\n\n def run(self):\n \"\"\"\n Kicks off train cycle and writes model parameter file at the end\n \"\"\"\n self._time_start = time.time()\n\n print(\"Experiment started.\")\n\n # Iterate over epochs\n for self.epoch in range(self.n_epochs):\n self.train()\n self.validate()\n # save model for inferencing\n self.save_model_parameters()\n\n self._time_end = time.time()\n print(f\"Run complete. Total time: {time.strftime('%H:%M:%S', time.gmtime(self._time_end - self._time_start))}\")\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.nn.functional.softmax",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.load",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"numpy.mean"
]
] |
toddrme2178/pyccel
|
[
"deec37503ab0c5d0bcca1a035f7909f7ce8ef653",
"deec37503ab0c5d0bcca1a035f7909f7ce8ef653"
] |
[
"tests/epyccel/modules/loops.py",
"tests/macro/scripts/blas/dswap.py"
] |
[
"from pyccel.decorators import types\n\n#==============================================================================\n\n@types( int )\ndef sum_natural_numbers( n ):\n x = 0\n for i in range( 1, n+1 ):\n x += i\n return x\n\n# ...\n@types( int )\ndef factorial( n ):\n x = 1\n for i in range( 2, n+1 ):\n x *= i\n return x\n\n# ...\n@types( int )\ndef fibonacci( n ):\n x = 0\n y = 1\n for i in range( n ):\n z = x+y\n x = y\n y = z\n return x\n\n# ...\n@types( int )\ndef double_loop( n ):\n x = 0\n for i in range( 3, 10 ):\n x += 1\n y = n*x\n for j in range( 4, 15 ):\n z = x-y\n return z\n\n# ...\n@types( 'int[:,:](order=C)' )\ndef double_loop_on_2d_array_C( z ):\n\n from numpy import shape\n\n s = shape( z )\n m = s[0]\n n = s[1]\n \n for i in range( m ):\n for j in range( n ):\n z[i,j] = i-j\n\n\n# ...\n@types( 'int[:,:](order=F)' )\ndef double_loop_on_2d_array_F( z ):\n\n from numpy import shape\n\n s = shape( z )\n m = s[0]\n n = s[1]\n\n for i in range( m ):\n for j in range( n ):\n z[i,j] = i-j\n\n# ...\n@types( 'int[:,:](order=C)' )\ndef product_loop_on_2d_array_C( z ):\n\n from numpy import shape\n from itertools import product\n\n s = shape( z )\n m = s[0]\n n = s[1]\n\n x = [i for i in range(m)]\n y = [j for j in range(n)]\n\n for i,j in product( x, y ):\n z[i,j] = i-j\n\n# ...\n@types( 'int[:,:](order=F)' )\ndef product_loop_on_2d_array_F( z ):\n\n from numpy import shape\n from itertools import product\n\n s = shape( z )\n m = s[0]\n n = s[1]\n\n x = [i for i in range(m)]\n y = [j for j in range(n)]\n\n for i,j in product( x, y ):\n z[i,j] = i-j\n\n# ...\n@types( 'int[:]' )\ndef map_on_1d_array( z ):\n\n @types( int )\n def f( x ):\n return x+5\n\n res = 0\n for v in map( f, z ):\n res *= v\n\n return res\n\n# ...\n@types( 'int[:]' )\ndef enumerate_on_1d_array( z ):\n\n res = 0\n for i,v in enumerate( z ):\n res += v*i\n\n return res\n\n# ...\n@types( int )\ndef zip_prod( m ):\n\n x = [ i for i in range(m)]\n y = [2*j for j in range(m)]\n\n res = 0\n for i1,i2 in zip( x, y ):\n res += i1*i2\n\n return res\n",
"from pyccel.stdlib.internal.blas import dswap\nfrom numpy import zeros\n\nn = 4\n\na = zeros(n, 'double')\nb = zeros(n, 'double')\n\na[0] = 2.0\na[1] = 3.0\na[2] = 4.0\na[3] = 5.0\n\nb[0] = 5.0\nb[1] = 4.0\nb[2] = 9.0\nb[3] = 2.0\n\nprint('--- before swap')\nprint(a)\nprint(b)\n\n#$ header macro (x, y), _dswap(x, y, n=x.shape, incx=1, incy=1) := dswap(n, x, incx, y, incy)\na,b = _dswap(a, b)\n\nprint('--- after swap')\nprint(a)\nprint(b)\n"
] |
[
[
"numpy.shape"
],
[
"numpy.zeros"
]
] |
linhvannguyen/PhDworks
|
[
"9336e5257f5ddc3c899a6fb68b1028c905d13ff9"
] |
[
"codes/isotropic/regression/funcs/KRR_poly_cv_alpha_degree_sspacing3_tspacing4.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 3 14:20:44 2016\n\n@author: nguyen\n\"\"\"\nimport numpy as np\nfrom netCDF4 import Dataset\n\n# Constants\nNh = 96\nNt = 37\nsspacing = 3\ntspacing = 4\n\nHTLS_sknots = np.arange(0,Nh,sspacing)\nHTHS_sknots = np.arange(0,Nh,1)\nLTHS_tknots = np.arange(0,Nh,tspacing)\nNl = len(HTLS_sknots)\nNs = len(LTHS_tknots)\n\nDh = Nh*Nh\nDl = Nl*Nl\n\nN = Nt*Ns\n\n#Load all training data\nXh_tr = np.zeros((N, Dh))\nXl_tr = np.zeros((N, Dl))\nncfile1 = Dataset('/data/ISOTROPIC/data/data_downsampled4.nc','r')\nfor t in range(Nt):\n count = 0\n for i in LTHS_tknots:\n xh = np.array(ncfile1.variables['velocity_x'][t,0:Nh,0:Nh,i])\n xl = xh[0:-1:sspacing,0:-1:sspacing]\n Xh_tr[t*Ns + count,:] = np.reshape(xh,(1, Dh))\n Xl_tr[t*Ns + count,:] = np.reshape(xl,(1, Dl))\n count = count + 1\nncfile1.close()\n\n\n# normalized: centered, variance 1\nmea_l = np.zeros(Dl)\nsig_l = np.zeros(Dl)\nfor k in range(Dl):\n mea_l[k] = np.mean(Xl_tr[:,k])\n sig_l[k] = np.std(Xl_tr[:,k])\n Xl_tr[:,k] = (Xl_tr[:,k]-mea_l[k])/sig_l[k] \n \nmea_h = np.zeros(Dh)\nsig_h = np.zeros(Dh)\nfor k in range(Dh):\n mea_h[k] = np.mean(Xh_tr[:,k])\n sig_h[k] = np.std(Xh_tr[:,k])\n Xh_tr[:,k] = (Xh_tr[:,k]-mea_h[k])/sig_h[k] \n\n\nfrom sklearn.kernel_ridge import KernelRidge\n\n\n# Use GridSearchCV to get a rough idea of parameters\nfrom sklearn.grid_search import GridSearchCV\n\nalphas = np.append(0,np.logspace(-7, -1, 50))\ndegrees = np.arange(1, 5, 1)\n\nkr = GridSearchCV(KernelRidge(kernel='poly'), cv=6, param_grid={\"alpha\": alphas, \"degree\": degrees})\nkr.fit(Xl_tr, Xh_tr)\n\nprint('\\n Best estimator:', kr.best_estimator_)\n\n# save to .mat file\nimport scipy.io as io\nio.savemat('/data/ISOTROPIC/regression/KRR_poly_cv_alpha_degree_sspacing3_tspacing4.mat', \n dict(alphas=alphas, degrees=degrees, KRR_lambda_opt=kr.best_estimator_.alpha,\n KRR_deg_opt=kr.best_estimator_.degree))\n"
] |
[
[
"numpy.logspace",
"numpy.arange",
"numpy.reshape",
"sklearn.kernel_ridge.KernelRidge",
"numpy.std",
"numpy.mean",
"numpy.array",
"numpy.zeros"
]
] |
activeshadow/HELICS-Examples
|
[
"750cd111eb11efc681d2575b4919759bdce38e51"
] |
[
"python/BLOSEM_tutorial/EVComboFed.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 8/27/2020\n\nThis is a simple EV federate that models a set of EV terminals in an\nEV charging garage. Each terminal can support charging at levels 1, 2,\nand 3 but the EVs that come to charge have a randomly assigned charging\nlevel.\n\nManaging these terminals is a centralized EV Controller that receives from\nthe EV the current SOC and sends a command back to the terminal to continue\ncharging or stop charging (once the EV is full). Once an EV is full, a new\nEV is moved into the charging terminal (with a randomly assigned charging\nlevel) and begins charging.\n\n@author: Allison M. Campbell\nallison.m.campbell@pnnl.gov\n\"\"\"\n\nimport helics as h\nimport random\nimport string\nimport time\nfrom datetime import datetime, timedelta\nimport json\nimport logging\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\ndef destroy_federate(fed):\n '''\n As part of ending a HELICS co-simulation it is good housekeeping to\n formally destroy a federate. Doing so informs the rest of the\n federation that it is no longer a part of the co-simulation and they\n should proceed without it (if applicable). Generally this is done\n when the co-simulation is complete and all federates end execution\n at more or less the same wall-clock time.\n\n :param fed: Federate to be destroyed\n :return: (none)\n '''\n status = h.helicsFederateFinalize(fed)\n h.helicsFederateFree(fed)\n h.helicsCloseLibrary()\n print(\"EV: Federate finalized\")\n\n\ndef get_new_EV(numEVs):\n '''\n Using hard-coded probabilities, a distribution of EVs with support\n for specific charging levels are generated. The number of EVs\n generated is defined by the user.\n\n :param numEVs: Number of EVs\n :return\n numLvL1: Number of new EVs that will charge at level 1\n numLvL2: Number of new EVs that will charge at level 2\n numLvL3: Number of new EVs that will charge at level 3\n listOfEVs: List of all EVs (and their charging levels) generated\n\n '''\n\n # Probabilities of a new EV charging at the specified level.\n lvl1 = 0.1\n lvl2 = 0.6\n lvl3 = 0.3\n listOfEVs = np.random.choice([1,2,3],numEVs,p=[lvl1,lvl2,lvl3]).tolist()\n numLvl1 = listOfEVs.count(1)\n numLvl2 = listOfEVs.count(2)\n numLvl3 = listOfEVs.count(3)\n\n return numLvl1,numLvl2,numLvl3,listOfEVs\n\n\nif __name__ == \"__main__\":\n np.random.seed(1)\n\n ############## Registering federate from json ##########################\n name = \"EV_federate\"\n fed = h.helicsCreateCombinationFederateFromConfig(\"EVconfig.json\")\n federate_name = h.helicsFederateGetName(fed)\n logging.info(f'Created federate {federate_name}')\n end_count = h.helicsFederateGetEndpointCount(fed)\n logging.info(f'\\tNumber of endpoints: {end_count}')\n sub_count = h.helicsFederateGetInputCount(fed)\n logging.info(f'\\tNumber of subscriptions: {sub_count}')\n pub_count = h.helicsFederateGetPublicationCount(fed)\n logging.info(f'\\tNumber of publications: {pub_count}')\n print(f'Created federate {federate_name}')\n print(f'\\tNumber of endpoints: {end_count}')\n print(f'\\tNumber of subscriptions: {sub_count}')\n print(f'\\tNumber of publications: {pub_count}')\n\n # Diagnostics to confirm JSON config correctly added the required\n # endpoints, publications, and subscriptions.\n endid = {}\n for i in range(0, end_count):\n endid[i] = h.helicsFederateGetEndpointByIndex(fed, i)\n end_name = h.helicsEndpointGetName(endid[i])\n logger.info(f'\\tRegistered Endpoint ---> {end_name}')\n subid = {}\n for i in range(0, sub_count):\n subid[i] = h.helicsFederateGetInputByIndex(fed, i)\n sub_name = h.helicsSubscriptionGetKey(subid[i])\n logger.info(f'\\tRegistered subscription---> {sub_name}')\n\n pubid = {}\n for i in range(0, pub_count):\n pubid[i] = h.helicsFederateGetPublicationByIndex(fed, i)\n pub_name = h.helicsPublicationGetKey(pubid[i])\n logger.info(f'\\tRegistered publication---> {pub_name}')\n\n\n ############## Entering Execution Mode ##################################\n h.helicsFederateEnterExecutingMode(fed)\n logger.info('Entered HELICS execution mode')\n\n # Definition of charging power level (in kW) for level 1, 2, 3 chargers\n charge_rate = [1.8,7.2,50]\n\n\n\n # All EVs are assumed to have the same size batteries (approx. the\n # size of a Nissan Leaf\n batt_size = 62 # kWh\n\n # Charging current at this value indicates the EV is charging in constant\n # current mode. We're going to assume this value is invariant with\n # charging level and it is the charging voltage that changes.\n # TODO: Define this value for reals\n critical_charging_current = 4.5\n\n # SOC at which the charging mode changes from constant current to\n # constant voltage\n critical_soc = 0.75\n\n # Charging adjustment gain factor.\n voltage_adj_gain = 0.01\n\n hours = 24*7 # one week\n total_interval = int(60 * 60 * hours)\n update_interval = 60 # updates every minute\n grantedtime = -1\n\n # Generate an initial fleet of EVs, one for each previously defined\n # endpoint. This gives each EV a unique link to the EV controller\n # federate.\n numLvl1,numLvl2,numLvl3,EVlist = get_new_EV(end_count)\n\n # This is the voltage that we'll charge at when we reach the critical\n # charging current and switch to constant voltage charging mode.\n constant_voltage = {}\n for j, EV in enumerate(EVlist):\n constant_voltage[j] = (charge_rate[EV-1] * 1000) / critical_charging_current\n logger.info(f'constant voltage value: {constant_voltage[j]}')\n\n # Set the SOCs of the initial EV fleet to arbitrary values\n currentsoc = np.linspace(0.1,0.5,num=end_count)\n\n # Data collection lists\n time_sim = []\n power = []\n\n # Blocking call for a time request at simulation time 0\n initial_time = 60\n logger.debug(f'Requesting initial time {initial_time}')\n t = h.helicsFederateRequestTime(fed, initial_time )\n logger.debug(f'Granted time {t}')\n\n\n # Defining the intial charging current by assuming we're starting\n # in the constant_voltage charging range. If we're still in the\n # constant current range the battery model will come back with the\n # current that is too high and we'll drop the charging voltage down.\n charging_voltage = {}\n new_EV = {}\n for j in range(0, end_count):\n charging_voltage[j] = constant_voltage[j]\n new_EV[j] = False\n\n # Once granted an initial time, send the initial SOCs to the EV\n # Controller\n for j in range(0,end_count):\n destination_name = str(h.helicsEndpointGetDefaultDestination(endid[j]))\n h.helicsEndpointSendMessageRaw(endid[j], \"\", str(currentsoc[j]).encode()) #\n\n\n ########## Main co-simulation loop ########################################\n # As long as granted time is in the time range to be simulated...\n while t < total_interval:\n\n # Time request for the next physical interval to be simulated\n requested_time = (t+update_interval)\n logger.debug(f'Requesting time {requested_time}')\n grantedtime = h.helicsFederateRequestTime (fed, requested_time)\n logger.debug(f'Granted time {grantedtime}')\n\n t = grantedtime\n\n for j in range(0,end_count):\n\n logger.debug(f'EV {j+1} time {t}')\n # Model the physics of the battery charging. This happens\n # every time step whether a message comes in or not and always\n # uses the latest value provided by the battery model.\n charging_current = h.helicsInputGetDouble((subid[j]))\n logger.debug(f'\\tCharging current: {charging_current:.2f} from '\n f'input {h.helicsSubscriptionGetKey(subid[j])}')\n\n if new_EV[j]:\n charging_voltage[j] = 0\n logger.debug(f'New EV; setting charging voltage to 0')\n new_EV[j] = False\n else:\n ############### SOC estimation ###################################\n # Estimate SOC based on charging current and voltage\n if charging_current == 0:\n # Just connected a new EV so going to charge at a\n # nominal level and see what happens.\n # Making up the SOC level just so the controller doesn't\n # disconnect the EV prematurely.\n charging_voltage[j] = constant_voltage[j]\n currentsoc[j] = 0\n\n elif charging_current >= critical_charging_current:\n # SOC is estimated by some function of charging voltage\n # SOC in this range below the critical_soc. When the charging\n # voltage reaches the constant_voltage value we are,\n # by definition, assumed to be at the critical SOC value\n voltage_diff = constant_voltage[j] - charging_voltage[j]\n voltage_factor = 1 - (voltage_diff / constant_voltage[j])\n # TODO: Still need to implement the function that maps\n # charging voltage to SOC. Need to ensure we don't exceed\n # the voltage rating for the level of charger.\n # implement json for value federate\n #\n\n else:\n # SOC estimated based on charging current\n # As charging continues beyong the critical SOC, the voltage\n # will remain constant but the charging current will decrease\n current_diff = critical_charging_current - charging_current\n # The charging current is highest when the SOC is lowest\n # (in the constant voltage charging regime) Small\n # differences translate into low SOCs above 0.75\n current_factor = current_diff / critical_charging_current\n logger.debug(f'\\t Current factor: {current_factor:.2f}')\n currentsoc[j] = critical_soc + (current_factor / (1 -\n critical_soc) )\n logger.debug(f'\\t EV SOC estimate: {currentsoc[j]:.4f}')\n\n\n\n ######## Charging algorithm - Update charging voltage #############\n # Model a charging algorithm with constant current during low\n # SOC periods and constant voltage during high SOC periods\n # We won't know the SOC when we start charging so need to\n # estimate it from the current\n if charging_current != 0:\n # Don't need to do this if we just connected a new EV.\n # Once the battery is providing real charging currents\n # we'll estimate the new charging voltage.\n if charging_current > critical_charging_current:\n # Constant current charging\n # Stupid algorithm\n # TODO: implement a good-enough contant current charging\n # algorithm\n logger.debug(f'\\t Constant current charging')\n current_difference = critical_charging_current - charging_current\n current_factor_diff = current_difference / critical_charging_current\n charging_voltage[j] = charging_voltage[j] * \\\n voltage_adj_gain * ( 1+\n current_factor_diff)\n if charging_voltage[j] < 0:\n charging_voltage[j] = 1\n logger.debug(f'\\t Current factor difference:'\n f' {current_factor_diff:.2f}')\n logger.debug((f'\\t New charging voltage:'\n f' {charging_voltage[j]:.2f}'))\n else:\n # Constant voltage charging\n logger.debug(f'\\t Constant voltage charging')\n logger.debug(f'\\t New charging voltage: {charging_voltage[j]:.2f}')\n\n\n # Publish updated charging voltage\n h.helicsPublicationPublishDouble(pubid[j], charging_voltage[j])\n\n\n # Check for messages from EV Controller\n endpoint_name = h.helicsEndpointGetName(endid[j])\n if h.helicsEndpointHasMessage(endid[j]):\n msg = h.helicsEndpointGetMessageObject(endid[j])\n instructions = h.helicsMessageGetString(msg)\n logger.debug(f'\\tReceived message at endpoint {endpoint_name}'\n f' at time {t}'\n f' with command {instructions}')\n\n # Update charging state based on message from controller\n # The protocol used by the EV and the EV Controller is simple:\n # EV Controller sends \"1\" - keep charging\n # EV Controller sends andything else: stop charging\n # The default state is charging (1) so we only need to\n # do something if the controller says to stop\n if int(instructions) == 0:\n # Stop charing this EV and move another one into the\n # charging station\n _,_,_,newEVtype = get_new_EV(1)\n EVlist[j] = newEVtype[0]\n new_EV = True\n #currentsoc[j] = 0.05\n logger.info(f'\\tEV full; moving in new EV charging at '\n f'level {newEVtype[0]}')\n else:\n logger.debug(f'\\tNo messages at endpoint {endpoint_name} '\n f'recieved at '\n f'time {t}')\n\n # Send message to Controller with SOC every 15 minutes\n if t % 900 == 0:\n destination_name = str(\n h.helicsEndpointGetDefaultDestination(endid[j]))\n h.helicsEndpointSendMessageRaw(endid[j], \"\",\n str(currentsoc[j])) #\n logger.debug(f'Sent message from endpoint {endpoint_name}'\n f' at time {t}'\n f' with payload SOC {currentsoc[j]}')\n\n # Calculate the total power required by all chargers. This is the\n # primary metric of interest, to understand the power profile\n # and capacity requirements required for this charging garage.\n total_power = 0\n for j in range(0,end_count):\n total_power += charge_rate[(EVlist[j]-1)]\n\n # Data collection vectors\n time_sim.append(t)\n power.append(total_power)\n\n\n\n # Cleaning up HELICS stuff once we've finished the co-simulation.\n destroy_federate(fed)\n\n # Output graph showing the charging profile for each of the charging\n # terminals\n xaxis = np.array(time_sim)/3600\n yaxis = np.array(power)\n plt.figure()\n plt.plot(xaxis, yaxis, color='tab:blue', linestyle='-')\n plt.yticks(np.arange(0,120,5))\n plt.ylabel('kW')\n plt.grid(True)\n plt.xlabel('time (hr)')\n plt.title('Instantaneous Power Draw from 5 EVs')\n plt.show()\n"
] |
[
[
"numpy.random.seed",
"numpy.linspace",
"matplotlib.pyplot.title",
"numpy.arange",
"numpy.random.choice",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
landbroken/MyPaper
|
[
"e77581262aac210e6273c3647d091f7cf53eae4a"
] |
[
"src/lib_learning/logistics_learning.py"
] |
[
"#!/usr/bin/python3.9\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2022 LinYulong. All Rights Reserved \n#\n# @Time : 2022/2/7\n# @Author : LinYulong\n# @Description: 逻辑斯蒂回归模型Logistics regression\n# https://blog.csdn.net/u013421629/article/details/78470020\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\n# 创建特征列表。\ncolumn_names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape',\n 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli',\n 'Mitoses', 'Class']\n\n# 使用pandas.read_csv函数从互联网读取指定数据。\ndata = pd.read_csv(\n 'https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data',\n names=column_names)\n\n# print data\n# 将?替换为标准缺失值表示。\ndata = data.replace(to_replace='?', value=np.nan)\n# 丢弃带有缺失值的数据(只要有一个维度有缺失)。\ndata = data.dropna(how='any')\n\n# 输出data的数据量和维度。\n# print data.shape\n\n# 随机采样25%的数据用于测试,剩下的75%用于构建训练集合。\nx_train, x_test, y_train, y_test = train_test_split(data[column_names[1:10]], data[column_names[10]], test_size=0.25,\n random_state=33)\n\n# 查验训练样本的数量和类别分布。\n# print y_train.value_counts()\n\n# 查验测试样本的数量和类别分布。\n# print y_test.value_counts()\n\n# 标准化数据,保证每个维度的特征数据方差为1,均值为0。使得预测结果不会被某些维度过大的特征值而主导。\nss = StandardScaler()\nx_train = ss.fit_transform(x_train)\nx_test = ss.transform(x_test)\n\n# 初始化LogisticRegression\nlr = LogisticRegression()\n# 调用LogisticRegression中的fit函数/模块用来训练模型参数。\nlr.fit(x_train, y_train)\n# 使用训练好的模型lr对X_test进行预测,结果储存在变量lr_y_predict中。\nlr_y_predict = lr.predict(x_test)\nprint(\"=== lr_y_predict ===\")\nprint(lr_y_predict)\nprint(\"=== end lr_y_predict ===\")\n\n# 初始化GDClassifier。\nsgdc = SGDClassifier()\n# 调用SGDClassifier中的fit函数/模块用来训练模型参数。\nsgdc.fit(x_train, y_train)\n# 使用训练好的模型sgdc对X_test进行预测,结果储存在变量sgdc_y_predict中。\nsgdc_y_predict = sgdc.predict(x_test)\n\n# print sgdc_y_predict\n\n\n# 打印混淆矩阵\nlabels1 = list(set(lr_y_predict))\nconf_mat1 = confusion_matrix(y_test, lr_y_predict, labels=labels1)\nprint(\"Logistics regression\")\nprint(conf_mat1)\n\nlabels2 = list(set(sgdc_y_predict))\nconf_mat2 = confusion_matrix(y_test, sgdc_y_predict, labels=labels2)\nprint(\"sgdc_y_predict\")\nprint(conf_mat2)\n\n# 使用逻辑斯蒂回归模型自带的评分函数score获得模型在测试集上的准确性结果。\nprint('Accuracy of LR Classifier:', lr.score(x_test, y_test))\n# 利用classification_report模块获得LogisticRegression其他三个指标的结果。\nprint(classification_report(y_test, lr_y_predict, target_names=['Benign', 'Malignant']))\n\n# 使用随机梯度下降模型自带的评分函数score获得模型在测试集上的准确性结果。\nprint('Accuarcy of SGD Classifier:', sgdc.score(x_test, y_test))\n# 利用classification_report模块获得SGDClassifier其他三个指标的结果。\nprint(classification_report(y_test, sgdc_y_predict, target_names=['Benign', 'Malignant']))\n"
] |
[
[
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.confusion_matrix",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.classification_report",
"sklearn.linear_model.SGDClassifier"
]
] |
saikrishnarallabandi/Vocoding-Experiments
|
[
"f2e6c23ea5743ad1d1162669df3c34ccef0541e3"
] |
[
"lstmvc.py"
] |
[
"import numpy as np\nimport sys, os\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom model import *\n\n# Locations\nsrc_folder = '../feats/VCC2SF1'\ntgt_folder = '../feats/VCC2TF1'\n\nsrc_files = sorted(os.listdir(src_folder))\ntgt_files = sorted(os.listdir(tgt_folder))\n\n# \nbatch_size = 1\n\nclass vcc_dataset(Dataset):\n\n def __init__(self, src_array, tgt_array):\n self.src_array = src_array\n self.tgt_array = tgt_array\n\n def __getitem__(self, index):\n x = np.loadtxt(src_folder + '/' + self.src_array[index])\n y = np.loadtxt(tgt_folder + '/' + self.tgt_array[index])\n x_len = x.shape[0]\n y_len = y.shape[0]\n if x_len < y_len:\n return x, y[:x_len]\n elif y_len < x_len:\n return x[:y_len], y\n else:\n print (\" This cannot happen you fool!!\")\n return np.loadtxt(src_folder + '/' + self.src_array[index]), np.loadtxt(tgt_folder + '/' + self.tgt_array[index])\n\n def __len__(self):\n return len(self.src_array)\n \n\n\nvcc_train = vcc_dataset(src_files, tgt_files)\ntrain_loader = DataLoader(vcc_train,\n batch_size=batch_size,\n shuffle=True,\n num_workers=0\n )\nnet = Model_LstmFc_v3()\nnet.double()\nlearning_rate = 0.001\noptimizer = torch.optim.SGD(net.parameters(), lr=learning_rate, momentum= 0.9)\nmse_loss = nn.MSELoss()\n\ntotal_loss = 0\nfor i,(a,b) in enumerate(train_loader):\n a,b = Variable(a), Variable(b)\n #print(\"Shapes of a and b: \", a.shape, b.shape)\n c = net(a.double())\n loss = mse_loss(c, b) \n total_loss += loss.item()\n\n optimizer.zero_grad()\n loss.backward() \n optimizer.step()\n \n if i % 10 == 1:\n print (\" Loss after batch \", i, \" : \", total_loss* 1.0 / (i+1))\n"
] |
[
[
"torch.utils.data.DataLoader",
"numpy.loadtxt",
"torch.autograd.Variable"
]
] |
autoih/tensorflow
|
[
"4a1ae31d56c3c7f40232aace615945c29dcf9c38"
] |
[
"tensorflow/python/framework/ops.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Classes and functions used to construct graphs.\"\"\"\n# pylint: disable=g-bad-name\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport re\nimport sys\nimport threading\nimport types\n\nimport numpy as np\nimport six\nfrom six.moves import map # pylint: disable=redefined-builtin\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import function_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.core.framework import op_def_pb2\nfrom tensorflow.core.framework import versions_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python import pywrap_tensorflow as c_api\nfrom tensorflow.python import tf2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import core\nfrom tensorflow.python.eager import monitoring\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.framework import c_api_util\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import device as pydev\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import indexed_slices\nfrom tensorflow.python.framework import registry\nfrom tensorflow.python.framework import tensor_conversion_registry\nfrom tensorflow.python.framework import tensor_like\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import traceable_stack\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.platform import app\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import decorator_utils\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import function_utils\nfrom tensorflow.python.util import lock_util\nfrom tensorflow.python.util import memory\nfrom tensorflow.python.util import object_identity\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util import tf_stack\nfrom tensorflow.python.util.compat import collections_abc\nfrom tensorflow.python.util.deprecation import deprecated_args\nfrom tensorflow.python.util.lazy_loader import LazyLoader\nfrom tensorflow.python.util.tf_export import kwarg_only\nfrom tensorflow.python.util.tf_export import tf_export\nfrom tensorflow.tools.docs.doc_controls import do_not_generate_docs\n\nag_ctx = LazyLoader(\n \"ag_ctx\", globals(),\n \"tensorflow.python.autograph.core.ag_ctx\")\n\n\n# Temporary global switches determining if we should enable the work-in-progress\n# calls to the C API. These will be removed once all functionality is supported.\n_USE_C_API = True\n_USE_C_SHAPES = True\n\n_api_usage_gauge = monitoring.BoolGauge(\n \"/tensorflow/api/ops_eager_execution\",\n \"Whether ops.enable_eager_execution() is called.\")\n\n\n# pylint: disable=protected-access\n_TensorLike = tensor_like._TensorLike\n_DTYPES_INTERN_TABLE = dtypes._INTERN_TABLE\n# pylint: enable=protected-access\n\n\ndef tensor_id(tensor):\n \"\"\"Returns a unique identifier for this Tensor.\"\"\"\n return tensor._id # pylint: disable=protected-access\n\n\nclass _UserDeviceSpec(object):\n \"\"\"Store user-specified device and provide computation of merged device.\"\"\"\n\n def __init__(self, device_name_or_function):\n self._device_name_or_function = device_name_or_function\n self.display_name = str(self._device_name_or_function)\n self.function = device_name_or_function\n self.raw_string = None\n\n if isinstance(device_name_or_function, pydev.MergeDevice):\n self.is_null_merge = device_name_or_function.is_null_merge\n\n elif callable(device_name_or_function):\n self.is_null_merge = False\n dev_func = self._device_name_or_function\n func_name = function_utils.get_func_name(dev_func)\n func_code = function_utils.get_func_code(dev_func)\n if func_code:\n fname = func_code.co_filename\n lineno = func_code.co_firstlineno\n else:\n fname = \"unknown\"\n lineno = -1\n self.display_name = \"%s<%s, %d>\" % (func_name, fname, lineno)\n\n elif device_name_or_function is None:\n # NOTE(taylorrobie): This MUST be False. None signals a break in the\n # device stack, so `is_null_merge` must be False for such a case to\n # allow callers to safely skip over null merges without missing a None.\n self.is_null_merge = False\n\n else:\n self.raw_string = device_name_or_function\n self.function = pydev.merge_device(device_name_or_function)\n self.is_null_merge = self.function.is_null_merge\n\n # We perform this check in __init__ because it is of non-trivial cost,\n # and self.string_merge is typically called many times.\n self.fast_string_merge = isinstance(self.function, pydev.MergeDevice)\n\n def string_merge(self, node_def):\n if self.fast_string_merge:\n return self.function.shortcut_string_merge(node_def)\n\n return compat.as_str(_device_string(self.function(node_def)))\n\n\nclass NullContextmanager(object):\n\n def __init__(self, *args, **kwargs):\n pass\n\n def __enter__(self):\n pass\n\n def __exit__(self, type_arg, value_arg, traceback_arg):\n return False # False values do not suppress exceptions\n\n\ndef _override_helper(clazz_object, operator, func):\n \"\"\"Overrides (string) operator on Tensors to call func.\n\n Args:\n clazz_object: the class to override for; either Tensor or SparseTensor.\n operator: the string name of the operator to override.\n func: the function that replaces the overridden operator.\n\n Raises:\n ValueError: If operator has already been overwritten,\n or if operator is not allowed to be overwritten.\n \"\"\"\n existing = getattr(clazz_object, operator, None)\n if existing is not None:\n # Check to see if this is a default method-wrapper or slot wrapper which\n # will be true for the comparison operators.\n if not isinstance(existing, type(object.__lt__)):\n raise ValueError(\"operator %s cannot be overwritten again on class %s.\" %\n (operator, clazz_object))\n if operator not in Tensor.OVERLOADABLE_OPERATORS:\n raise ValueError(\"Overriding %s is disallowed\" % operator)\n setattr(clazz_object, operator, func)\n\n\ndef _as_graph_element(obj):\n \"\"\"Convert `obj` to a graph element if possible, otherwise return `None`.\n\n Args:\n obj: Object to convert.\n\n Returns:\n The result of `obj._as_graph_element()` if that method is available;\n otherwise `None`.\n \"\"\"\n conv_fn = getattr(obj, \"_as_graph_element\", None)\n if conv_fn and callable(conv_fn):\n return conv_fn()\n return None\n\n\n_TENSOR_LIKE_TYPES = tuple()\n\n\ndef is_dense_tensor_like(t):\n \"\"\"EXPERIMENTAL: Returns true if `t` implements the tensor interface.\n\n See `register_dense_tensor_like_type()` for the current definition of a\n \"tensor-like type\".\n\n Args:\n t: An object.\n\n Returns:\n True iff `t` is an instance of one of the registered \"tensor-like\" types.\n \"\"\"\n return isinstance(t, _TENSOR_LIKE_TYPES)\n\n\ndef register_dense_tensor_like_type(tensor_type):\n \"\"\"EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface.\n\n A \"tensor-like type\" can represent a single dense tensor, and implements\n the `name` and `dtype` properties.\n\n Args:\n tensor_type: A type implementing the tensor interface.\n\n Raises:\n TypeError: If `tensor_type` does not implement the tensor interface.\n \"\"\"\n try:\n if not isinstance(tensor_type.name, property):\n raise TypeError(\"Type %s does not define a `name` property\" %\n tensor_type.__name__)\n except AttributeError:\n raise TypeError(\"Type %s does not define a `name` property\" %\n tensor_type.__name__)\n try:\n if not isinstance(tensor_type.dtype, property):\n raise TypeError(\"Type %s does not define a `dtype` property\" %\n tensor_type.__name__)\n except AttributeError:\n raise TypeError(\"Type %s does not define a `dtype` property\" %\n tensor_type.__name__)\n # We expect this list to be small, so choose quadratic complexity\n # for registration, so that we have a tuple that can be used for\n # more efficient `isinstance` checks later.\n global _TENSOR_LIKE_TYPES\n _TENSOR_LIKE_TYPES = tuple(list(_TENSOR_LIKE_TYPES) + [tensor_type])\n\n\ndef uid():\n \"\"\"A unique (within this program execution) integer.\"\"\"\n return c_api.TFE_Py_UID()\n\n\ndef numpy_text(tensor, is_repr=False):\n \"\"\"Human readable representation of a tensor's numpy value.\"\"\"\n if tensor.dtype.is_numpy_compatible:\n # pylint: disable=protected-access\n text = repr(tensor._numpy()) if is_repr else str(tensor._numpy())\n # pylint: enable=protected-access\n else:\n text = \"<unprintable>\"\n if \"\\n\" in text:\n text = \"\\n\" + text\n return text\n\n@tf_export(v1=[\"enable_tensor_equality\"])\ndef enable_tensor_equality():\n \"\"\"Compare Tensors with element-wise comparison and thus be unhashable.\n\n Comparing tensors with element-wise allows comparisons such as\n tf.Variable(1.0) == 1.0. Element-wise equality implies that tensors are\n unhashable. Thus tensors can no longer be directly used in sets or as a key in\n a dictionary.\n \"\"\"\n Tensor._USE_EQUALITY = True # pylint: disable=protected-access\n\n@tf_export(v1=[\"disable_tensor_equality\"])\ndef disable_tensor_equality():\n \"\"\"Compare Tensors by their id and be hashable.\n\n This is a legacy behaviour of TensorFlow and is highly discouraged.\n \"\"\"\n Tensor._USE_EQUALITY = False # pylint: disable=protected-access\n\n\n@tf_export(\"Tensor\")\nclass Tensor(_TensorLike):\n \"\"\"Represents one of the outputs of an `Operation`.\n\n A `Tensor` is a symbolic handle to one of the outputs of an\n `Operation`. It does not hold the values of that operation's output,\n but instead provides a means of computing those values in a\n TensorFlow `tf.compat.v1.Session`.\n\n This class has two primary purposes:\n\n 1. A `Tensor` can be passed as an input to another `Operation`.\n This builds a dataflow connection between operations, which\n enables TensorFlow to execute an entire `Graph` that represents a\n large, multi-step computation.\n\n 2. After the graph has been launched in a session, the value of the\n `Tensor` can be computed by passing it to\n `tf.Session.run`.\n `t.eval()` is a shortcut for calling\n `tf.compat.v1.get_default_session().run(t)`.\n\n In the following example, `c`, `d`, and `e` are symbolic `Tensor`\n objects, whereas `result` is a numpy array that stores a concrete\n value:\n\n ```python\n # Build a dataflow graph.\n c = tf.constant([[1.0, 2.0], [3.0, 4.0]])\n d = tf.constant([[1.0, 1.0], [0.0, 1.0]])\n e = tf.matmul(c, d)\n\n # Construct a `Session` to execute the graph.\n sess = tf.compat.v1.Session()\n\n # Execute the graph and store the value that `e` represents in `result`.\n result = sess.run(e)\n ```\n \"\"\"\n\n # List of Python operators that we allow to override.\n OVERLOADABLE_OPERATORS = {\n # Binary.\n \"__add__\",\n \"__radd__\",\n \"__sub__\",\n \"__rsub__\",\n \"__mul__\",\n \"__rmul__\",\n \"__div__\",\n \"__rdiv__\",\n \"__truediv__\",\n \"__rtruediv__\",\n \"__floordiv__\",\n \"__rfloordiv__\",\n \"__mod__\",\n \"__rmod__\",\n \"__lt__\",\n \"__le__\",\n \"__gt__\",\n \"__ge__\",\n \"__ne__\",\n \"__eq__\",\n \"__and__\",\n \"__rand__\",\n \"__or__\",\n \"__ror__\",\n \"__xor__\",\n \"__rxor__\",\n \"__getitem__\",\n \"__pow__\",\n \"__rpow__\",\n # Unary.\n \"__invert__\",\n \"__neg__\",\n \"__abs__\",\n \"__matmul__\",\n \"__rmatmul__\"\n }\n\n # Whether to allow hashing or numpy-style equality\n _USE_EQUALITY = tf2.enabled()\n\n def __init__(self, op, value_index, dtype):\n \"\"\"Creates a new `Tensor`.\n\n Args:\n op: An `Operation`. `Operation` that computes this tensor.\n value_index: An `int`. Index of the operation's endpoint that produces\n this tensor.\n dtype: A `DType`. Type of elements stored in this tensor.\n\n Raises:\n TypeError: If the op is not an `Operation`.\n \"\"\"\n if not isinstance(op, Operation):\n raise TypeError(\"op needs to be an Operation: %s\" % op)\n self._op = op\n self._value_index = value_index\n self._dtype = dtypes.as_dtype(dtype)\n # This will be set by self._as_tf_output().\n self._tf_output = None\n # This will be set by self.shape().\n self._shape_val = None\n # List of operations that use this Tensor as input. We maintain this list\n # to easily navigate a computation graph.\n self._consumers = []\n self._id = uid()\n self._name = None\n\n @staticmethod\n def _create_with_tf_output(op, value_index, dtype, tf_output):\n ret = Tensor(op, value_index, dtype)\n ret._tf_output = tf_output\n return ret\n\n @property\n def op(self):\n \"\"\"The `Operation` that produces this tensor as an output.\"\"\"\n return self._op\n\n @property\n def dtype(self):\n \"\"\"The `DType` of elements in this tensor.\"\"\"\n return self._dtype\n\n @property\n def graph(self):\n \"\"\"The `Graph` that contains this tensor.\"\"\"\n return self._op.graph\n\n @property\n def name(self):\n \"\"\"The string name of this tensor.\"\"\"\n if self._name is None:\n if not self._op.name:\n raise ValueError(\"Operation was not named: %s\" % self._op)\n self._name = \"%s:%d\" % (self._op.name, self._value_index)\n return self._name\n\n @property\n def device(self):\n \"\"\"The name of the device on which this tensor will be produced, or None.\"\"\"\n return self._op.device\n\n @property\n def shape(self):\n \"\"\"Returns the `TensorShape` that represents the shape of this tensor.\n\n The shape is computed using shape inference functions that are\n registered in the Op for each `Operation`. See\n `tf.TensorShape`\n for more details of what a shape represents.\n\n The inferred shape of a tensor is used to provide shape\n information without having to launch the graph in a session. This\n can be used for debugging, and providing early error messages. For\n example:\n\n ```python\n c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n\n print(c.shape)\n ==> TensorShape([Dimension(2), Dimension(3)])\n\n d = tf.constant([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])\n\n print(d.shape)\n ==> TensorShape([Dimension(4), Dimension(2)])\n\n # Raises a ValueError, because `c` and `d` do not have compatible\n # inner dimensions.\n e = tf.matmul(c, d)\n\n f = tf.matmul(c, d, transpose_a=True, transpose_b=True)\n\n print(f.shape)\n ==> TensorShape([Dimension(3), Dimension(4)])\n ```\n\n In some cases, the inferred shape may have unknown dimensions. If\n the caller has additional information about the values of these\n dimensions, `Tensor.set_shape()` can be used to augment the\n inferred shape.\n\n Returns:\n A `TensorShape` representing the shape of this tensor.\n\n \"\"\"\n if self._shape_val is None:\n self._shape_val = self._c_api_shape()\n return self._shape_val\n\n def _c_api_shape(self):\n \"\"\"Returns the TensorShape of this tensor according to the C API.\"\"\"\n c_graph = self._op._graph._c_graph # pylint: disable=protected-access\n shape_vector, unknown_shape = c_api.TF_GraphGetTensorShapeHelper(\n c_graph, self._as_tf_output())\n if unknown_shape:\n return tensor_shape.unknown_shape()\n else:\n shape_vector = [None if d == -1 else d for d in shape_vector]\n return tensor_shape.TensorShape(shape_vector)\n\n @property\n def _shape(self):\n logging.warning(\"Tensor._shape is private, use Tensor.shape \"\n \"instead. Tensor._shape will eventually be removed.\")\n return self.shape\n\n @_shape.setter\n def _shape(self, value):\n raise ValueError(\n \"Tensor._shape cannot be assigned, use Tensor.set_shape instead.\")\n\n def _disallow_when_autograph_disabled(self, task):\n raise errors.OperatorNotAllowedInGraphError(\n \"{} is not allowed: AutoGraph is disabled in this function.\"\n \" Try decorating it directly with @tf.function.\".format(task))\n\n def _disallow_when_autograph_enabled(self, task):\n raise errors.OperatorNotAllowedInGraphError(\n \"{} is not allowed: AutoGraph did not convert this function. Try\"\n \" decorating it directly with @tf.function.\".format(task))\n\n def _disallow_in_graph_mode(self, task):\n raise errors.OperatorNotAllowedInGraphError(\n \"{} is not allowed in Graph execution. Use Eager execution or decorate\"\n \" this function with @tf.function.\".format(task))\n\n def _disallow_bool_casting(self):\n if ag_ctx.control_status_ctx().status == ag_ctx.Status.DISABLED:\n self._disallow_when_autograph_disabled(\n \"using a `tf.Tensor` as a Python `bool`\")\n elif ag_ctx.control_status_ctx().status == ag_ctx.Status.ENABLED:\n self._disallow_when_autograph_enabled(\n \"using a `tf.Tensor` as a Python `bool`\")\n else:\n # Default: V1-style Graph execution.\n self._disallow_in_graph_mode(\"using a `tf.Tensor` as a Python `bool`\")\n\n def _disallow_iteration(self):\n if ag_ctx.control_status_ctx().status == ag_ctx.Status.DISABLED:\n self._disallow_when_autograph_disabled(\"iterating over `tf.Tensor`\")\n elif ag_ctx.control_status_ctx().status == ag_ctx.Status.ENABLED:\n self._disallow_when_autograph_enabled(\"iterating over `tf.Tensor`\")\n else:\n # Default: V1-style Graph execution.\n self._disallow_in_graph_mode(\"iterating over `tf.Tensor`\")\n\n def __iter__(self):\n if not context.executing_eagerly():\n self._disallow_iteration()\n\n shape = self._shape_tuple()\n if shape is None:\n raise TypeError(\"Cannot iterate over a tensor with unknown shape.\")\n if not shape:\n raise TypeError(\"Cannot iterate over a scalar tensor.\")\n if shape[0] is None:\n raise TypeError(\n \"Cannot iterate over a tensor with unknown first dimension.\")\n for i in xrange(shape[0]):\n yield self[i]\n\n def _shape_as_list(self):\n if self.shape.ndims is not None:\n return [dim.value for dim in self.shape.dims]\n else:\n return None\n\n def _shape_tuple(self):\n shape = self._shape_as_list()\n if shape is None:\n return None\n return tuple(shape)\n\n def _rank(self):\n \"\"\"Integer rank of this Tensor, if known, else None.\n\n Returns:\n Integer rank or None\n \"\"\"\n return self.shape.ndims\n\n def _maybe_constant_shape(self, gen_array_ops):\n \"\"\"The shape tuple if fully defined, otherwise op to get shape.\"\"\"\n\n shape = self._shape_as_list()\n if shape is not None and all(x is not None for x in shape):\n return shape\n return gen_array_ops.shape(self)\n\n def get_shape(self):\n \"\"\"Alias of Tensor.shape.\"\"\"\n return self.shape\n\n def set_shape(self, shape):\n \"\"\"Updates the shape of this tensor.\n\n This method can be called multiple times, and will merge the given\n `shape` with the current shape of this tensor. It can be used to\n provide additional information about the shape of this tensor that\n cannot be inferred from the graph alone. For example, this can be used\n to provide additional information about the shapes of images:\n\n ```python\n _, image_data = tf.compat.v1.TFRecordReader(...).read(...)\n image = tf.image.decode_png(image_data, channels=3)\n\n # The height and width dimensions of `image` are data dependent, and\n # cannot be computed without executing the op.\n print(image.shape)\n ==> TensorShape([Dimension(None), Dimension(None), Dimension(3)])\n\n # We know that each image in this dataset is 28 x 28 pixels.\n image.set_shape([28, 28, 3])\n print(image.shape)\n ==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])\n ```\n\n NOTE: This shape is not enforced at runtime. Setting incorrect shapes can\n result in inconsistencies between the statically-known graph and the runtime\n value of tensors. For runtime validation of the shape, use `tf.ensure_shape`\n instead.\n\n Args:\n shape: A `TensorShape` representing the shape of this tensor, a\n `TensorShapeProto`, a list, a tuple, or None.\n\n Raises:\n ValueError: If `shape` is not compatible with the current shape of\n this tensor.\n \"\"\"\n # Reset cached shape.\n self._shape_val = None\n\n # We want set_shape to be reflected in the C API graph for when we run it.\n if not isinstance(shape, tensor_shape.TensorShape):\n shape = tensor_shape.TensorShape(shape)\n dim_list = []\n if shape.dims is None:\n unknown_shape = True\n else:\n unknown_shape = False\n for dim in shape.dims:\n if dim.value is None:\n dim_list.append(-1)\n else:\n dim_list.append(dim.value)\n try:\n c_api.TF_GraphSetTensorShape_wrapper(\n self._op._graph._c_graph, # pylint: disable=protected-access\n self._as_tf_output(),\n dim_list,\n unknown_shape)\n except errors.InvalidArgumentError as e:\n # Convert to ValueError for backwards compatibility.\n raise ValueError(str(e))\n\n @property\n def value_index(self):\n \"\"\"The index of this tensor in the outputs of its `Operation`.\"\"\"\n return self._value_index\n\n def consumers(self):\n \"\"\"Returns a list of `Operation`s that consume this tensor.\n\n Returns:\n A list of `Operation`s.\n \"\"\"\n consumer_names = c_api.TF_OperationOutputConsumers_wrapper(\n self._as_tf_output())\n # pylint: disable=protected-access\n return [\n self.graph._get_operation_by_name_unsafe(name)\n for name in consumer_names\n ]\n # pylint: enable=protected-access\n\n def _as_node_def_input(self):\n \"\"\"Return a value to use for the NodeDef \"input\" attribute.\n\n The returned string can be used in a NodeDef \"input\" attribute\n to indicate that the NodeDef uses this Tensor as input.\n\n Raises:\n ValueError: if this Tensor's Operation does not have a name.\n\n Returns:\n a string.\n \"\"\"\n if not self._op.name:\n raise ValueError(\"Operation was not named: %s\" % self._op)\n if self._value_index == 0:\n return self._op.name\n else:\n return \"%s:%d\" % (self._op.name, self._value_index)\n\n def _as_tf_output(self):\n # pylint: disable=protected-access\n # NOTE: Beyond preventing unnecessary (re-)allocation, the cached object\n # also guarantees that a dictionary of tf_output objects will retain a\n # deterministic (yet unsorted) order which prevents memory blowup in the\n # cache of executor(s) stored for every session.\n if self._tf_output is None:\n self._tf_output = c_api_util.tf_output(self.op._c_op, self.value_index)\n return self._tf_output\n # pylint: enable=protected-access\n\n def __str__(self):\n return \"Tensor(\\\"%s\\\"%s%s%s)\" % (\n self.name,\n (\", shape=%s\" %\n self.get_shape()) if self.get_shape().ndims is not None else \"\",\n (\", dtype=%s\" % self._dtype.name) if self._dtype else \"\",\n (\", device=%s\" % self.device) if self.device else \"\")\n\n def __repr__(self):\n return \"<tf.Tensor '%s' shape=%s dtype=%s>\" % (self.name, self.get_shape(),\n self._dtype.name)\n\n def __hash__(self):\n g = getattr(self, \"graph\", None)\n if (Tensor._USE_EQUALITY and executing_eagerly_outside_functions() and\n (g is None or g._building_function)): # pylint: disable=protected-access\n raise TypeError(\"Tensor is unhashable if Tensor equality is enabled. \"\n \"Instead, use tensor.experimental_ref() as the key.\")\n else:\n return id(self)\n\n def __copy__(self):\n # TODO(b/77597810): get rid of Tensor copies.\n cls = self.__class__\n result = cls.__new__(cls)\n result.__dict__.update(self.__dict__)\n return result\n\n # NOTE(mrry): This enables the Tensor's overloaded \"right\" binary\n # operators to run when the left operand is an ndarray, because it\n # accords the Tensor class higher priority than an ndarray, or a\n # numpy matrix.\n # TODO(mrry): Convert this to using numpy's __numpy_ufunc__\n # mechanism, which allows more control over how Tensors interact\n # with ndarrays.\n __array_priority__ = 100\n\n def __array__(self):\n raise NotImplementedError(\"Cannot convert a symbolic Tensor ({}) to a numpy\"\n \" array.\".format(self.name))\n\n def __len__(self):\n raise TypeError(\"len is not well defined for symbolic Tensors. ({}) \"\n \"Please call `x.shape` rather than `len(x)` for \"\n \"shape information.\".format(self.name))\n\n @staticmethod\n def _override_operator(operator, func):\n _override_helper(Tensor, operator, func)\n\n def __bool__(self):\n \"\"\"Dummy method to prevent a tensor from being used as a Python `bool`.\n\n This overload raises a `TypeError` when the user inadvertently\n treats a `Tensor` as a boolean (most commonly in an `if` or `while`\n statement), in code that was not converted by AutoGraph. For example:\n\n ```python\n if tf.constant(True): # Will raise.\n # ...\n\n if tf.constant(5) < tf.constant(7): # Will raise.\n # ...\n ```\n\n Raises:\n `TypeError`.\n \"\"\"\n self._disallow_bool_casting()\n\n def __nonzero__(self):\n \"\"\"Dummy method to prevent a tensor from being used as a Python `bool`.\n\n This is the Python 2.x counterpart to `__bool__()` above.\n\n Raises:\n `TypeError`.\n \"\"\"\n self._disallow_bool_casting()\n\n def eval(self, feed_dict=None, session=None):\n \"\"\"Evaluates this tensor in a `Session`.\n\n Calling this method will execute all preceding operations that\n produce the inputs needed for the operation that produces this\n tensor.\n\n *N.B.* Before invoking `Tensor.eval()`, its graph must have been\n launched in a session, and either a default session must be\n available, or `session` must be specified explicitly.\n\n Args:\n feed_dict: A dictionary that maps `Tensor` objects to feed values. See\n `tf.Session.run` for a description of the valid feed values.\n session: (Optional.) The `Session` to be used to evaluate this tensor. If\n none, the default session will be used.\n\n Returns:\n A numpy array corresponding to the value of this tensor.\n\n \"\"\"\n return _eval_using_default_session(self, feed_dict, self.graph, session)\n\n def experimental_ref(self):\n # tf.Variable also has the same experimental_ref() API. If you update the\n # documenation here, please update tf.Variable.experimental_ref() as well.\n \"\"\"Returns a hashable reference object to this Tensor.\n\n Warning: Experimental API that could be changed or removed.\n\n The primary usecase for this API is to put tensors in a set/dictionary.\n We can't put tensors in a set/dictionary as `tensor.__hash__()` is no longer\n available starting Tensorflow 2.0.\n\n ```python\n import tensorflow as tf\n\n x = tf.constant(5)\n y = tf.constant(10)\n z = tf.constant(10)\n\n # The followings will raise an exception starting 2.0\n # TypeError: Tensor is unhashable if Tensor equality is enabled.\n tensor_set = {x, y, z}\n tensor_dict = {x: 'five', y: 'ten', z: 'ten'}\n ```\n\n Instead, we can use `tensor.experimental_ref()`.\n\n ```python\n tensor_set = {x.experimental_ref(),\n y.experimental_ref(),\n z.experimental_ref()}\n\n print(x.experimental_ref() in tensor_set)\n ==> True\n\n tensor_dict = {x.experimental_ref(): 'five',\n y.experimental_ref(): 'ten',\n z.experimental_ref(): 'ten'}\n\n print(tensor_dict[y.experimental_ref()])\n ==> ten\n ```\n\n Also, the reference object provides `.deref()` function that returns the\n original Tensor.\n\n ```python\n x = tf.constant(5)\n print(x.experimental_ref().deref())\n ==> tf.Tensor(5, shape=(), dtype=int32)\n ```\n \"\"\"\n return object_identity.Reference(self)\n\n\n# TODO(agarwal): consider getting rid of this.\nclass _EagerTensorBase(Tensor):\n \"\"\"Base class for EagerTensor.\"\"\"\n\n # __int__, __float__ and __index__ may copy the tensor to CPU and\n # only work for scalars; values are cast as per numpy.\n def __int__(self):\n return int(self._numpy())\n\n def __long__(self):\n return long(self._numpy())\n\n def __float__(self):\n return float(self._numpy())\n\n def __index__(self):\n return self._numpy().__index__()\n\n def __bool__(self):\n return bool(self._numpy())\n\n __nonzero__ = __bool__\n\n def __format__(self, format_spec):\n return self._numpy().__format__(format_spec)\n\n def __reduce__(self):\n return convert_to_tensor, (self._numpy(),)\n\n def __copy__(self):\n # Eager Tensors are immutable so it's safe to return themselves as a copy.\n return self\n\n def __deepcopy__(self, memo):\n # Eager Tensors are immutable so it's safe to return themselves as a copy.\n del memo\n return self\n\n def __str__(self):\n return \"tf.Tensor(%s, shape=%s, dtype=%s)\" % (numpy_text(self), self.shape,\n self.dtype.name)\n\n def __repr__(self):\n return \"<tf.Tensor: shape=%s, dtype=%s, numpy=%s>\" % (\n self.shape, self.dtype.name, numpy_text(self, is_repr=True))\n\n def __len__(self):\n \"\"\"Returns the length of the first dimension in the Tensor.\"\"\"\n if not self.shape.ndims:\n raise TypeError(\"Scalar tensor has no `len()`\")\n # pylint: disable=protected-access\n try:\n return self._shape_tuple()[0]\n except core._NotOkStatusException as e:\n six.raise_from(core._status_to_exception(e.code, e.message), None)\n\n def _numpy_internal(self):\n raise NotImplementedError()\n\n def _numpy(self):\n # pylint: disable=protected-access\n try:\n return self._numpy_internal()\n except core._NotOkStatusException as e:\n six.raise_from(core._status_to_exception(e.code, e.message), None)\n\n @property\n def dtype(self):\n # Note: using the intern table directly here as this is\n # performance-sensitive in some models.\n return dtypes._INTERN_TABLE[self._datatype_enum()] # pylint: disable=protected-access\n\n def numpy(self):\n \"\"\"Returns a numpy array or a scalar with the same contents as the Tensor.\n\n TODO(ashankar,agarwal): Perhaps this should NOT reference the underlying\n buffer but instead always explicitly copy? Note that currently it may or may\n not copy based on whether the numpy data is properly aligned or not.\n\n Returns:\n A numpy array or a scalar. Numpy array may share memory with the\n Tensor object. Any changes to one may be reflected in the other. A scalar\n value is returned when self has rank 0.\n\n Raises:\n ValueError: if the type of this Tensor is not representable in numpy.\n \"\"\"\n maybe_arr = self._numpy() # pylint: disable=protected-access\n return maybe_arr.copy() if isinstance(maybe_arr, np.ndarray) else maybe_arr\n\n @property\n def backing_device(self):\n \"\"\"Returns the name of the device holding this tensor's memory.\n\n `.backing_device` is usually the same as `.device`, which returns\n the device on which the kernel of the operation that produced this tensor\n ran. However, some operations can produce tensors on a different device\n (e.g., an operation that executes on the GPU but produces output tensors\n in host memory).\n \"\"\"\n raise NotImplementedError()\n\n def _datatype_enum(self):\n raise NotImplementedError()\n\n def _shape_tuple(self):\n \"\"\"The shape of this Tensor, as a tuple.\n\n This is more performant than tuple(shape().as_list()) as it avoids\n two list and one object creation. Marked private for now as from an API\n perspective, it would be better to have a single performant way of\n getting a shape rather than exposing shape() and shape_tuple()\n (and heaven forbid, shape_list() etc. as well!). Punting on that for now,\n but ideally one would work things out and remove the need for this method.\n\n Returns:\n tuple with the shape.\n \"\"\"\n raise NotImplementedError()\n\n def _maybe_constant_shape(self, _):\n return self.shape\n\n def _rank(self):\n \"\"\"Integer rank of this Tensor.\n\n Unlike regular Tensors, the rank is always known for EagerTensors.\n\n This is more performant than len(self._shape_tuple())\n\n Returns:\n Integer rank\n \"\"\"\n raise NotImplementedError()\n\n def _num_elements(self):\n \"\"\"Number of elements of this Tensor.\n\n Unlike regular Tensors, the number of elements is always known for\n EagerTensors.\n\n This is more performant than tensor.shape.num_elements\n\n Returns:\n Long - num elements in the tensor\n \"\"\"\n raise NotImplementedError()\n\n def _copy_to_device(self, device_name): # pylint: disable=redefined-outer-name\n raise NotImplementedError()\n\n @staticmethod\n def _override_operator(name, func):\n setattr(_EagerTensorBase, name, func)\n\n def _copy_nograd(self, ctx=None, device_name=None):\n \"\"\"Copies tensor to dest device, but doesn't record the operation.\"\"\"\n # Creates a new tensor on the dest device.\n if ctx is None:\n ctx = context.context()\n if device_name is None:\n device_name = ctx.device_name\n # pylint: disable=protected-access\n try:\n ctx.ensure_initialized()\n new_tensor = self._copy_to_device(device_name)\n except core._NotOkStatusException as e:\n six.raise_from(core._status_to_exception(e.code, e.message), None)\n return new_tensor\n\n def _copy(self, ctx=None, device_name=None):\n \"\"\"Copies tensor to dest device.\"\"\"\n new_tensor = self._copy_nograd(ctx, device_name)\n # Record the copy on tape and define backprop copy as well.\n if context.executing_eagerly():\n self_device = self.device\n\n def grad_fun(dresult):\n return [\n dresult._copy(device_name=self_device)\n if hasattr(dresult, \"_copy\") else dresult\n ]\n\n tape.record_operation(\"_copy\", [new_tensor], [self], grad_fun)\n return new_tensor\n # pylint: enable=protected-access\n\n @property\n def shape(self):\n if self._tensor_shape is None: # pylint: disable=access-member-before-definition\n # pylint: disable=protected-access\n try:\n # `_tensor_shape` is declared and defined in the definition of\n # `EagerTensor`, in C.\n self._tensor_shape = tensor_shape.TensorShape(self._shape_tuple())\n except core._NotOkStatusException as e:\n six.raise_from(core._status_to_exception(e.code, e.message), None)\n\n return self._tensor_shape\n\n def get_shape(self):\n \"\"\"Alias of Tensor.shape.\"\"\"\n return self.shape\n\n def _shape_as_list(self):\n \"\"\"The shape of the tensor as a list.\"\"\"\n return list(self._shape_tuple())\n\n @property\n def ndim(self):\n \"\"\"Returns the number of Tensor dimensions.\"\"\"\n return self.shape.ndims\n\n @deprecation.deprecated(None, \"Use tf.identity instead.\")\n def cpu(self):\n \"\"\"A copy of this Tensor with contents backed by host memory.\"\"\"\n return self._copy(context.context(), \"CPU:0\")\n\n @deprecation.deprecated(None, \"Use tf.identity instead.\")\n def gpu(self, gpu_index=0):\n \"\"\"A copy of this Tensor with contents backed by memory on the GPU.\n\n Arguments:\n gpu_index: Identifies which GPU to place the contents on the returned\n Tensor in.\n\n Returns:\n A GPU-memory backed Tensor object initialized with the same contents\n as this Tensor.\n \"\"\"\n return self._copy(context.context(), \"GPU:\" + str(gpu_index))\n\n def set_shape(self, shape):\n if not self.shape.is_compatible_with(shape):\n raise ValueError(\n \"Tensor's shape %s is not compatible with supplied shape %s\" %\n (self.shape, shape))\n\n # Methods not supported / implemented for Eager Tensors.\n @property\n def op(self):\n raise AttributeError(\n \"Tensor.op is meaningless when eager execution is enabled.\")\n\n @property\n def graph(self):\n raise AttributeError(\n \"Tensor.graph is meaningless when eager execution is enabled.\")\n\n @property\n def name(self):\n raise AttributeError(\n \"Tensor.name is meaningless when eager execution is enabled.\")\n\n @property\n def value_index(self):\n raise AttributeError(\n \"Tensor.value_index is meaningless when eager execution is enabled.\")\n\n def consumers(self):\n raise NotImplementedError(\n \"Tensor.consumers is meaningless when eager execution is enabled.\")\n\n def _add_consumer(self, consumer):\n raise NotImplementedError(\n \"_add_consumer not supported when eager execution is enabled.\")\n\n def _as_node_def_input(self):\n raise NotImplementedError(\n \"_as_node_def_input not supported when eager execution is enabled.\")\n\n def _as_tf_output(self):\n raise NotImplementedError(\n \"_as_tf_output not supported when eager execution is enabled.\")\n\n def eval(self, feed_dict=None, session=None):\n raise NotImplementedError(\n \"eval is not supported when eager execution is enabled, \"\n \"is .numpy() what you're looking for?\")\n\n\n# This call creates an EagerTensor class, as a subclass of _EagerTensorBase, and\n# registers it with the current module.\nEagerTensor = c_api.TFE_Py_InitEagerTensor(_EagerTensorBase)\n\n\nregister_dense_tensor_like_type(Tensor)\n\n\n@tf_export(v1=[\"convert_to_tensor\"])\ndef convert_to_tensor_v1(value,\n dtype=None,\n name=None,\n preferred_dtype=None,\n dtype_hint=None):\n \"\"\"Converts the given `value` to a `Tensor`.\n\n This function converts Python objects of various types to `Tensor`\n objects. It accepts `Tensor` objects, numpy arrays, Python lists,\n and Python scalars. For example:\n\n ```python\n import numpy as np\n\n def my_func(arg):\n arg = tf.convert_to_tensor(arg, dtype=tf.float32)\n return tf.matmul(arg, arg) + arg\n\n # The following calls are equivalent.\n value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))\n value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])\n value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))\n ```\n\n This function can be useful when composing a new operation in Python\n (such as `my_func` in the example above). All standard Python op\n constructors apply this function to each of their Tensor-valued\n inputs, which allows those ops to accept numpy arrays, Python lists,\n and scalars in addition to `Tensor` objects.\n\n Note: This function diverges from default Numpy behavior for `float` and\n `string` types when `None` is present in a Python list or scalar. Rather\n than silently converting `None` values, an error will be thrown.\n\n Args:\n value: An object whose type has a registered `Tensor` conversion function.\n dtype: Optional element type for the returned tensor. If missing, the type\n is inferred from the type of `value`.\n name: Optional name to use if a new `Tensor` is created.\n preferred_dtype: Optional element type for the returned tensor, used when\n dtype is None. In some cases, a caller may not have a dtype in mind when\n converting to a tensor, so preferred_dtype can be used as a soft\n preference. If the conversion to `preferred_dtype` is not possible, this\n argument has no effect.\n dtype_hint: same meaning as preferred_dtype, and overrides it.\n\n Returns:\n A `Tensor` based on `value`.\n\n Raises:\n TypeError: If no conversion function is registered for `value` to `dtype`.\n RuntimeError: If a registered conversion function returns an invalid value.\n ValueError: If the `value` is a tensor not of given `dtype` in graph mode.\n \"\"\"\n preferred_dtype = deprecation.deprecated_argument_lookup(\n \"dtype_hint\", dtype_hint, \"preferred_dtype\", preferred_dtype)\n return convert_to_tensor_v2(value, dtype, preferred_dtype, name)\n\n\n@tf_export(\"convert_to_tensor\", v1=[])\ndef convert_to_tensor_v2(value, dtype=None, dtype_hint=None, name=None):\n \"\"\"Converts the given `value` to a `Tensor`.\n\n This function converts Python objects of various types to `Tensor`\n objects. It accepts `Tensor` objects, numpy arrays, Python lists,\n and Python scalars. For example:\n\n ```python\n import numpy as np\n\n def my_func(arg):\n arg = tf.convert_to_tensor(arg, dtype=tf.float32)\n return tf.matmul(arg, arg) + arg\n\n # The following calls are equivalent.\n value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))\n value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])\n value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))\n ```\n\n This function can be useful when composing a new operation in Python\n (such as `my_func` in the example above). All standard Python op\n constructors apply this function to each of their Tensor-valued\n inputs, which allows those ops to accept numpy arrays, Python lists,\n and scalars in addition to `Tensor` objects.\n\n Note: This function diverges from default Numpy behavior for `float` and\n `string` types when `None` is present in a Python list or scalar. Rather\n than silently converting `None` values, an error will be thrown.\n\n Args:\n value: An object whose type has a registered `Tensor` conversion function.\n dtype: Optional element type for the returned tensor. If missing, the type\n is inferred from the type of `value`.\n dtype_hint: Optional element type for the returned tensor, used when dtype\n is None. In some cases, a caller may not have a dtype in mind when\n converting to a tensor, so dtype_hint can be used as a soft preference.\n If the conversion to `dtype_hint` is not possible, this argument has no\n effect.\n name: Optional name to use if a new `Tensor` is created.\n\n Returns:\n A `Tensor` based on `value`.\n\n Raises:\n TypeError: If no conversion function is registered for `value` to `dtype`.\n RuntimeError: If a registered conversion function returns an invalid value.\n ValueError: If the `value` is a tensor not of given `dtype` in graph mode.\n \"\"\"\n return convert_to_tensor(\n value=value,\n dtype=dtype,\n name=name,\n preferred_dtype=dtype_hint,\n as_ref=False)\n\n\ndef _error_prefix(name):\n return \"\" if name is None else \"%s: \" % name\n\n\ndef convert_to_tensor(value,\n dtype=None,\n name=None,\n as_ref=False,\n preferred_dtype=None,\n dtype_hint=None,\n ctx=None,\n accepted_result_types=(Tensor,)):\n \"\"\"Implementation of the public convert_to_tensor.\"\"\"\n # TODO(b/142518781): Fix all call-sites and remove redundant arg\n preferred_dtype = preferred_dtype or dtype_hint\n if isinstance(value, EagerTensor):\n if ctx is None:\n ctx = context.context()\n if not ctx.executing_eagerly():\n graph = get_default_graph()\n if not graph.building_function:\n raise RuntimeError(\"Attempting to capture an EagerTensor without \"\n \"building a function.\")\n return graph.capture(value, name=name)\n\n if dtype is not None:\n dtype = dtypes.as_dtype(dtype)\n if isinstance(value, Tensor):\n if dtype is not None and not dtype.is_compatible_with(value.dtype):\n raise ValueError(\n \"Tensor conversion requested dtype %s for Tensor with dtype %s: %r\" %\n (dtype.name, value.dtype.name, value))\n return value\n\n if preferred_dtype is not None:\n preferred_dtype = dtypes.as_dtype(preferred_dtype)\n for base_type, conversion_func in tensor_conversion_registry.get(type(value)):\n # If dtype is None but preferred_dtype is not None, we try to\n # cast to preferred_dtype first.\n ret = None\n if dtype is None and preferred_dtype is not None:\n try:\n ret = conversion_func(\n value, dtype=preferred_dtype, name=name, as_ref=as_ref)\n except (TypeError, ValueError):\n # Could not coerce the conversion to use the preferred dtype.\n pass\n else:\n if (ret is not NotImplemented and\n ret.dtype.base_dtype != preferred_dtype.base_dtype):\n raise TypeError(\"convert_to_tensor did not convert to \"\n \"the preferred dtype: %s vs %s \" %\n (ret.dtype.base_dtype, preferred_dtype.base_dtype))\n\n if ret is None:\n ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\n\n if ret is NotImplemented:\n continue\n\n if not isinstance(ret, accepted_result_types):\n raise RuntimeError(\n \"%sConversion function %r for type %s returned non-Tensor: %r\" %\n (_error_prefix(name), conversion_func, base_type, ret))\n if dtype and not dtype.is_compatible_with(ret.dtype):\n raise RuntimeError(\n \"%sConversion function %r for type %s returned incompatible \"\n \"dtype: requested = %s, actual = %s\" %\n (_error_prefix(name), conversion_func, base_type, dtype.name,\n ret.dtype.name))\n return ret\n raise TypeError(\"%sCannot convert %r with type %s to Tensor: \"\n \"no conversion function registered.\" %\n (_error_prefix(name), value, type(value)))\n\n\ninternal_convert_to_tensor = convert_to_tensor\n\n\ndef internal_convert_n_to_tensor(values,\n dtype=None,\n name=None,\n as_ref=False,\n preferred_dtype=None,\n ctx=None):\n \"\"\"Converts `values` to a list of `Tensor` objects.\n\n Args:\n values: A list of objects that can be consumed by `tf.convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` objects.\n name: (Optional.) A name prefix to used when a new `Tensor` is created, in\n which case element `i` will be given the name `name + '_' + i`.\n as_ref: True if the caller wants the results as ref tensors.\n preferred_dtype: Optional element type for the returned tensors, used when\n dtype is None. In some cases, a caller may not have a dtype in mind when\n converting to a tensor, so preferred_dtype can be used as a soft\n preference. If the conversion to `preferred_dtype` is not possible, this\n argument has no effect.\n ctx: The value of context.context().\n\n Returns:\n A list of `Tensor` and/or `IndexedSlices` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n if not isinstance(values, collections_abc.Sequence):\n raise TypeError(\"values must be a sequence.\")\n ret = []\n if ctx is None:\n ctx = context.context()\n for i, value in enumerate(values):\n n = None if name is None else \"%s_%d\" % (name, i)\n ret.append(\n convert_to_tensor(\n value,\n dtype=dtype,\n name=n,\n as_ref=as_ref,\n preferred_dtype=preferred_dtype,\n ctx=ctx))\n return ret\n\n\ndef convert_n_to_tensor(values, dtype=None, name=None, preferred_dtype=None):\n \"\"\"Converts `values` to a list of `Tensor` objects.\n\n Args:\n values: A list of objects that can be consumed by `tf.convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` objects.\n name: (Optional.) A name prefix to used when a new `Tensor` is created, in\n which case element `i` will be given the name `name + '_' + i`.\n preferred_dtype: Optional element type for the returned tensors, used when\n dtype is None. In some cases, a caller may not have a dtype in mind when\n converting to a tensor, so preferred_dtype can be used as a soft\n preference. If the conversion to `preferred_dtype` is not possible, this\n argument has no effect.\n\n Returns:\n A list of `Tensor` and/or `IndexedSlices` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n return internal_convert_n_to_tensor(\n values=values,\n dtype=dtype,\n name=name,\n preferred_dtype=preferred_dtype,\n as_ref=False)\n\n\ndef convert_to_tensor_or_composite(value, dtype=None, name=None):\n \"\"\"Converts the given object to a `Tensor` or `CompositeTensor`.\n\n If `value` is a `CompositeTensor` it is returned unmodified. Otherwise, it\n is converted to a `Tensor` using `convert_to_tensor()`.\n\n Args:\n value: A `CompositeTensor` or an object that can be consumed by\n `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` or\n `CompositeTensor`.\n name: (Optional.) A name to use if a new `Tensor` is created.\n\n Returns:\n A `Tensor` or `CompositeTensor`, based on `value`.\n\n Raises:\n ValueError: If `dtype` does not match the element type of `value`.\n \"\"\"\n return internal_convert_to_tensor_or_composite(\n value=value, dtype=dtype, name=name, as_ref=False)\n\n\ndef internal_convert_to_tensor_or_composite(value,\n dtype=None,\n name=None,\n as_ref=False):\n \"\"\"Converts the given object to a `Tensor` or `CompositeTensor`.\n\n If `value` is a `CompositeTensor` it is returned unmodified. Otherwise, it\n is converted to a `Tensor` using `convert_to_tensor()`.\n\n Args:\n value: A `CompositeTensor`, or an object that can be consumed by\n `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` or\n `CompositeTensor`.\n name: (Optional.) A name to use if a new `Tensor` is created.\n as_ref: True if the caller wants the results as ref tensors.\n\n Returns:\n A `Tensor` or `CompositeTensor`, based on `value`.\n\n Raises:\n ValueError: If `dtype` does not match the element type of `value`.\n \"\"\"\n if isinstance(value, composite_tensor.CompositeTensor):\n value_dtype = getattr(value, \"dtype\", None)\n if dtype and not dtypes.as_dtype(dtype).is_compatible_with(value_dtype):\n raise ValueError(\n \"Tensor conversion requested dtype %s for Tensor with dtype %s: %r\" %\n (dtypes.as_dtype(dtype).name, value.dtype.name, str(value)))\n return value\n else:\n return convert_to_tensor(\n value,\n dtype=dtype,\n name=name,\n as_ref=as_ref,\n accepted_result_types=(Tensor, composite_tensor.CompositeTensor))\n\n\ndef internal_convert_n_to_tensor_or_composite(values,\n dtype=None,\n name=None,\n as_ref=False):\n \"\"\"Converts `values` to a list of `Tensor` or `CompositeTensor` objects.\n\n Any `CompositeTensor` objects in `values` are returned unmodified.\n\n Args:\n values: A list of `None`, `CompositeTensor`, or objects that can be consumed\n by `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor`s or\n `CompositeTensor`s.\n name: (Optional.) A name prefix to used when a new `Tensor` is created, in\n which case element `i` will be given the name `name + '_' + i`.\n as_ref: True if the caller wants the results as ref tensors.\n\n Returns:\n A list of `Tensor`, `CompositeTensor`, and/or `None` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n if not isinstance(values, collections_abc.Sequence):\n raise TypeError(\"values must be a sequence.\")\n ret = []\n for i, value in enumerate(values):\n if value is None:\n ret.append(value)\n else:\n n = None if name is None else \"%s_%d\" % (name, i)\n ret.append(\n internal_convert_to_tensor_or_composite(\n value, dtype=dtype, name=n, as_ref=as_ref))\n return ret\n\n\ndef convert_n_to_tensor_or_composite(values, dtype=None, name=None):\n \"\"\"Converts `values` to a list of `Output` or `CompositeTensor` objects.\n\n Any `CompositeTensor` objects in `values` are returned unmodified.\n\n Args:\n values: A list of `None`, `CompositeTensor``, or objects that can be\n consumed by `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor`s or\n `CompositeTensor`s.\n name: (Optional.) A name prefix to used when a new `Tensor` is created, in\n which case element `i` will be given the name `name + '_' + i`.\n\n Returns:\n A list of `Tensor` and/or `CompositeTensor` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n return internal_convert_n_to_tensor_or_composite(\n values=values, dtype=dtype, name=name, as_ref=False)\n\n\ndef _device_string(dev_spec):\n if pydev.is_device_spec(dev_spec):\n return dev_spec.to_string()\n else:\n return dev_spec\n\n\ndef _NodeDef(op_type, name, attrs=None):\n \"\"\"Create a NodeDef proto.\n\n Args:\n op_type: Value for the \"op\" attribute of the NodeDef proto.\n name: Value for the \"name\" attribute of the NodeDef proto.\n attrs: Dictionary where the key is the attribute name (a string)\n and the value is the respective \"attr\" attribute of the NodeDef proto (an\n AttrValue).\n\n Returns:\n A node_def_pb2.NodeDef protocol buffer.\n \"\"\"\n node_def = node_def_pb2.NodeDef(op=compat.as_bytes(op_type),\n name=compat.as_bytes(name))\n if attrs:\n for k, v in six.iteritems(attrs):\n node_def.attr[k].CopyFrom(v)\n return node_def\n\n\n# Copied from core/framework/node_def_util.cc\n# TODO(mrry,josh11b): Consolidate this validation in C++ code.\n_VALID_OP_NAME_REGEX = re.compile(\"^[A-Za-z0-9.][A-Za-z0-9_.\\\\-/>]*$\")\n_VALID_SCOPE_NAME_REGEX = re.compile(\"^[A-Za-z0-9_.\\\\-/>]*$\")\n\n\ndef _create_c_op(graph, node_def, inputs, control_inputs):\n \"\"\"Creates a TF_Operation.\n\n Args:\n graph: a `Graph`.\n node_def: `node_def_pb2.NodeDef` for the operation to create.\n inputs: A list of `Tensor`s (corresponding to scalar inputs) and lists of\n `Tensor`s (corresponding to sequence inputs, e.g. \"int64 * N\",\n \"list(int64)\"). The length of the list should be equal to the number of\n inputs specified by this operation's op def.\n control_inputs: A list of `Operation`s to set as control dependencies.\n\n Returns:\n A wrapped TF_Operation*.\n \"\"\"\n # pylint: disable=protected-access\n op_desc = c_api.TF_NewOperation(graph._c_graph, compat.as_str(node_def.op),\n compat.as_str(node_def.name))\n if node_def.device:\n c_api.TF_SetDevice(op_desc, compat.as_str(node_def.device))\n # Add inputs\n for op_input in inputs:\n if isinstance(op_input, (list, tuple)):\n c_api.TF_AddInputList(op_desc, [t._as_tf_output() for t in op_input])\n else:\n c_api.TF_AddInput(op_desc, op_input._as_tf_output())\n\n # Add control inputs\n for control_input in control_inputs:\n c_api.TF_AddControlInput(op_desc, control_input._c_op)\n # pylint: enable=protected-access\n\n # Add attrs\n for name, attr_value in node_def.attr.items():\n serialized = attr_value.SerializeToString()\n # TODO(skyewm): this creates and deletes a new TF_Status for every attr.\n # It might be worth creating a convenient way to re-use the same status.\n c_api.TF_SetAttrValueProto(op_desc, compat.as_str(name), serialized)\n\n try:\n c_op = c_api.TF_FinishOperation(op_desc)\n except errors.InvalidArgumentError as e:\n # Convert to ValueError for backwards compatibility.\n raise ValueError(str(e))\n\n return c_op\n\n\n@tf_export(\"Operation\")\nclass Operation(object):\n \"\"\"Represents a graph node that performs computation on tensors.\n\n An `Operation` is a node in a `tf.Graph` that takes zero or more `Tensor`\n objects as input, and produces zero or more `Tensor` objects as output.\n Objects of type `Operation` are created by calling a Python op constructor\n (such as `tf.matmul`) within a `tf.function` or under a `tf.Graph.as_default`\n context manager.\n\n For example, within a `tf.function`, `c = tf.matmul(a, b)` creates an\n `Operation` of type \"MatMul\" that takes tensors `a` and `b` as input, and\n produces `c` as output.\n\n If a `tf.compat.v1.Session` is used, an `Operation` of a `tf.Graph` can be\n executed by passing it to `tf.Session.run`. `op.run()` is a shortcut for\n calling `tf.compat.v1.get_default_session().run(op)`.\n \"\"\"\n\n def __init__(self,\n node_def,\n g,\n inputs=None,\n output_types=None,\n control_inputs=None,\n input_types=None,\n original_op=None,\n op_def=None):\n r\"\"\"Creates an `Operation`.\n\n NOTE: This constructor validates the name of the `Operation` (passed\n as `node_def.name`). Valid `Operation` names match the following\n regular expression:\n\n [A-Za-z0-9.][A-Za-z0-9_.\\\\-/]*\n\n Args:\n node_def: `node_def_pb2.NodeDef`. `NodeDef` for the `Operation`. Used for\n attributes of `node_def_pb2.NodeDef`, typically `name`, `op`, and\n `device`. The `input` attribute is irrelevant here as it will be\n computed when generating the model.\n g: `Graph`. The parent graph.\n inputs: list of `Tensor` objects. The inputs to this `Operation`.\n output_types: list of `DType` objects. List of the types of the `Tensors`\n computed by this operation. The length of this list indicates the\n number of output endpoints of the `Operation`.\n control_inputs: list of operations or tensors from which to have a control\n dependency.\n input_types: List of `DType` objects representing the types of the tensors\n accepted by the `Operation`. By default uses `[x.dtype.base_dtype for x\n in inputs]`. Operations that expect reference-typed inputs must specify\n these explicitly.\n original_op: Optional. Used to associate the new `Operation` with an\n existing `Operation` (for example, a replica with the op that was\n replicated).\n op_def: Optional. The `op_def_pb2.OpDef` proto that describes the op type\n that this `Operation` represents.\n\n Raises:\n TypeError: if control inputs are not Operations or Tensors,\n or if `node_def` is not a `NodeDef`,\n or if `g` is not a `Graph`,\n or if `inputs` are not tensors,\n or if `inputs` and `input_types` are incompatible.\n ValueError: if the `node_def` name is not valid.\n \"\"\"\n # For internal use only: `node_def` can be set to a TF_Operation to create\n # an Operation for that op. This is useful for creating Operations for ops\n # indirectly created by C API methods, e.g. the ops created by\n # TF_ImportGraphDef. When `node_def` is a TF_Operation, all optional fields\n # should be None.\n\n if isinstance(node_def, node_def_pb2.NodeDef):\n if node_def.ByteSize() >= (1 << 31) or node_def.ByteSize() < 0:\n raise ValueError(\n \"Cannot create a tensor proto whose content is larger than 2GB.\")\n if not _VALID_OP_NAME_REGEX.match(node_def.name):\n raise ValueError(\"'%s' is not a valid node name\" % node_def.name)\n c_op = None\n elif type(node_def).__name__ == \"SwigPyObject\":\n assert inputs is None\n assert output_types is None\n assert control_inputs is None\n assert input_types is None\n assert original_op is None\n assert op_def is None\n c_op = node_def\n else:\n raise TypeError(\"node_def needs to be a NodeDef: %s\" % node_def)\n\n if not isinstance(g, Graph):\n raise TypeError(\"g needs to be a Graph: %s\" % g)\n self._graph = g\n\n if inputs is None:\n inputs = []\n elif not isinstance(inputs, list):\n raise TypeError(\"inputs needs to be a list of Tensors: %s\" % inputs)\n for a in inputs:\n if not isinstance(a, Tensor):\n raise TypeError(\"input needs to be a Tensor: %s\" % a)\n if input_types is None:\n input_types = [i.dtype.base_dtype for i in inputs]\n else:\n if not all(\n x.is_compatible_with(i.dtype) for i, x in zip(inputs, input_types)):\n raise TypeError(\"In op '%s', input types (%s) are not compatible \"\n \"with expected types (%s)\" %\n (node_def.name, [i.dtype for i in inputs], input_types))\n\n # Build the list of control inputs.\n control_input_ops = []\n if control_inputs:\n for c in control_inputs:\n control_op = None\n if isinstance(c, Operation):\n control_op = c\n elif isinstance(c, (Tensor, IndexedSlices)):\n control_op = c.op\n else:\n raise TypeError(\"Control input must be an Operation, \"\n \"a Tensor, or IndexedSlices: %s\" % c)\n control_input_ops.append(control_op)\n\n # This will be set by self.inputs.\n self._inputs_val = None\n\n # pylint: disable=protected-access\n self._original_op = original_op\n self._traceback = tf_stack.extract_stack()\n\n # List of _UserDevSpecs holding code location of device context manager\n # invocations and the users original argument to them.\n self._device_code_locations = None\n # Dict mapping op name to file and line information for op colocation\n # context managers.\n self._colocation_code_locations = None\n self._control_flow_context = self.graph._get_control_flow_context()\n\n # Gradient function for this op. There are three ways to specify gradient\n # function, and first available gradient gets used, in the following order.\n # 1. self._gradient_function\n # 2. Gradient name registered by \"_gradient_op_type\" attribute.\n # 3. Gradient name registered by op.type.\n self._gradient_function = None\n\n # Initialize self._c_op.\n if c_op:\n self._c_op = c_op\n op_def = g._get_op_def(c_api.TF_OperationOpType(c_op))\n name = self.name\n else:\n if op_def is None:\n op_def = self._graph._get_op_def(node_def.op)\n # TODO(skyewm): op_def_library.apply_op() flattens the incoming inputs.\n # Refactor so we don't have to do this here.\n grouped_inputs = self._reconstruct_sequence_inputs(\n op_def, inputs, node_def.attr)\n self._c_op = _create_c_op(self._graph, node_def, grouped_inputs,\n control_input_ops)\n name = compat.as_str(node_def.name)\n # pylint: enable=protected-access\n\n self._is_stateful = op_def.is_stateful\n\n # Initialize self._outputs.\n num_outputs = c_api.TF_OperationNumOutputs(self._c_op)\n self._outputs = []\n for i in range(num_outputs):\n tf_output = c_api_util.tf_output(self._c_op, i)\n output_type = c_api.TF_OperationOutputType(tf_output)\n tensor = Tensor._create_with_tf_output(self, i, output_type, tf_output) # pylint: disable=protected-access\n self._outputs.append(tensor)\n\n self._id_value = self._graph._add_op(self, name) # pylint: disable=protected-access\n\n if not c_op:\n self._control_flow_post_processing(input_tensors=inputs)\n\n def _control_flow_post_processing(self, input_tensors=None):\n \"\"\"Add this op to its control flow context.\n\n This may add new ops and change this op's inputs. self.inputs must be\n available before calling this method.\n\n Args:\n input_tensors: (Optional.) A list of `Tensors` corresponding to the inputs\n of this op, which should be equivalent to `self.inputs`. Pass this\n argument to avoid evaluating `self.inputs` unnecessarily.\n \"\"\"\n if input_tensors is None:\n input_tensors = self.inputs\n for input_tensor in input_tensors:\n control_flow_util.CheckInputFromValidContext(self, input_tensor.op)\n if self._control_flow_context is not None:\n self._control_flow_context.AddOp(self)\n\n def _reconstruct_sequence_inputs(self, op_def, inputs, attrs):\n \"\"\"Regroups a flat list of input tensors into scalar and sequence inputs.\n\n Args:\n op_def: The `op_def_pb2.OpDef` (for knowing the input types)\n inputs: a list of input `Tensor`s to the op.\n attrs: mapping from attr name to `attr_value_pb2.AttrValue` (these define\n how long each sequence is)\n\n Returns:\n A list of `Tensor`s (corresponding to scalar inputs) and lists of\n `Tensor`s (corresponding to sequence inputs).\n \"\"\"\n grouped_inputs = []\n i = 0\n for input_arg in op_def.input_arg:\n if input_arg.number_attr:\n input_len = attrs[input_arg.number_attr].i\n is_sequence = True\n elif input_arg.type_list_attr:\n input_len = len(attrs[input_arg.type_list_attr].list.type)\n is_sequence = True\n else:\n input_len = 1\n is_sequence = False\n\n if is_sequence:\n grouped_inputs.append(inputs[i:i + input_len])\n else:\n grouped_inputs.append(inputs[i])\n i += input_len\n\n assert i == len(inputs)\n return grouped_inputs\n\n def colocation_groups(self):\n \"\"\"Returns the list of colocation groups of the op.\"\"\"\n default_colocation_group = [compat.as_bytes(\"loc:@%s\" % self.name)]\n try:\n class_attr = self.get_attr(\"_class\")\n except ValueError:\n # This op has no explicit colocation group, so it is itself its\n # own root of a colocation group.\n return default_colocation_group\n\n attr_groups = [\n class_name for class_name in class_attr\n if class_name.startswith(b\"loc:@\")\n ]\n\n # If there are no colocation groups in the explicit _class field,\n # return the default colocation group.\n return attr_groups if attr_groups else default_colocation_group\n\n def values(self):\n \"\"\"DEPRECATED: Use outputs.\"\"\"\n return tuple(self.outputs)\n\n def _get_control_flow_context(self):\n \"\"\"Returns the control flow context of this op.\n\n Returns:\n A context object.\n \"\"\"\n return self._control_flow_context\n\n def _set_control_flow_context(self, ctx):\n \"\"\"Sets the current control flow context of this op.\n\n Args:\n ctx: a context object.\n \"\"\"\n self._control_flow_context = ctx\n\n @property\n def name(self):\n \"\"\"The full name of this operation.\"\"\"\n return c_api.TF_OperationName(self._c_op)\n\n @property\n def _id(self):\n \"\"\"The unique integer id of this operation.\"\"\"\n return self._id_value\n\n @property\n def device(self):\n \"\"\"The name of the device to which this op has been assigned, if any.\n\n Returns:\n The string name of the device to which this op has been\n assigned, or an empty string if it has not been assigned to a\n device.\n \"\"\"\n return c_api.TF_OperationDevice(self._c_op)\n\n @property\n def _device_assignments(self):\n \"\"\"Code locations for device context managers active at op creation.\n\n This property will return a list of traceable_stack.TraceableObject\n instances where .obj is a string representing the assigned device\n (or information about the function that would be applied to this op\n to compute the desired device) and the filename and lineno members\n record the location of the relevant device context manager.\n\n For example, suppose file_a contained these lines:\n\n file_a.py:\n 15: with tf.device('/gpu:0'):\n 16: node_b = tf.constant(4, name='NODE_B')\n\n Then a TraceableObject t_obj representing the device context manager\n would have these member values:\n\n t_obj.obj -> '/gpu:0'\n t_obj.filename = 'file_a.py'\n t_obj.lineno = 15\n\n and node_b.op._device_assignments would return the list [t_obj].\n\n Returns:\n [str: traceable_stack.TraceableObject, ...] as per this method's\n description, above.\n \"\"\"\n return self._device_code_locations or []\n\n @property\n def _colocation_dict(self):\n \"\"\"Code locations for colocation context managers active at op creation.\n\n This property will return a dictionary for which the keys are nodes with\n which this Operation is colocated, and for which the values are\n traceable_stack.TraceableObject instances. The TraceableObject instances\n record the location of the relevant colocation context manager but have the\n \"obj\" field set to None to prevent leaking private data.\n\n For example, suppose file_a contained these lines:\n\n file_a.py:\n 14: node_a = tf.constant(3, name='NODE_A')\n 15: with tf.compat.v1.colocate_with(node_a):\n 16: node_b = tf.constant(4, name='NODE_B')\n\n Then a TraceableObject t_obj representing the colocation context manager\n would have these member values:\n\n t_obj.obj -> None\n t_obj.filename = 'file_a.py'\n t_obj.lineno = 15\n\n and node_b.op._colocation_dict would return the dictionary\n\n { 'NODE_A': t_obj }\n\n Returns:\n {str: traceable_stack.TraceableObject} as per this method's description,\n above.\n \"\"\"\n locations_dict = self._colocation_code_locations or {}\n return locations_dict.copy()\n\n @property\n def _output_types(self):\n \"\"\"List this operation's output types.\n\n Returns:\n List of the types of the Tensors computed by this operation.\n Each element in the list is an integer whose value is one of\n the TF_DataType enums defined in c_api.h\n The length of this list indicates the number of output endpoints\n of the operation.\n \"\"\"\n num_outputs = c_api.TF_OperationNumOutputs(self._c_op)\n output_types = [\n c_api.TF_OperationOutputType(self._tf_output(i))\n for i in xrange(num_outputs)\n ]\n # In all the tests we have output_types that are passed into\n # Operation.__init__ are a list of ints (which is illegal according\n # to the docstring), but input_types are instances of DType.\n # This extra assert is to catch if we ever use DType for output_types.\n if output_types:\n assert isinstance(output_types[0], int)\n return output_types\n\n def _tf_output(self, output_idx):\n \"\"\"Create and return a new TF_Output for output_idx'th output of this op.\"\"\"\n tf_output = c_api.TF_Output()\n tf_output.oper = self._c_op\n tf_output.index = output_idx\n return tf_output\n\n def _tf_input(self, input_idx):\n \"\"\"Create and return a new TF_Input for input_idx'th input of this op.\"\"\"\n tf_input = c_api.TF_Input()\n tf_input.oper = self._c_op\n tf_input.index = input_idx\n return tf_input\n\n def _set_device(self, device): # pylint: disable=redefined-outer-name\n \"\"\"Set the device of this operation.\n\n Args:\n device: string or device.. The device to set.\n \"\"\"\n self._set_device_from_string(compat.as_str(_device_string(device)))\n\n def _set_device_from_string(self, device_str):\n \"\"\"Fast path to set device if the type is known to be a string.\n\n This function is called frequently enough during graph construction that\n there are non-trivial performance gains if the caller can guarantee that\n the specified device is already a string.\n\n Args:\n device_str: A string specifying where to place this op.\n \"\"\"\n c_api.SetRequestedDevice(\n self._graph._c_graph, # pylint: disable=protected-access\n self._c_op, # pylint: disable=protected-access\n device_str)\n\n def _update_input(self, index, tensor):\n \"\"\"Update the input to this operation at the given index.\n\n NOTE: This is for TF internal use only. Please don't use it.\n\n Args:\n index: the index of the input to update.\n tensor: the Tensor to be used as the input at the given index.\n\n Raises:\n TypeError: if tensor is not a Tensor,\n or if input tensor type is not convertible to dtype.\n ValueError: if the Tensor is from a different graph.\n \"\"\"\n if not isinstance(tensor, Tensor):\n raise TypeError(\"tensor must be a Tensor: %s\" % tensor)\n _assert_same_graph(self, tensor)\n\n # Reset cached inputs.\n self._inputs_val = None\n c_api.UpdateEdge(\n self._graph._c_graph, # pylint: disable=protected-access\n tensor._as_tf_output(), # pylint: disable=protected-access\n self._tf_input(index))\n\n def _add_while_inputs(self, tensors):\n \"\"\"See AddWhileInputHack in python_api.h.\n\n NOTE: This is for TF internal use only. Please don't use it.\n\n Args:\n tensors: list of Tensors\n\n Raises:\n TypeError: if tensor is not a Tensor,\n or if input tensor type is not convertible to dtype.\n ValueError: if the Tensor is from a different graph.\n \"\"\"\n for tensor in tensors:\n if not isinstance(tensor, Tensor):\n raise TypeError(\"tensor must be a Tensor: %s\" % tensor)\n _assert_same_graph(self, tensor)\n\n # Reset cached inputs.\n self._inputs_val = None\n c_api.AddWhileInputHack(\n self._graph._c_graph, # pylint: disable=protected-access\n tensor._as_tf_output(), # pylint: disable=protected-access\n self._c_op)\n\n def _add_control_inputs(self, ops):\n \"\"\"Add a list of new control inputs to this operation.\n\n Args:\n ops: the list of Operations to add as control input.\n\n Raises:\n TypeError: if ops is not a list of Operations.\n ValueError: if any op in ops is from a different graph.\n \"\"\"\n for op in ops:\n if not isinstance(op, Operation):\n raise TypeError(\"op must be an Operation: %s\" % op)\n c_api.AddControlInput(self._graph._c_graph, self._c_op, op._c_op) # pylint: disable=protected-access\n\n def _add_control_input(self, op):\n \"\"\"Add a new control input to this operation.\n\n Args:\n op: the Operation to add as control input.\n\n Raises:\n TypeError: if op is not an Operation.\n ValueError: if op is from a different graph.\n \"\"\"\n if not isinstance(op, Operation):\n raise TypeError(\"op must be an Operation: %s\" % op)\n c_api.AddControlInput(self._graph._c_graph, self._c_op, op._c_op) # pylint: disable=protected-access\n\n def _remove_all_control_inputs(self):\n \"\"\"Removes any control inputs to this operation.\"\"\"\n c_api.RemoveAllControlInputs(self._graph._c_graph, self._c_op) # pylint: disable=protected-access\n\n def _add_outputs(self, types, shapes):\n \"\"\"Adds new Tensors to self.outputs.\n\n Note: this is generally unsafe to use. This is used in certain situations in\n conjunction with _set_type_list_attr.\n\n Arguments:\n types: list of DTypes\n shapes: list of TensorShapes\n \"\"\"\n assert len(types) == len(shapes)\n orig_num_outputs = len(self.outputs)\n for i in range(len(types)):\n t = Tensor(self, orig_num_outputs + i, types[i])\n self._outputs.append(t)\n t.set_shape(shapes[i])\n\n def __str__(self):\n return str(self.node_def)\n\n def __repr__(self):\n return \"<tf.Operation '%s' type=%s>\" % (self.name, self.type)\n\n @property\n def outputs(self):\n \"\"\"The list of `Tensor` objects representing the outputs of this op.\"\"\"\n return self._outputs\n\n @property\n def inputs(self):\n \"\"\"The sequence of `Tensor` objects representing the data inputs of this op.\"\"\"\n if self._inputs_val is None:\n # pylint: disable=protected-access\n self._inputs_val = tuple(map(self.graph._get_tensor_by_tf_output,\n c_api.GetOperationInputs(self._c_op)))\n # pylint: enable=protected-access\n return self._inputs_val\n\n @property\n def _input_types(self):\n num_inputs = c_api.TF_OperationNumInputs(self._c_op)\n input_types = [\n dtypes.as_dtype(c_api.TF_OperationInputType(self._tf_input(i)))\n for i in xrange(num_inputs)\n ]\n return input_types\n\n @property\n def control_inputs(self):\n \"\"\"The `Operation` objects on which this op has a control dependency.\n\n Before this op is executed, TensorFlow will ensure that the\n operations in `self.control_inputs` have finished executing. This\n mechanism can be used to run ops sequentially for performance\n reasons, or to ensure that the side effects of an op are observed\n in the correct order.\n\n Returns:\n A list of `Operation` objects.\n\n \"\"\"\n control_c_ops = c_api.TF_OperationGetControlInputs_wrapper(self._c_op)\n # pylint: disable=protected-access\n return [\n self.graph._get_operation_by_name_unsafe(c_api.TF_OperationName(c_op))\n for c_op in control_c_ops\n ]\n # pylint: enable=protected-access\n\n @property\n def _control_outputs(self):\n \"\"\"The `Operation` objects which have a control dependency on this op.\n\n Before any of the ops in self._control_outputs can execute tensorflow will\n ensure self has finished executing.\n\n Returns:\n A list of `Operation` objects.\n\n \"\"\"\n control_c_ops = c_api.TF_OperationGetControlOutputs_wrapper(self._c_op)\n # pylint: disable=protected-access\n return [\n self.graph._get_operation_by_name_unsafe(c_api.TF_OperationName(c_op))\n for c_op in control_c_ops\n ]\n # pylint: enable=protected-access\n\n @property\n def type(self):\n \"\"\"The type of the op (e.g. `\"MatMul\"`).\"\"\"\n return c_api.TF_OperationOpType(self._c_op)\n\n @property\n def graph(self):\n \"\"\"The `Graph` that contains this operation.\"\"\"\n return self._graph\n\n @property\n def node_def(self):\n # pylint: disable=line-too-long\n \"\"\"Returns the `NodeDef` representation of this operation.\n\n Returns:\n A\n [`NodeDef`](https://www.tensorflow.org/code/tensorflow/core/framework/node_def.proto)\n protocol buffer.\n \"\"\"\n # pylint: enable=line-too-long\n with c_api_util.tf_buffer() as buf:\n c_api.TF_OperationToNodeDef(self._c_op, buf)\n data = c_api.TF_GetBuffer(buf)\n node_def = node_def_pb2.NodeDef()\n node_def.ParseFromString(compat.as_bytes(data))\n return node_def\n\n @property\n def op_def(self):\n # pylint: disable=line-too-long\n \"\"\"Returns the `OpDef` proto that represents the type of this op.\n\n Returns:\n An\n [`OpDef`](https://www.tensorflow.org/code/tensorflow/core/framework/op_def.proto)\n protocol buffer.\n \"\"\"\n # pylint: enable=line-too-long\n return self._graph._get_op_def(self.type)\n\n @property\n def traceback(self):\n \"\"\"Returns the call stack from when this operation was constructed.\"\"\"\n return self._traceback\n\n def _set_attr(self, attr_name, attr_value):\n \"\"\"Private method used to set an attribute in the node_def.\"\"\"\n buf = c_api.TF_NewBufferFromString(\n compat.as_bytes(attr_value.SerializeToString()))\n try:\n self._set_attr_with_buf(attr_name, buf)\n finally:\n c_api.TF_DeleteBuffer(buf)\n\n def _set_attr_with_buf(self, attr_name, attr_buf):\n \"\"\"Set an attr in the node_def with a pre-allocated buffer.\"\"\"\n # pylint: disable=protected-access\n c_api.SetAttr(self._graph._c_graph, self._c_op, attr_name, attr_buf)\n # pylint: enable=protected-access\n\n def _set_func_attr(self, attr_name, func_name):\n \"\"\"Private method used to set a function attribute in the node_def.\"\"\"\n func = attr_value_pb2.NameAttrList(name=func_name)\n self._set_attr(attr_name, attr_value_pb2.AttrValue(func=func))\n\n def _set_func_list_attr(self, attr_name, func_names):\n \"\"\"Private method used to set a list(function) attribute in the node_def.\"\"\"\n funcs = [attr_value_pb2.NameAttrList(name=func_name)\n for func_name in func_names]\n funcs_list = attr_value_pb2.AttrValue.ListValue(func=funcs)\n self._set_attr(attr_name, attr_value_pb2.AttrValue(list=funcs_list))\n\n def _set_type_list_attr(self, attr_name, types):\n \"\"\"Private method used to set a list(type) attribute in the node_def.\"\"\"\n if not types:\n return\n if isinstance(types[0], dtypes.DType):\n types = [dt.as_datatype_enum for dt in types]\n types_list = attr_value_pb2.AttrValue.ListValue(type=types)\n self._set_attr(attr_name, attr_value_pb2.AttrValue(list=types_list))\n\n def _set_shape_list_attr(self, attr_name, shapes):\n \"\"\"Private method used to set a list(shape) attribute in the node_def.\"\"\"\n shapes = [s.as_proto() for s in shapes]\n shapes_list = attr_value_pb2.AttrValue.ListValue(shape=shapes)\n self._set_attr(attr_name, attr_value_pb2.AttrValue(list=shapes_list))\n\n def _clear_attr(self, attr_name):\n \"\"\"Private method used to clear an attribute in the node_def.\"\"\"\n # pylint: disable=protected-access\n c_api.ClearAttr(self._graph._c_graph, self._c_op, attr_name)\n # pylint: enable=protected-access\n\n def get_attr(self, name):\n \"\"\"Returns the value of the attr of this op with the given `name`.\n\n Args:\n name: The name of the attr to fetch.\n\n Returns:\n The value of the attr, as a Python object.\n\n Raises:\n ValueError: If this op does not have an attr with the given `name`.\n \"\"\"\n fields = (\"s\", \"i\", \"f\", \"b\", \"type\", \"shape\", \"tensor\", \"func\")\n try:\n with c_api_util.tf_buffer() as buf:\n c_api.TF_OperationGetAttrValueProto(self._c_op, name, buf)\n data = c_api.TF_GetBuffer(buf)\n except errors.InvalidArgumentError as e:\n # Convert to ValueError for backwards compatibility.\n raise ValueError(str(e))\n x = attr_value_pb2.AttrValue()\n x.ParseFromString(data)\n\n oneof_value = x.WhichOneof(\"value\")\n if oneof_value is None:\n return []\n if oneof_value == \"list\":\n for f in fields:\n if getattr(x.list, f):\n if f == \"type\":\n return [dtypes.as_dtype(t) for t in x.list.type]\n else:\n return list(getattr(x.list, f))\n return []\n if oneof_value == \"type\":\n return dtypes.as_dtype(x.type)\n assert oneof_value in fields, \"Unsupported field type in \" + str(x)\n return getattr(x, oneof_value)\n\n def _get_attr_type(self, name):\n \"\"\"Returns the `DType` value of the attr of this op with the given `name`.\"\"\"\n try:\n dtype_enum = c_api.TF_OperationGetAttrType(self._c_op, name)\n return _DTYPES_INTERN_TABLE[dtype_enum]\n except errors.InvalidArgumentError as e:\n # Convert to ValueError for backwards compatibility.\n raise ValueError(str(e))\n\n def _get_attr_bool(self, name):\n \"\"\"Returns the `bool` value of the attr of this op with the given `name`.\"\"\"\n try:\n return c_api.TF_OperationGetAttrBool(self._c_op, name)\n except errors.InvalidArgumentError as e:\n # Convert to ValueError for backwards compatibility.\n raise ValueError(str(e))\n\n def _get_attr_int(self, name):\n \"\"\"Returns the `int` value of the attr of this op with the given `name`.\"\"\"\n try:\n return c_api.TF_OperationGetAttrInt(self._c_op, name)\n except errors.InvalidArgumentError as e:\n # Convert to ValueError for backwards compatibility.\n raise ValueError(str(e))\n\n def run(self, feed_dict=None, session=None):\n \"\"\"Runs this operation in a `Session`.\n\n Calling this method will execute all preceding operations that\n produce the inputs needed for this operation.\n\n *N.B.* Before invoking `Operation.run()`, its graph must have been\n launched in a session, and either a default session must be\n available, or `session` must be specified explicitly.\n\n Args:\n feed_dict: A dictionary that maps `Tensor` objects to feed values. See\n `tf.Session.run` for a description of the valid feed values.\n session: (Optional.) The `Session` to be used to run to this operation. If\n none, the default session will be used.\n \"\"\"\n _run_using_default_session(self, feed_dict, self.graph, session)\n\n_gradient_registry = registry.Registry(\"gradient\")\n\n\n@tf_export(\"RegisterGradient\")\nclass RegisterGradient(object):\n \"\"\"A decorator for registering the gradient function for an op type.\n\n This decorator is only used when defining a new op type. For an op\n with `m` inputs and `n` outputs, the gradient function is a function\n that takes the original `Operation` and `n` `Tensor` objects\n (representing the gradients with respect to each output of the op),\n and returns `m` `Tensor` objects (representing the partial gradients\n with respect to each input of the op).\n\n For example, assuming that operations of type `\"Sub\"` take two\n inputs `x` and `y`, and return a single output `x - y`, the\n following gradient function would be registered:\n\n ```python\n @tf.RegisterGradient(\"Sub\")\n def _sub_grad(unused_op, grad):\n return grad, tf.negative(grad)\n ```\n\n The decorator argument `op_type` is the string type of an\n operation. This corresponds to the `OpDef.name` field for the proto\n that defines the operation.\n \"\"\"\n\n def __init__(self, op_type):\n \"\"\"Creates a new decorator with `op_type` as the Operation type.\n\n Args:\n op_type: The string type of an operation. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n\n Raises:\n TypeError: If `op_type` is not string.\n \"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string\")\n self._op_type = op_type\n\n def __call__(self, f):\n \"\"\"Registers the function `f` as gradient function for `op_type`.\"\"\"\n _gradient_registry.register(f, self._op_type)\n return f\n\n\n@deprecation.deprecated_endpoints(\"NotDifferentiable\", \"NoGradient\")\n@tf_export(\"no_gradient\", v1=[\"no_gradient\", \"NotDifferentiable\", \"NoGradient\"])\ndef no_gradient(op_type):\n \"\"\"Specifies that ops of type `op_type` is not differentiable.\n\n This function should *not* be used for operations that have a\n well-defined gradient that is not yet implemented.\n\n This function is only used when defining a new op type. It may be\n used for ops such as `tf.size()` that are not differentiable. For\n example:\n\n ```python\n tf.no_gradient(\"Size\")\n ```\n\n The gradient computed for 'op_type' will then propagate zeros.\n\n For ops that have a well-defined gradient but are not yet implemented,\n no declaration should be made, and an error *must* be thrown if\n an attempt to request its gradient is made.\n\n Args:\n op_type: The string type of an operation. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n\n Raises:\n TypeError: If `op_type` is not a string.\n\n \"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string\")\n _gradient_registry.register(None, op_type)\n\n\n# Aliases for the old names, will be eventually removed.\nNoGradient = no_gradient\nNotDifferentiable = no_gradient\n\n\ndef get_gradient_function(op):\n \"\"\"Returns the function that computes gradients for \"op\".\"\"\"\n if not op.inputs:\n return None\n\n gradient_function = op._gradient_function # pylint: disable=protected-access\n if gradient_function:\n return gradient_function\n\n try:\n op_type = op.get_attr(\"_gradient_op_type\")\n except ValueError:\n op_type = op.type\n return _gradient_registry.lookup(op_type)\n\n\ndef set_shape_and_handle_data_for_outputs(_):\n \"\"\"No op. TODO(b/74620627): Remove this.\"\"\"\n pass\n\n\nclass OpStats(object):\n \"\"\"A holder for statistics about an operator.\n\n This class holds information about the resource requirements for an op,\n including the size of its weight parameters on-disk and how many FLOPS it\n requires to execute forward inference.\n\n If you define a new operation, you can create a function that will return a\n set of information about its usage of the CPU and disk space when serialized.\n The function itself takes a Graph object that's been set up so you can call\n methods like get_tensor_by_name to help calculate the results, and a NodeDef\n argument.\n\n \"\"\"\n\n def __init__(self, statistic_type, value=None):\n \"\"\"Sets up the initial placeholders for the statistics.\"\"\"\n self.statistic_type = statistic_type\n self.value = value\n\n @property\n def statistic_type(self):\n return self._statistic_type\n\n @statistic_type.setter\n def statistic_type(self, statistic_type):\n self._statistic_type = statistic_type\n\n @property\n def value(self):\n return self._value\n\n @value.setter\n def value(self, value):\n self._value = value\n\n def __iadd__(self, other):\n if other.statistic_type != self.statistic_type:\n raise ValueError(\"Can't add an OpStat of type %s to one of %s.\" %\n (self.statistic_type, other.statistic_type))\n if self.value is None:\n self.value = other.value\n elif other.value is not None:\n self._value += other.value\n return self\n\n\n_stats_registry = registry.Registry(\"statistical functions\")\n\n\nclass RegisterStatistics(object):\n \"\"\"A decorator for registering the statistics function for an op type.\n\n This decorator can be defined for an op type so that it gives a\n report on the resources used by an instance of an operator, in the\n form of an OpStats object.\n\n Well-known types of statistics include these so far:\n\n - flops: When running a graph, the bulk of the computation happens doing\n numerical calculations like matrix multiplications. This type allows a node\n to return how many floating-point operations it takes to complete. The\n total number of FLOPs for a graph is a good guide to its expected latency.\n\n You can add your own statistics just by picking a new type string, registering\n functions for the ops you care about, and then calling get_stats_for_node_def.\n\n If a statistic for an op is registered multiple times, a KeyError will be\n raised.\n\n Since the statistics is counted on a per-op basis. It is not suitable for\n model parameters (capacity), which is expected to be counted only once, even\n if it is shared by multiple ops. (e.g. RNN)\n\n For example, you can define a new metric called doohickey for a Foo operation\n by placing this in your code:\n\n ```python\n @ops.RegisterStatistics(\"Foo\", \"doohickey\")\n def _calc_foo_bojangles(unused_graph, unused_node_def):\n return ops.OpStats(\"doohickey\", 20)\n ```\n\n Then in client code you can retrieve the value by making this call:\n\n ```python\n doohickey = ops.get_stats_for_node_def(graph, node_def, \"doohickey\")\n ```\n\n If the NodeDef is for an op with a registered doohickey function, you'll get\n back the calculated amount in doohickey.value, or None if it's not defined.\n\n \"\"\"\n\n def __init__(self, op_type, statistic_type):\n \"\"\"Saves the `op_type` as the `Operation` type.\"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string.\")\n if \",\" in op_type:\n raise TypeError(\"op_type must not contain a comma.\")\n self._op_type = op_type\n if not isinstance(statistic_type, six.string_types):\n raise TypeError(\"statistic_type must be a string.\")\n if \",\" in statistic_type:\n raise TypeError(\"statistic_type must not contain a comma.\")\n self._statistic_type = statistic_type\n\n def __call__(self, f):\n \"\"\"Registers \"f\" as the statistics function for \"op_type\".\"\"\"\n _stats_registry.register(f, self._op_type + \",\" + self._statistic_type)\n return f\n\n\ndef get_stats_for_node_def(graph, node, statistic_type):\n \"\"\"Looks up the node's statistics function in the registry and calls it.\n\n This function takes a Graph object and a NodeDef from a GraphDef, and if\n there's an associated statistics method, calls it and returns a result. If no\n function has been registered for the particular node type, it returns an empty\n statistics object.\n\n Args:\n graph: A Graph object that's been set up with the node's graph.\n node: A NodeDef describing the operator.\n statistic_type: A string identifying the statistic we're interested in.\n\n Returns:\n An OpStats object containing information about resource usage.\n \"\"\"\n\n try:\n stats_func = _stats_registry.lookup(node.op + \",\" + statistic_type)\n result = stats_func(graph, node)\n except LookupError:\n result = OpStats(statistic_type)\n return result\n\n\ndef name_from_scope_name(name):\n \"\"\"Returns the name of an op given the name of its scope.\n\n Args:\n name: the name of the scope.\n\n Returns:\n the name of the op (equal to scope name minus any trailing slash).\n \"\"\"\n return name[:-1] if (name and name[-1] == \"/\") else name\n\n\n_MUTATION_LOCK_GROUP = 0\n_SESSION_RUN_LOCK_GROUP = 1\n\n\n@tf_export(\"Graph\")\nclass Graph(object):\n \"\"\"A TensorFlow computation, represented as a dataflow graph.\n\n Graphs are used by `tf.function`s to represent the function's computations.\n Each graph contains a set of `tf.Operation` objects, which represent units of\n computation; and `tf.Tensor` objects, which represent the units of data that\n flow between operations.\n\n ### Using graphs directly (deprecated)\n\n A `tf.Graph` can be constructed and used directly without a `tf.function`, as\n was required in TensorFlow 1, but this is deprecated and it is recommended to\n use a `tf.function` instead. If a graph is directly used, other deprecated\n TensorFlow 1 classes are also required to execute the graph, such as a\n `tf.compat.v1.Session`.\n\n A default graph can be registered with the `tf.Graph.as_default` context\n manager. Then, operations will be added to the graph instead of being executed\n eagerly. For example:\n\n ```python\n g = tf.Graph()\n with g.as_default():\n # Define operations and tensors in `g`.\n c = tf.constant(30.0)\n assert c.graph is g\n ```\n\n `tf.compat.v1.get_default_graph()` can be used to obtain the default graph.\n\n Important note: This class *is not* thread-safe for graph construction. All\n operations should be created from a single thread, or external\n synchronization must be provided. Unless otherwise specified, all methods\n are not thread-safe.\n\n A `Graph` instance supports an arbitrary number of \"collections\"\n that are identified by name. For convenience when building a large\n graph, collections can store groups of related objects: for\n example, the `tf.Variable` uses a collection (named\n `tf.GraphKeys.GLOBAL_VARIABLES`) for\n all variables that are created during the construction of a graph. The caller\n may define additional collections by specifying a new name.\n \"\"\"\n\n def __init__(self):\n \"\"\"Creates a new, empty Graph.\"\"\"\n # Protects core state that can be returned via public accessors.\n # Thread-safety is provided on a best-effort basis to support buggy\n # programs, and is not guaranteed by the public `tf.Graph` API.\n #\n # NOTE(mrry): This does not protect the various stacks. A warning will\n # be reported if these are used from multiple threads\n self._lock = threading.RLock()\n # The group lock synchronizes Session.run calls with methods that create\n # and mutate ops (e.g. Graph.create_op()). This synchronization is\n # necessary because it's illegal to modify an operation after it's been run.\n # The group lock allows any number of threads to mutate ops at the same time\n # but if any modification is going on, all Session.run calls have to wait.\n # Similarly, if one or more Session.run calls are going on, all mutate ops\n # have to wait until all Session.run calls have finished.\n self._group_lock = lock_util.GroupLock(num_groups=2)\n self._nodes_by_id = {} # GUARDED_BY(self._lock)\n self._next_id_counter = 0 # GUARDED_BY(self._lock)\n self._nodes_by_name = {} # GUARDED_BY(self._lock)\n self._version = 0 # GUARDED_BY(self._lock)\n # Maps a name used in the graph to the next id to use for that name.\n self._names_in_use = {}\n self._stack_state_is_thread_local = False\n self._thread_local = threading.local()\n # Functions that will be applied to choose a device if none is specified.\n # In TF2.x or after switch_to_thread_local(),\n # self._thread_local._device_function_stack is used instead.\n self._graph_device_function_stack = traceable_stack.TraceableStack()\n # Default original_op applied to new ops.\n self._default_original_op = None\n # Current control flow context. It could be either CondContext or\n # WhileContext defined in ops/control_flow_ops.py\n self._control_flow_context = None\n # A new node will depend of the union of all of the nodes in the stack.\n # In TF2.x or after switch_to_thread_local(),\n # self._thread_local._control_dependencies_stack is used instead.\n self._graph_control_dependencies_stack = []\n # Arbitrary collections of objects.\n self._collections = {}\n # The graph-level random seed\n self._seed = None\n # A dictionary of attributes that should be applied to all ops.\n self._attr_scope_map = {}\n # A map from op type to the kernel label that should be used.\n self._op_to_kernel_label_map = {}\n # A map from op type to an alternative op type that should be used when\n # computing gradients.\n self._gradient_override_map = {}\n # A map from op type to a gradient function that should be used instead.\n self._gradient_function_map = {}\n # True if the graph is considered \"finalized\". In that case no\n # new operations can be added.\n self._finalized = False\n # Functions defined in the graph\n self._functions = collections.OrderedDict()\n # Default GraphDef versions\n self._graph_def_versions = versions_pb2.VersionDef(\n producer=versions.GRAPH_DEF_VERSION,\n min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER)\n self._building_function = False\n # Stack of colocate_with ops. In TF2.x or after switch_to_thread_local(),\n # self._thread_local._colocation_stack is used instead.\n self._graph_colocation_stack = traceable_stack.TraceableStack()\n # Set of tensors that are dangerous to feed!\n self._unfeedable_tensors = object_identity.ObjectIdentitySet()\n # Set of operations that are dangerous to fetch!\n self._unfetchable_ops = set()\n # A map of tensor handle placeholder to tensor dtype.\n self._handle_feeders = {}\n # A map from tensor handle to its read op.\n self._handle_readers = {}\n # A map from tensor handle to its move op.\n self._handle_movers = {}\n # A map from tensor handle to its delete op.\n self._handle_deleters = {}\n # Allow optimizers and other objects to pseudo-uniquely key graphs (this key\n # will be shared when defining function graphs, for example, so optimizers\n # being called inside function definitions behave as if they were seeing the\n # actual outside graph).\n self._graph_key = \"grap-key-%d/\" % (uid(),)\n # A string with the last reduction method passed to\n # losses.compute_weighted_loss(), or None. This is required only for\n # backward compatibility with Estimator and optimizer V1 use cases.\n self._last_loss_reduction = None\n # Flag that is used to indicate whether loss has been scaled by optimizer.\n # If this flag has been set, then estimator uses it to scale losss back\n # before reporting. This is required only for backward compatibility with\n # Estimator and optimizer V1 use cases.\n self._is_loss_scaled_by_optimizer = False\n self._container = \"\"\n # Set to True if this graph is being built in an\n # AutomaticControlDependencies context.\n self._add_control_dependencies = False\n # Cache for OpDef protobufs retrieved via the C API.\n self._op_def_cache = {}\n # Cache for constant results of `broadcast_gradient_args()`. The keys are\n # tuples of fully-defined shapes: (x_shape_tuple, y_shape_tuple), and the\n # values are tuples of reduction indices: (rx, ry).\n self._bcast_grad_args_cache = {}\n # Cache for constant results of `reduced_shape()`. The keys are pairs of\n # tuples: (input_shape_tuple, reduction_indices_tuple), and the values\n # are pairs of tuples: (output_shape_kept_dims, tile_scaling).\n self._reduced_shape_cache = {}\n\n # TODO(skyewm): fold as much of the above as possible into the C\n # implementation\n self._scoped_c_graph = c_api_util.ScopedTFGraph()\n # The C API requires all ops to have shape functions. Disable this\n # requirement (many custom ops do not have shape functions, and we don't\n # want to break these existing cases).\n c_api.SetRequireShapeInferenceFns(self._c_graph, False)\n if tf2.enabled():\n self.switch_to_thread_local()\n\n # Note: this method is private because the API of tf.Graph() is public and\n # frozen, and this functionality is still not ready for public visibility.\n @tf_contextlib.contextmanager\n def _variable_creator_scope(self, creator, priority=100):\n \"\"\"Scope which defines a variable creation function.\n\n Args:\n creator: A callable taking `next_creator` and `kwargs`. See the\n `tf.variable_creator_scope` docstring.\n priority: Creators with a higher `priority` are called first. Within the\n same priority, creators are called inner-to-outer.\n\n Yields:\n `_variable_creator_scope` is a context manager with a side effect, but\n doesn't return a value.\n\n Raises:\n RuntimeError: If variable creator scopes are not properly nested.\n \"\"\"\n # This step keeps a reference to the existing stack, and it also initializes\n # self._thread_local._variable_creator_stack if it doesn't exist yet.\n old = self._variable_creator_stack\n new = list(old)\n new.append((priority, creator))\n # Sorting is stable, so we'll put higher-priority creators later in the list\n # but otherwise maintain registration order.\n new.sort(key=lambda item: item[0])\n self._thread_local._variable_creator_stack = new # pylint: disable=protected-access\n try:\n yield\n finally:\n if self._thread_local._variable_creator_stack is not new: # pylint: disable=protected-access\n raise RuntimeError(\n \"Exiting variable_creator_scope without proper nesting.\")\n self._thread_local._variable_creator_stack = old # pylint: disable=protected-access\n\n # Note: this method is private because the API of tf.Graph() is public and\n # frozen, and this functionality is still not ready for public visibility.\n @property\n def _variable_creator_stack(self):\n if not hasattr(self._thread_local, \"_variable_creator_stack\"):\n self._thread_local._variable_creator_stack = [] # pylint: disable=protected-access\n\n # This previously returned a copy of the stack instead of the stack itself,\n # to guard against accidental mutation. Consider, however, code that wants\n # to save and restore the variable creator stack:\n # def f():\n # original_stack = graph._variable_creator_stack\n # graph._variable_creator_stack = new_stack\n # ... # Some code\n # graph._variable_creator_stack = original_stack\n #\n # And lets say you have some code that calls this function with some\n # variable_creator:\n # def g():\n # with variable_scope.variable_creator_scope(creator):\n # f()\n # When exiting the variable creator scope, it would see a different stack\n # object than it expected leading to a \"Exiting variable_creator_scope\n # without proper nesting\" error.\n return self._thread_local._variable_creator_stack # pylint: disable=protected-access\n\n @_variable_creator_stack.setter\n def _variable_creator_stack(self, variable_creator_stack):\n self._thread_local._variable_creator_stack = variable_creator_stack # pylint: disable=protected-access\n\n def _check_not_finalized(self):\n \"\"\"Check if the graph is finalized.\n\n Raises:\n RuntimeError: If the graph finalized.\n \"\"\"\n if self._finalized:\n raise RuntimeError(\"Graph is finalized and cannot be modified.\")\n\n def _add_op(self, op, op_name):\n \"\"\"Adds 'op' to the graph and returns the unique ID for the added Operation.\n\n Args:\n op: the Operation to add.\n op_name: the name of the Operation.\n\n Returns:\n An integer that is a unique ID for the added Operation.\n \"\"\"\n self._check_not_finalized()\n with self._lock:\n self._next_id_counter += 1\n op_id = self._next_id_counter\n self._nodes_by_id[op_id] = op\n self._nodes_by_name[op_name] = op\n self._version = max(self._version, op_id)\n return op_id\n\n @property\n def _c_graph(self):\n if self._scoped_c_graph:\n return self._scoped_c_graph.graph\n return None\n\n @property\n def version(self):\n \"\"\"Returns a version number that increases as ops are added to the graph.\n\n Note that this is unrelated to the\n `tf.Graph.graph_def_versions`.\n\n Returns:\n An integer version that increases as ops are added to the graph.\n \"\"\"\n if self._finalized:\n return self._version\n\n with self._lock:\n return self._version\n\n @property\n def graph_def_versions(self):\n # pylint: disable=line-too-long\n \"\"\"The GraphDef version information of this graph.\n\n For details on the meaning of each version, see\n [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto).\n\n Returns:\n A `VersionDef`.\n \"\"\"\n # pylint: enable=line-too-long\n with c_api_util.tf_buffer() as buf:\n c_api.TF_GraphVersions(self._c_graph, buf)\n data = c_api.TF_GetBuffer(buf)\n version_def = versions_pb2.VersionDef()\n version_def.ParseFromString(compat.as_bytes(data))\n return version_def\n\n @property\n def seed(self):\n \"\"\"The graph-level random seed of this graph.\"\"\"\n return self._seed\n\n @seed.setter\n def seed(self, seed):\n self._seed = seed\n\n @property\n def finalized(self):\n \"\"\"True if this graph has been finalized.\"\"\"\n return self._finalized\n\n def finalize(self):\n \"\"\"Finalizes this graph, making it read-only.\n\n After calling `g.finalize()`, no new operations can be added to\n `g`. This method is used to ensure that no operations are added\n to a graph when it is shared between multiple threads, for example\n when using a `tf.compat.v1.train.QueueRunner`.\n \"\"\"\n self._finalized = True\n\n def _unsafe_unfinalize(self):\n \"\"\"Opposite of `finalize`.\n\n Internal interface.\n\n NOTE: Unfinalizing a graph could have negative impact on performance,\n especially in a multi-threaded environment. Unfinalizing a graph\n when it is in use by a Session may lead to undefined behavior. Ensure\n that all sessions using a graph are closed before calling this method.\n \"\"\"\n self._finalized = False\n\n def _get_control_flow_context(self):\n \"\"\"Returns the current control flow context.\n\n Returns:\n A context object.\n \"\"\"\n return self._control_flow_context\n\n def _set_control_flow_context(self, ctx):\n \"\"\"Sets the current control flow context.\n\n Args:\n ctx: a context object.\n \"\"\"\n self._control_flow_context = ctx\n\n def _copy_functions_to_graph_def(self, graph_def, starting_bytesize):\n \"\"\"If this graph contains functions, copy them to `graph_def`.\"\"\"\n bytesize = starting_bytesize\n for f in self._functions.values():\n bytesize += f.definition.ByteSize()\n if bytesize >= (1 << 31) or bytesize < 0:\n raise ValueError(\"GraphDef cannot be larger than 2GB.\")\n graph_def.library.function.extend([f.definition])\n if f.grad_func_name:\n grad_def = function_pb2.GradientDef()\n grad_def.function_name = f.name\n grad_def.gradient_func = f.grad_func_name\n graph_def.library.gradient.extend([grad_def])\n\n def _as_graph_def(self, from_version=None, add_shapes=False):\n # pylint: disable=line-too-long\n \"\"\"Returns a serialized `GraphDef` representation of this graph.\n\n The serialized `GraphDef` can be imported into another `Graph`\n (using `tf.import_graph_def`) or used with the\n [C++ Session API](../../../../api_docs/cc/index.md).\n\n This method is thread-safe.\n\n Args:\n from_version: Optional. If this is set, returns a `GraphDef` containing\n only the nodes that were added to this graph since its `version`\n property had the given value.\n add_shapes: If true, adds an \"_output_shapes\" list attr to each node with\n the inferred shapes of each of its outputs.\n\n Returns:\n A tuple containing a\n [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)\n protocol buffer, and the version of the graph to which that\n `GraphDef` corresponds.\n\n Raises:\n ValueError: If the `graph_def` would be too large.\n\n \"\"\"\n # pylint: enable=line-too-long\n with self._lock:\n with c_api_util.tf_buffer() as buf:\n c_api.TF_GraphToGraphDef(self._c_graph, buf)\n data = c_api.TF_GetBuffer(buf)\n graph = graph_pb2.GraphDef()\n graph.ParseFromString(compat.as_bytes(data))\n # Strip the experimental library field iff it's empty.\n if not graph.library.function:\n graph.ClearField(\"library\")\n\n if add_shapes:\n for node in graph.node:\n op = self._nodes_by_name[node.name]\n if op.outputs:\n node.attr[\"_output_shapes\"].list.shape.extend(\n [output.get_shape().as_proto() for output in op.outputs])\n for function_def in graph.library.function:\n defined_function = self._functions[function_def.signature.name]\n try:\n func_graph = defined_function.graph\n except AttributeError:\n # _DefinedFunction doesn't have a graph, _EagerDefinedFunction\n # does. Both rely on ops.py, so we can't really isinstance check\n # them.\n continue\n input_shapes = function_def.attr[\"_input_shapes\"]\n try:\n func_graph_inputs = func_graph.inputs\n except AttributeError:\n continue\n # TODO(b/141471245): Fix the inconsistency when inputs of func graph\n # are appended during gradient computation of while/cond.\n for input_tensor, _ in zip(func_graph_inputs,\n function_def.signature.input_arg):\n if input_tensor.dtype == dtypes.resource:\n # TODO(allenl): Save and restore handle data, then save the\n # resource placeholder's shape. Right now some shape functions get\n # confused if we set the shape of the resource placeholder (to a\n # scalar of course) and there isn't any handle data.\n input_shapes.list.shape.add().CopyFrom(\n tensor_shape.TensorShape(None).as_proto())\n else:\n input_shapes.list.shape.add().CopyFrom(\n input_tensor.get_shape().as_proto())\n for node in function_def.node_def:\n try:\n op = func_graph.get_operation_by_name(node.name)\n except KeyError:\n continue\n node.attr[\"_output_shapes\"].list.shape.extend(\n [output.get_shape().as_proto() for output in op.outputs])\n\n return graph, self._version\n\n def as_graph_def(self, from_version=None, add_shapes=False):\n # pylint: disable=line-too-long\n \"\"\"Returns a serialized `GraphDef` representation of this graph.\n\n The serialized `GraphDef` can be imported into another `Graph`\n (using `tf.import_graph_def`) or used with the\n [C++ Session API](../../api_docs/cc/index.md).\n\n This method is thread-safe.\n\n Args:\n from_version: Optional. If this is set, returns a `GraphDef` containing\n only the nodes that were added to this graph since its `version`\n property had the given value.\n add_shapes: If true, adds an \"_output_shapes\" list attr to each node with\n the inferred shapes of each of its outputs.\n\n Returns:\n A\n [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)\n protocol buffer.\n\n Raises:\n ValueError: If the `graph_def` would be too large.\n \"\"\"\n # pylint: enable=line-too-long\n result, _ = self._as_graph_def(from_version, add_shapes)\n return result\n\n def _is_function(self, name):\n \"\"\"Tests whether 'name' is registered in this graph's function library.\n\n Args:\n name: string op name.\n\n Returns:\n bool indicating whether or not 'name' is registered in function library.\n \"\"\"\n return compat.as_str(name) in self._functions\n\n def _get_function(self, name):\n \"\"\"Returns the function definition for 'name'.\n\n Args:\n name: string function name.\n\n Returns:\n The function def proto.\n \"\"\"\n return self._functions.get(compat.as_str(name), None)\n\n def _add_function(self, function):\n \"\"\"Adds a function to the graph.\n\n After the function has been added, you can call to the function by\n passing the function name in place of an op name to\n `Graph.create_op()`.\n\n Args:\n function: A `_DefinedFunction` object.\n\n Raises:\n ValueError: if another function is defined with the same name.\n \"\"\"\n name = function.name\n # Sanity checks on gradient definition.\n if (function.grad_func_name is not None) and (function.python_grad_func is\n not None):\n raise ValueError(\"Gradient defined twice for function %s\" % name)\n\n # Add function to graph\n # pylint: disable=protected-access\n gradient = (\n function._grad_func._c_func.func if function._grad_func else None)\n c_api.TF_GraphCopyFunction(self._c_graph, function._c_func.func, gradient)\n # pylint: enable=protected-access\n\n self._functions[compat.as_str(name)] = function\n\n # Need a new-enough consumer to support the functions we add to the graph.\n if self._graph_def_versions.min_consumer < 12:\n self._graph_def_versions.min_consumer = 12\n\n @property\n def building_function(self):\n \"\"\"Returns True iff this graph represents a function.\"\"\"\n return self._building_function\n\n # Helper functions to create operations.\n @deprecated_args(None,\n \"Shapes are always computed; don't use the compute_shapes \"\n \"as it has no effect.\", \"compute_shapes\")\n def create_op(\n self,\n op_type,\n inputs,\n dtypes=None, # pylint: disable=redefined-outer-name\n input_types=None,\n name=None,\n attrs=None,\n op_def=None,\n compute_shapes=True,\n compute_device=True):\n \"\"\"Creates an `Operation` in this graph.\n\n This is a low-level interface for creating an `Operation`. Most\n programs will not call this method directly, and instead use the\n Python op constructors, such as `tf.constant()`, which add ops to\n the default graph.\n\n Args:\n op_type: The `Operation` type to create. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n inputs: A list of `Tensor` objects that will be inputs to the `Operation`.\n dtypes: (Optional) A list of `DType` objects that will be the types of the\n tensors that the operation produces.\n input_types: (Optional.) A list of `DType`s that will be the types of the\n tensors that the operation consumes. By default, uses the base `DType`\n of each input in `inputs`. Operations that expect reference-typed inputs\n must specify `input_types` explicitly.\n name: (Optional.) A string name for the operation. If not specified, a\n name is generated based on `op_type`.\n attrs: (Optional.) A dictionary where the key is the attribute name (a\n string) and the value is the respective `attr` attribute of the\n `NodeDef` proto that will represent the operation (an `AttrValue`\n proto).\n op_def: (Optional.) The `OpDef` proto that describes the `op_type` that\n the operation will have.\n compute_shapes: (Optional.) Deprecated. Has no effect (shapes are always\n computed).\n compute_device: (Optional.) If True, device functions will be executed to\n compute the device property of the Operation.\n\n Raises:\n TypeError: if any of the inputs is not a `Tensor`.\n ValueError: if colocation conflicts with existing device assignment.\n\n Returns:\n An `Operation` object.\n \"\"\"\n del compute_shapes\n for idx, a in enumerate(inputs):\n if not isinstance(a, Tensor):\n raise TypeError(\"Input #%d is not a tensor: %s\" % (idx, a))\n return self._create_op_internal(op_type, inputs, dtypes, input_types, name,\n attrs, op_def, compute_device)\n\n def _create_op_internal(\n self,\n op_type,\n inputs,\n dtypes=None, # pylint: disable=redefined-outer-name\n input_types=None,\n name=None,\n attrs=None,\n op_def=None,\n compute_device=True):\n \"\"\"Creates an `Operation` in this graph.\n\n Implements `Graph.create_op()` without the overhead of the deprecation\n wrapper.\n\n Args:\n op_type: The `Operation` type to create. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n inputs: A list of `Tensor` objects that will be inputs to the `Operation`.\n dtypes: (Optional) A list of `DType` objects that will be the types of the\n tensors that the operation produces.\n input_types: (Optional.) A list of `DType`s that will be the types of the\n tensors that the operation consumes. By default, uses the base `DType`\n of each input in `inputs`. Operations that expect reference-typed inputs\n must specify `input_types` explicitly.\n name: (Optional.) A string name for the operation. If not specified, a\n name is generated based on `op_type`.\n attrs: (Optional.) A dictionary where the key is the attribute name (a\n string) and the value is the respective `attr` attribute of the\n `NodeDef` proto that will represent the operation (an `AttrValue`\n proto).\n op_def: (Optional.) The `OpDef` proto that describes the `op_type` that\n the operation will have.\n compute_device: (Optional.) If True, device functions will be executed to\n compute the device property of the Operation.\n\n Raises:\n ValueError: if colocation conflicts with existing device assignment.\n\n Returns:\n An `Operation` object.\n \"\"\"\n self._check_not_finalized()\n if name is None:\n name = op_type\n # If a names ends with a '/' it is a \"name scope\" and we use it as-is,\n # after removing the trailing '/'.\n if name and name[-1] == \"/\":\n name = name_from_scope_name(name)\n else:\n name = self.unique_name(name)\n\n node_def = _NodeDef(op_type, name, attrs)\n\n input_ops = set([t.op for t in inputs])\n control_inputs = self._control_dependencies_for_inputs(input_ops)\n # _create_op_helper mutates the new Operation. `_mutation_lock` ensures a\n # Session.run call cannot occur between creating and mutating the op.\n with self._mutation_lock():\n ret = Operation(\n node_def,\n self,\n inputs=inputs,\n output_types=dtypes,\n control_inputs=control_inputs,\n input_types=input_types,\n original_op=self._default_original_op,\n op_def=op_def)\n self._create_op_helper(ret, compute_device=compute_device)\n return ret\n\n def _create_op_from_tf_operation(self, c_op, compute_device=True):\n \"\"\"Creates an `Operation` in this graph from the supplied TF_Operation.\n\n This method is like create_op() except the new Operation is constructed\n using `c_op`. The returned Operation will have `c_op` as its _c_op\n field. This is used to create Operation objects around TF_Operations created\n indirectly by the C API (e.g. by TF_ImportGraphDef, TF_FinishWhile).\n\n This function does not call Operation._control_flow_post_processing or\n Graph._control_dependencies_for_inputs (since the inputs may not be\n available yet). The caller is responsible for calling these methods.\n\n Args:\n c_op: a wrapped TF_Operation\n compute_device: (Optional.) If True, device functions will be executed to\n compute the device property of the Operation.\n\n Returns:\n An `Operation` object.\n \"\"\"\n self._check_not_finalized()\n ret = Operation(c_op, self)\n # If a name_scope was created with ret.name but no nodes were created in it,\n # the name will still appear in _names_in_use even though the name hasn't\n # been used. This is ok, just leave _names_in_use as-is in this case.\n # TODO(skyewm): make the C API guarantee no name conflicts.\n name_key = ret.name.lower()\n if name_key not in self._names_in_use:\n self._names_in_use[name_key] = 1\n self._create_op_helper(ret, compute_device=compute_device)\n return ret\n\n def _create_op_helper(self, op, compute_device=True):\n \"\"\"Common logic for creating an op in this graph.\"\"\"\n # Apply any additional attributes requested. Do not overwrite any existing\n # attributes.\n for key, value in self._attr_scope_map.items():\n try:\n op.get_attr(key)\n except ValueError:\n if callable(value):\n value = value(op.node_def)\n if not isinstance(value, (type(None), attr_value_pb2.AttrValue)):\n raise TypeError(\n \"Callable for scope map key '%s' must return either None or \"\n \"an AttrValue protocol buffer; but it returned: %s\" %\n (key, value))\n if value:\n op._set_attr(key, value) # pylint: disable=protected-access\n\n # Apply a kernel label if one has been specified for this op type.\n try:\n kernel_label = self._op_to_kernel_label_map[op.type]\n op._set_attr(\"_kernel\", # pylint: disable=protected-access\n attr_value_pb2.AttrValue(s=compat.as_bytes(kernel_label)))\n except KeyError:\n pass\n\n op._gradient_function = self._gradient_function_map.get(op.type) # pylint: disable=protected-access\n\n # Apply the overriding op type for gradients if one has been specified for\n # this op type.\n try:\n mapped_op_type = self._gradient_override_map[op.type]\n op._set_attr(\"_gradient_op_type\", # pylint: disable=protected-access\n attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type)))\n except KeyError:\n pass\n\n self._record_op_seen_by_control_dependencies(op)\n\n if compute_device:\n self._apply_device_functions(op)\n\n # Snapshot the colocation stack metadata before we might generate error\n # messages using it. Note that this snapshot depends on the actual stack\n # and is independent of the op's _class attribute.\n # pylint: disable=protected-access\n op._colocation_code_locations = self._snapshot_colocation_stack_metadata()\n # pylint: enable=protected-access\n\n if self._colocation_stack:\n all_colocation_groups = []\n for colocation_op in self._colocation_stack.peek_objs():\n all_colocation_groups.extend(colocation_op.colocation_groups())\n if colocation_op.device:\n # pylint: disable=protected-access\n op._set_device(colocation_op.device)\n # pylint: enable=protected-access\n\n all_colocation_groups = sorted(set(all_colocation_groups))\n # pylint: disable=protected-access\n op._set_attr(\n \"_class\",\n attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(s=all_colocation_groups)))\n # pylint: enable=protected-access\n\n # Sets \"container\" attribute if\n # (1) self._container is not None\n # (2) \"is_stateful\" is set in OpDef\n # (3) \"container\" attribute is in OpDef\n # (4) \"container\" attribute is None\n if self._container and op._is_stateful: # pylint: disable=protected-access\n try:\n container_attr = op.get_attr(\"container\")\n except ValueError:\n # \"container\" attribute is not in OpDef\n pass\n else:\n if not container_attr:\n op._set_attr(\"container\", attr_value_pb2.AttrValue( # pylint: disable=protected-access\n s=compat.as_bytes(self._container)))\n\n def _add_new_tf_operations(self, compute_devices=True):\n \"\"\"Creates `Operations` in this graph for any new TF_Operations.\n\n This is useful for when TF_Operations are indirectly created by the C API\n outside of the Operation constructor (e.g. by TF_ImportGraphDef,\n TF_FinishWhile). This ensures there are corresponding Operations for all\n TF_Operations in the underlying TF_Graph.\n\n Args:\n compute_devices: (Optional.) If True, device functions will be executed to\n compute the device properties of each new Operation.\n\n Returns:\n A list of the new `Operation` objects.\n \"\"\"\n # Create all Operation objects before accessing their inputs since an op may\n # be created before its inputs.\n new_ops = [\n self._create_op_from_tf_operation(c_op, compute_device=compute_devices)\n for c_op in c_api_util.new_tf_operations(self)\n ]\n\n # pylint: disable=protected-access\n for op in new_ops:\n new_control_inputs = self._control_dependencies_for_inputs(op.inputs)\n op._add_control_inputs(new_control_inputs)\n op._control_flow_post_processing()\n # pylint: enable=protected-access\n\n return new_ops\n\n def as_graph_element(self, obj, allow_tensor=True, allow_operation=True):\n \"\"\"Returns the object referred to by `obj`, as an `Operation` or `Tensor`.\n\n This function validates that `obj` represents an element of this\n graph, and gives an informative error message if it is not.\n\n This function is the canonical way to get/validate an object of\n one of the allowed types from an external argument reference in the\n Session API.\n\n This method may be called concurrently from multiple threads.\n\n Args:\n obj: A `Tensor`, an `Operation`, or the name of a tensor or operation. Can\n also be any object with an `_as_graph_element()` method that returns a\n value of one of these types. Note: `_as_graph_element` will be called\n inside the graph's lock and so may not modify the graph.\n allow_tensor: If true, `obj` may refer to a `Tensor`.\n allow_operation: If true, `obj` may refer to an `Operation`.\n\n Returns:\n The `Tensor` or `Operation` in the Graph corresponding to `obj`.\n\n Raises:\n TypeError: If `obj` is not a type we support attempting to convert\n to types.\n ValueError: If `obj` is of an appropriate type but invalid. For\n example, an invalid string.\n KeyError: If `obj` is not an object in the graph.\n \"\"\"\n if self._finalized:\n return self._as_graph_element_locked(obj, allow_tensor, allow_operation)\n\n with self._lock:\n return self._as_graph_element_locked(obj, allow_tensor, allow_operation)\n\n def _as_graph_element_locked(self, obj, allow_tensor, allow_operation):\n \"\"\"See `Graph.as_graph_element()` for details.\"\"\"\n # The vast majority of this function is figuring\n # out what an API user might be doing wrong, so\n # that we can give helpful error messages.\n #\n # Ideally, it would be nice to split it up, but we\n # need context to generate nice error messages.\n\n if allow_tensor and allow_operation:\n types_str = \"Tensor or Operation\"\n elif allow_tensor:\n types_str = \"Tensor\"\n elif allow_operation:\n types_str = \"Operation\"\n else:\n raise ValueError(\"allow_tensor and allow_operation can't both be False.\")\n\n temp_obj = _as_graph_element(obj)\n if temp_obj is not None:\n obj = temp_obj\n\n # If obj appears to be a name...\n if isinstance(obj, compat.bytes_or_text_types):\n name = compat.as_str(obj)\n\n if \":\" in name and allow_tensor:\n # Looks like a Tensor name and can be a Tensor.\n try:\n op_name, out_n = name.split(\":\")\n out_n = int(out_n)\n except:\n raise ValueError(\"The name %s looks a like a Tensor name, but is \"\n \"not a valid one. Tensor names must be of the \"\n \"form \\\"<op_name>:<output_index>\\\".\" % repr(name))\n if op_name in self._nodes_by_name:\n op = self._nodes_by_name[op_name]\n else:\n raise KeyError(\"The name %s refers to a Tensor which does not \"\n \"exist. The operation, %s, does not exist in the \"\n \"graph.\" % (repr(name), repr(op_name)))\n try:\n return op.outputs[out_n]\n except:\n raise KeyError(\"The name %s refers to a Tensor which does not \"\n \"exist. The operation, %s, exists but only has \"\n \"%s outputs.\" %\n (repr(name), repr(op_name), len(op.outputs)))\n\n elif \":\" in name and not allow_tensor:\n # Looks like a Tensor name but can't be a Tensor.\n raise ValueError(\"Name %s appears to refer to a Tensor, not a %s.\" %\n (repr(name), types_str))\n\n elif \":\" not in name and allow_operation:\n # Looks like an Operation name and can be an Operation.\n if name not in self._nodes_by_name:\n raise KeyError(\"The name %s refers to an Operation not in the \"\n \"graph.\" % repr(name))\n return self._nodes_by_name[name]\n\n elif \":\" not in name and not allow_operation:\n # Looks like an Operation name but can't be an Operation.\n if name in self._nodes_by_name:\n # Yep, it's an Operation name\n err_msg = (\"The name %s refers to an Operation, not a %s.\" %\n (repr(name), types_str))\n else:\n err_msg = (\"The name %s looks like an (invalid) Operation name, \"\n \"not a %s.\" % (repr(name), types_str))\n err_msg += (\" Tensor names must be of the form \"\n \"\\\"<op_name>:<output_index>\\\".\")\n raise ValueError(err_msg)\n\n elif isinstance(obj, Tensor) and allow_tensor:\n # Actually obj is just the object it's referring to.\n if obj.graph is not self:\n raise ValueError(\"Tensor %s is not an element of this graph.\" % obj)\n return obj\n elif isinstance(obj, Operation) and allow_operation:\n # Actually obj is just the object it's referring to.\n if obj.graph is not self:\n raise ValueError(\"Operation %s is not an element of this graph.\" % obj)\n return obj\n else:\n # We give up!\n raise TypeError(\"Can not convert a %s into a %s.\" %\n (type(obj).__name__, types_str))\n\n def get_operations(self):\n \"\"\"Return the list of operations in the graph.\n\n You can modify the operations in place, but modifications\n to the list such as inserts/delete have no effect on the\n list of operations known to the graph.\n\n This method may be called concurrently from multiple threads.\n\n Returns:\n A list of Operations.\n \"\"\"\n if self._finalized:\n return list(self._nodes_by_id.values())\n\n with self._lock:\n return list(self._nodes_by_id.values())\n\n def get_operation_by_name(self, name):\n \"\"\"Returns the `Operation` with the given `name`.\n\n This method may be called concurrently from multiple threads.\n\n Args:\n name: The name of the `Operation` to return.\n\n Returns:\n The `Operation` with the given `name`.\n\n Raises:\n TypeError: If `name` is not a string.\n KeyError: If `name` does not correspond to an operation in this graph.\n \"\"\"\n\n if not isinstance(name, six.string_types):\n raise TypeError(\"Operation names are strings (or similar), not %s.\" %\n type(name).__name__)\n return self.as_graph_element(name, allow_tensor=False, allow_operation=True)\n\n def _get_operation_by_name_unsafe(self, name):\n \"\"\"Returns the `Operation` with the given `name`.\n\n This is a internal unsafe version of get_operation_by_name. It skips many\n checks and does not have user friedly error messages but runs considerably\n faster. This method may be called concurrently from multiple threads.\n\n Args:\n name: The name of the `Operation` to return.\n\n Returns:\n The `Operation` with the given `name`.\n\n Raises:\n KeyError: If `name` does not correspond to an operation in this graph.\n \"\"\"\n\n if self._finalized:\n return self._nodes_by_name[name]\n\n with self._lock:\n return self._nodes_by_name[name]\n\n def _get_operation_by_tf_operation(self, tf_oper):\n op_name = c_api.TF_OperationName(tf_oper)\n return self._get_operation_by_name_unsafe(op_name)\n\n def get_tensor_by_name(self, name):\n \"\"\"Returns the `Tensor` with the given `name`.\n\n This method may be called concurrently from multiple threads.\n\n Args:\n name: The name of the `Tensor` to return.\n\n Returns:\n The `Tensor` with the given `name`.\n\n Raises:\n TypeError: If `name` is not a string.\n KeyError: If `name` does not correspond to a tensor in this graph.\n \"\"\"\n # Names should be strings.\n if not isinstance(name, six.string_types):\n raise TypeError(\"Tensor names are strings (or similar), not %s.\" %\n type(name).__name__)\n return self.as_graph_element(name, allow_tensor=True, allow_operation=False)\n\n def _get_tensor_by_tf_output(self, tf_output):\n \"\"\"Returns the `Tensor` representing `tf_output`.\n\n Note that there is only one such `Tensor`, i.e. multiple calls to this\n function with the same TF_Output value will always return the same `Tensor`\n object.\n\n Args:\n tf_output: A wrapped `TF_Output` (the C API equivalent of `Tensor`).\n\n Returns:\n The `Tensor` that represents `tf_output`.\n \"\"\"\n op = self._get_operation_by_tf_operation(tf_output.oper)\n return op.outputs[tf_output.index]\n\n @property\n def _last_id(self):\n return self._next_id_counter\n\n def _get_op_def(self, type): # pylint: disable=redefined-builtin\n \"\"\"Returns the `OpDef` proto for `type`. `type` is a string.\"\"\"\n # NOTE: No locking is required because the lookup and insertion operations\n # on Python dictionaries are atomic.\n try:\n return self._op_def_cache[type]\n except KeyError:\n with c_api_util.tf_buffer() as buf:\n # pylint: disable=protected-access\n c_api.TF_GraphGetOpDef(self._c_graph, compat.as_bytes(type), buf)\n # pylint: enable=protected-access\n data = c_api.TF_GetBuffer(buf)\n op_def = op_def_pb2.OpDef()\n op_def.ParseFromString(compat.as_bytes(data))\n self._op_def_cache[type] = op_def\n return op_def\n\n def as_default(self):\n \"\"\"Returns a context manager that makes this `Graph` the default graph.\n\n This method should be used if you want to create multiple graphs\n in the same process. For convenience, a global default graph is\n provided, and all ops will be added to this graph if you do not\n create a new graph explicitly.\n\n Use this method with the `with` keyword to specify that ops created within\n the scope of a block should be added to this graph. In this case, once\n the scope of the `with` is exited, the previous default graph is set again\n as default. There is a stack, so it's ok to have multiple nested levels\n of `as_default` calls.\n\n The default graph is a property of the current thread. If you\n create a new thread, and wish to use the default graph in that\n thread, you must explicitly add a `with g.as_default():` in that\n thread's function.\n\n The following code examples are equivalent:\n\n ```python\n # 1. Using Graph.as_default():\n g = tf.Graph()\n with g.as_default():\n c = tf.constant(5.0)\n assert c.graph is g\n\n # 2. Constructing and making default:\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0)\n assert c.graph is g\n ```\n\n If eager execution is enabled ops created under this context manager will be\n added to the graph instead of executed eagerly.\n\n Returns:\n A context manager for using this graph as the default graph.\n \"\"\"\n return _default_graph_stack.get_controller(self)\n\n @property\n def collections(self):\n \"\"\"Returns the names of the collections known to this graph.\"\"\"\n return list(self._collections)\n\n def add_to_collection(self, name, value):\n \"\"\"Stores `value` in the collection with the given `name`.\n\n Note that collections are not sets, so it is possible to add a value to\n a collection several times.\n\n Args:\n name: The key for the collection. The `GraphKeys` class contains many\n standard names for collections.\n value: The value to add to the collection.\n \"\"\" # pylint: disable=g-doc-exception\n self._check_not_finalized()\n with self._lock:\n if name not in self._collections:\n self._collections[name] = [value]\n else:\n self._collections[name].append(value)\n\n def add_to_collections(self, names, value):\n \"\"\"Stores `value` in the collections given by `names`.\n\n Note that collections are not sets, so it is possible to add a value to\n a collection several times. This function makes sure that duplicates in\n `names` are ignored, but it will not check for pre-existing membership of\n `value` in any of the collections in `names`.\n\n `names` can be any iterable, but if `names` is a string, it is treated as a\n single collection name.\n\n Args:\n names: The keys for the collections to add to. The `GraphKeys` class\n contains many standard names for collections.\n value: The value to add to the collections.\n \"\"\"\n # Make sure names are unique, but treat strings as a single collection name\n names = (names,) if isinstance(names, six.string_types) else set(names)\n for name in names:\n self.add_to_collection(name, value)\n\n def get_collection_ref(self, name):\n \"\"\"Returns a list of values in the collection with the given `name`.\n\n If the collection exists, this returns the list itself, which can\n be modified in place to change the collection. If the collection does\n not exist, it is created as an empty list and the list is returned.\n\n This is different from `get_collection()` which always returns a copy of\n the collection list if it exists and never creates an empty collection.\n\n Args:\n name: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n\n Returns:\n The list of values in the collection with the given `name`, or an empty\n list if no value has been added to that collection.\n \"\"\" # pylint: disable=g-doc-exception\n with self._lock:\n coll_list = self._collections.get(name, None)\n if coll_list is None:\n coll_list = []\n self._collections[name] = coll_list\n return coll_list\n\n def get_collection(self, name, scope=None):\n \"\"\"Returns a list of values in the collection with the given `name`.\n\n This is different from `get_collection_ref()` which always returns the\n actual collection list if it exists in that it returns a new list each time\n it is called.\n\n Args:\n name: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n scope: (Optional.) A string. If supplied, the resulting list is filtered\n to include only items whose `name` attribute matches `scope` using\n `re.match`. Items without a `name` attribute are never returned if a\n scope is supplied. The choice of `re.match` means that a `scope` without\n special tokens filters by prefix.\n\n Returns:\n The list of values in the collection with the given `name`, or\n an empty list if no value has been added to that collection. The\n list contains the values in the order under which they were\n collected.\n \"\"\" # pylint: disable=g-doc-exception\n with self._lock:\n collection = self._collections.get(name, None)\n if collection is None:\n return []\n if scope is None:\n return list(collection)\n else:\n c = []\n regex = re.compile(scope)\n for item in collection:\n try:\n if regex.match(item.name):\n c.append(item)\n except AttributeError:\n # Collection items with no name are ignored.\n pass\n return c\n\n def get_all_collection_keys(self):\n \"\"\"Returns a list of collections used in this graph.\"\"\"\n with self._lock:\n return [x for x in self._collections if isinstance(x, six.string_types)]\n\n def clear_collection(self, name):\n \"\"\"Clears all values in a collection.\n\n Args:\n name: The key for the collection. The `GraphKeys` class contains many\n standard names for collections.\n \"\"\"\n self._check_not_finalized()\n with self._lock:\n if name in self._collections:\n del self._collections[name]\n\n @tf_contextlib.contextmanager\n def _original_op(self, op):\n \"\"\"Python 'with' handler to help annotate ops with their originator.\n\n An op may have an 'original_op' property that indicates the op on which\n it was based. For example a replica op is based on the op that was\n replicated and a gradient op is based on the op that was differentiated.\n\n All ops created in the scope of this 'with' handler will have\n the given 'op' as their original op.\n\n Args:\n op: The Operation that all ops created in this scope will have as their\n original op.\n\n Yields:\n Nothing.\n \"\"\"\n old_original_op = self._default_original_op\n self._default_original_op = op\n try:\n yield\n finally:\n self._default_original_op = old_original_op\n\n @property\n def _name_stack(self):\n # This may be called from a thread where name_stack doesn't yet exist.\n if not hasattr(self._thread_local, \"_name_stack\"):\n self._thread_local._name_stack = \"\"\n return self._thread_local._name_stack\n\n @_name_stack.setter\n def _name_stack(self, name_stack):\n self._thread_local._name_stack = name_stack\n\n # pylint: disable=g-doc-return-or-yield,line-too-long\n @tf_contextlib.contextmanager\n def name_scope(self, name):\n \"\"\"Returns a context manager that creates hierarchical names for operations.\n\n A graph maintains a stack of name scopes. A `with name_scope(...):`\n statement pushes a new name onto the stack for the lifetime of the context.\n\n The `name` argument will be interpreted as follows:\n\n * A string (not ending with '/') will create a new name scope, in which\n `name` is appended to the prefix of all operations created in the\n context. If `name` has been used before, it will be made unique by\n calling `self.unique_name(name)`.\n * A scope previously captured from a `with g.name_scope(...) as\n scope:` statement will be treated as an \"absolute\" name scope, which\n makes it possible to re-enter existing scopes.\n * A value of `None` or the empty string will reset the current name scope\n to the top-level (empty) name scope.\n\n For example:\n\n ```python\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0, name=\"c\")\n assert c.op.name == \"c\"\n c_1 = tf.constant(6.0, name=\"c\")\n assert c_1.op.name == \"c_1\"\n\n # Creates a scope called \"nested\"\n with g.name_scope(\"nested\") as scope:\n nested_c = tf.constant(10.0, name=\"c\")\n assert nested_c.op.name == \"nested/c\"\n\n # Creates a nested scope called \"inner\".\n with g.name_scope(\"inner\"):\n nested_inner_c = tf.constant(20.0, name=\"c\")\n assert nested_inner_c.op.name == \"nested/inner/c\"\n\n # Create a nested scope called \"inner_1\".\n with g.name_scope(\"inner\"):\n nested_inner_1_c = tf.constant(30.0, name=\"c\")\n assert nested_inner_1_c.op.name == \"nested/inner_1/c\"\n\n # Treats `scope` as an absolute name scope, and\n # switches to the \"nested/\" scope.\n with g.name_scope(scope):\n nested_d = tf.constant(40.0, name=\"d\")\n assert nested_d.op.name == \"nested/d\"\n\n with g.name_scope(\"\"):\n e = tf.constant(50.0, name=\"e\")\n assert e.op.name == \"e\"\n ```\n\n The name of the scope itself can be captured by `with\n g.name_scope(...) as scope:`, which stores the name of the scope\n in the variable `scope`. This value can be used to name an\n operation that represents the overall result of executing the ops\n in a scope. For example:\n\n ```python\n inputs = tf.constant(...)\n with g.name_scope('my_layer') as scope:\n weights = tf.Variable(..., name=\"weights\")\n biases = tf.Variable(..., name=\"biases\")\n affine = tf.matmul(inputs, weights) + biases\n output = tf.nn.relu(affine, name=scope)\n ```\n\n NOTE: This constructor validates the given `name`. Valid scope\n names match one of the following regular expressions:\n\n [A-Za-z0-9.][A-Za-z0-9_.\\\\-/]* (for scopes at the root)\n [A-Za-z0-9_.\\\\-/]* (for other scopes)\n\n Args:\n name: A name for the scope.\n\n Returns:\n A context manager that installs `name` as a new name scope.\n\n Raises:\n ValueError: If `name` is not a valid scope name, according to the rules\n above.\n \"\"\"\n if name:\n if isinstance(name, compat.bytes_or_text_types):\n name = compat.as_str(name)\n\n if self._name_stack:\n # Scopes created in a nested scope may have initial characters\n # that are illegal as the initial character of an op name\n # (viz. '-', '\\', '/', and '_').\n if not _VALID_SCOPE_NAME_REGEX.match(name):\n raise ValueError(\"'%s' is not a valid scope name\" % name)\n else:\n # Scopes created in the root must match the more restrictive\n # op name regex, which constrains the initial character.\n if not _VALID_OP_NAME_REGEX.match(name):\n raise ValueError(\"'%s' is not a valid scope name\" % name)\n old_stack = self._name_stack\n if not name: # Both for name=None and name=\"\" we re-set to empty scope.\n new_stack = None\n elif name[-1] == \"/\":\n new_stack = name_from_scope_name(name)\n else:\n new_stack = self.unique_name(name)\n self._name_stack = new_stack\n try:\n yield \"\" if new_stack is None else new_stack + \"/\"\n finally:\n self._name_stack = old_stack\n\n # pylint: enable=g-doc-return-or-yield,line-too-long\n\n def unique_name(self, name, mark_as_used=True):\n \"\"\"Return a unique operation name for `name`.\n\n Note: You rarely need to call `unique_name()` directly. Most of\n the time you just need to create `with g.name_scope()` blocks to\n generate structured names.\n\n `unique_name` is used to generate structured names, separated by\n `\"/\"`, to help identify operations when debugging a graph.\n Operation names are displayed in error messages reported by the\n TensorFlow runtime, and in various visualization tools such as\n TensorBoard.\n\n If `mark_as_used` is set to `True`, which is the default, a new\n unique name is created and marked as in use. If it's set to `False`,\n the unique name is returned without actually being marked as used.\n This is useful when the caller simply wants to know what the name\n to be created will be.\n\n Args:\n name: The name for an operation.\n mark_as_used: Whether to mark this name as being used.\n\n Returns:\n A string to be passed to `create_op()` that will be used\n to name the operation being created.\n \"\"\"\n if self._name_stack:\n name = self._name_stack + \"/\" + name\n\n # For the sake of checking for names in use, we treat names as case\n # insensitive (e.g. foo = Foo).\n name_key = name.lower()\n i = self._names_in_use.get(name_key, 0)\n # Increment the number for \"name_key\".\n if mark_as_used:\n self._names_in_use[name_key] = i + 1\n if i > 0:\n base_name_key = name_key\n # Make sure the composed name key is not already used.\n while name_key in self._names_in_use:\n name_key = \"%s_%d\" % (base_name_key, i)\n i += 1\n # Mark the composed name_key as used in case someone wants\n # to call unique_name(\"name_1\").\n if mark_as_used:\n self._names_in_use[name_key] = 1\n\n # Return the new name with the original capitalization of the given name.\n name = \"%s_%d\" % (name, i - 1)\n return name\n\n def get_name_scope(self):\n \"\"\"Returns the current name scope.\n\n For example:\n\n ```python\n with tf.name_scope('scope1'):\n with tf.name_scope('scope2'):\n print(tf.compat.v1.get_default_graph().get_name_scope())\n ```\n would print the string `scope1/scope2`.\n\n Returns:\n A string representing the current name scope.\n \"\"\"\n return self._name_stack\n\n @tf_contextlib.contextmanager\n def _colocate_with_for_gradient(self, op, gradient_uid,\n ignore_existing=False):\n with self.colocate_with(op, ignore_existing):\n if gradient_uid is not None and self._control_flow_context is not None:\n self._control_flow_context.EnterGradientColocation(op, gradient_uid)\n try:\n yield\n finally:\n self._control_flow_context.ExitGradientColocation(op, gradient_uid)\n else:\n yield\n\n @tf_contextlib.contextmanager\n def colocate_with(self, op, ignore_existing=False):\n \"\"\"Returns a context manager that specifies an op to colocate with.\n\n Note: this function is not for public use, only for internal libraries.\n\n For example:\n\n ```python\n a = tf.Variable([1.0])\n with g.colocate_with(a):\n b = tf.constant(1.0)\n c = tf.add(a, b)\n ```\n\n `b` and `c` will always be colocated with `a`, no matter where `a`\n is eventually placed.\n\n **NOTE** Using a colocation scope resets any existing device constraints.\n\n If `op` is `None` then `ignore_existing` must be `True` and the new\n scope resets all colocation and device constraints.\n\n Args:\n op: The op to colocate all created ops with, or `None`.\n ignore_existing: If true, only applies colocation of this op within the\n context, rather than applying all colocation properties on the stack.\n If `op` is `None`, this value must be `True`.\n\n Raises:\n ValueError: if op is None but ignore_existing is False.\n\n Yields:\n A context manager that specifies the op with which to colocate\n newly created ops.\n \"\"\"\n if op is None and not ignore_existing:\n raise ValueError(\"Trying to reset colocation (op is None) but \"\n \"ignore_existing is not True\")\n op = _op_to_colocate_with(op, self)\n\n # By default, colocate_with resets the device function stack,\n # since colocate_with is typically used in specific internal\n # library functions where colocation is intended to be \"stronger\"\n # than device functions.\n #\n # In the future, a caller may specify that device_functions win\n # over colocation, in which case we can add support.\n device_fn_tmp = self._device_function_stack\n self._device_function_stack = traceable_stack.TraceableStack()\n\n if ignore_existing:\n current_stack = self._colocation_stack\n self._colocation_stack = traceable_stack.TraceableStack()\n\n if op is not None:\n # offset refers to the stack frame used for storing code location.\n # We use 4, the sum of 1 to use our caller's stack frame and 3\n # to jump over layers of context managers above us.\n self._colocation_stack.push_obj(op, offset=4)\n\n try:\n yield\n finally:\n # Restore device function stack\n self._device_function_stack = device_fn_tmp\n if op is not None:\n self._colocation_stack.pop_obj()\n\n # Reset the colocation stack if requested.\n if ignore_existing:\n self._colocation_stack = current_stack\n\n def _add_device_to_stack(self, device_name_or_function, offset=0):\n \"\"\"Add device to stack manually, separate from a context manager.\"\"\"\n total_offset = 1 + offset\n spec = _UserDeviceSpec(device_name_or_function)\n self._device_function_stack.push_obj(spec, offset=total_offset)\n return spec\n\n @tf_contextlib.contextmanager\n def device(self, device_name_or_function):\n # pylint: disable=line-too-long\n \"\"\"Returns a context manager that specifies the default device to use.\n\n The `device_name_or_function` argument may either be a device name\n string, a device function, or None:\n\n * If it is a device name string, all operations constructed in\n this context will be assigned to the device with that name, unless\n overridden by a nested `device()` context.\n * If it is a function, it will be treated as a function from\n Operation objects to device name strings, and invoked each time\n a new Operation is created. The Operation will be assigned to\n the device with the returned name.\n * If it is None, all `device()` invocations from the enclosing context\n will be ignored.\n\n For information about the valid syntax of device name strings, see\n the documentation in\n [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h).\n\n For example:\n\n ```python\n with g.device('/device:GPU:0'):\n # All operations constructed in this context will be placed\n # on GPU 0.\n with g.device(None):\n # All operations constructed in this context will have no\n # assigned device.\n\n # Defines a function from `Operation` to device string.\n def matmul_on_gpu(n):\n if n.type == \"MatMul\":\n return \"/device:GPU:0\"\n else:\n return \"/cpu:0\"\n\n with g.device(matmul_on_gpu):\n # All operations of type \"MatMul\" constructed in this context\n # will be placed on GPU 0; all other operations will be placed\n # on CPU 0.\n ```\n\n **N.B.** The device scope may be overridden by op wrappers or\n other library code. For example, a variable assignment op\n `v.assign()` must be colocated with the `tf.Variable` `v`, and\n incompatible device scopes will be ignored.\n\n Args:\n device_name_or_function: The device name or function to use in the\n context.\n\n Yields:\n A context manager that specifies the default device to use for newly\n created ops.\n\n Raises:\n RuntimeError: If device scopes are not properly nested.\n \"\"\"\n self._add_device_to_stack(device_name_or_function, offset=2)\n old_top_of_stack = self._device_function_stack.peek_top_obj()\n try:\n yield\n finally:\n new_top_of_stack = self._device_function_stack.peek_top_obj()\n if old_top_of_stack is not new_top_of_stack:\n raise RuntimeError(\"Exiting device scope without proper scope nesting.\")\n self._device_function_stack.pop_obj()\n\n def _apply_device_functions(self, op):\n \"\"\"Applies the current device function stack to the given operation.\"\"\"\n # Apply any device functions in LIFO order, so that the most recently\n # pushed function has the first chance to apply a device to the op.\n # We apply here because the result can depend on the Operation's\n # signature, which is computed in the Operation constructor.\n # pylint: disable=protected-access\n prior_device_string = None\n for device_spec in self._device_function_stack.peek_objs():\n if device_spec.is_null_merge:\n continue\n\n if device_spec.function is None:\n break\n\n device_string = device_spec.string_merge(op)\n\n # Take advantage of the fact that None is a singleton and Python interns\n # strings, since identity checks are faster than equality checks.\n if device_string is not prior_device_string:\n op._set_device_from_string(device_string)\n prior_device_string = device_string\n op._device_code_locations = self._snapshot_device_function_stack_metadata()\n # pylint: enable=protected-access\n\n # pylint: disable=g-doc-return-or-yield\n @tf_contextlib.contextmanager\n def container(self, container_name):\n \"\"\"Returns a context manager that specifies the resource container to use.\n\n Stateful operations, such as variables and queues, can maintain their\n states on devices so that they can be shared by multiple processes.\n A resource container is a string name under which these stateful\n operations are tracked. These resources can be released or cleared\n with `tf.Session.reset()`.\n\n For example:\n\n ```python\n with g.container('experiment0'):\n # All stateful Operations constructed in this context will be placed\n # in resource container \"experiment0\".\n v1 = tf.Variable([1.0])\n v2 = tf.Variable([2.0])\n with g.container(\"experiment1\"):\n # All stateful Operations constructed in this context will be\n # placed in resource container \"experiment1\".\n v3 = tf.Variable([3.0])\n q1 = tf.queue.FIFOQueue(10, tf.float32)\n # All stateful Operations constructed in this context will be\n # be created in the \"experiment0\".\n v4 = tf.Variable([4.0])\n q1 = tf.queue.FIFOQueue(20, tf.float32)\n with g.container(\"\"):\n # All stateful Operations constructed in this context will be\n # be placed in the default resource container.\n v5 = tf.Variable([5.0])\n q3 = tf.queue.FIFOQueue(30, tf.float32)\n\n # Resets container \"experiment0\", after which the state of v1, v2, v4, q1\n # will become undefined (such as uninitialized).\n tf.Session.reset(target, [\"experiment0\"])\n ```\n\n Args:\n container_name: container name string.\n\n Returns:\n A context manager for defining resource containers for stateful ops,\n yields the container name.\n \"\"\"\n original_container = self._container\n self._container = container_name\n try:\n yield self._container\n finally:\n self._container = original_container\n\n # pylint: enable=g-doc-return-or-yield\n\n class _ControlDependenciesController(object):\n \"\"\"Context manager for `control_dependencies()`.\"\"\"\n\n def __init__(self, graph, control_inputs):\n \"\"\"Create a new `_ControlDependenciesController`.\n\n A `_ControlDependenciesController` is the context manager for\n `with tf.control_dependencies()` blocks. These normally nest,\n as described in the documentation for `control_dependencies()`.\n\n The `control_inputs` argument list control dependencies that must be\n added to the current set of control dependencies. Because of\n uniquification the set can be empty even if the caller passed a list of\n ops. The special value `None` indicates that we want to start a new\n empty set of control dependencies instead of extending the current set.\n\n In that case we also clear the current control flow context, which is an\n additional mechanism to add control dependencies.\n\n Args:\n graph: The graph that this controller is managing.\n control_inputs: List of ops to use as control inputs in addition to the\n current control dependencies. None to indicate that the dependencies\n should be cleared.\n \"\"\"\n self._graph = graph\n if control_inputs is None:\n self._control_inputs_val = []\n self._new_stack = True\n else:\n self._control_inputs_val = control_inputs\n self._new_stack = False\n self._seen_nodes = set()\n self._old_stack = None\n self._old_control_flow_context = None\n\n# pylint: disable=protected-access\n\n def __enter__(self):\n if self._new_stack:\n # Clear the control_dependencies graph.\n self._old_stack = self._graph._control_dependencies_stack\n self._graph._control_dependencies_stack = []\n # Clear the control_flow_context too.\n self._old_control_flow_context = self._graph._get_control_flow_context()\n self._graph._set_control_flow_context(None)\n self._graph._push_control_dependencies_controller(self)\n\n def __exit__(self, unused_type, unused_value, unused_traceback):\n self._graph._pop_control_dependencies_controller(self)\n if self._new_stack:\n self._graph._control_dependencies_stack = self._old_stack\n self._graph._set_control_flow_context(self._old_control_flow_context)\n\n# pylint: enable=protected-access\n\n @property\n def control_inputs(self):\n return self._control_inputs_val\n\n def add_op(self, op):\n if isinstance(op, Tensor):\n op = op.experimental_ref()\n self._seen_nodes.add(op)\n\n def op_in_group(self, op):\n if isinstance(op, Tensor):\n op = op.experimental_ref()\n return op in self._seen_nodes\n\n def _push_control_dependencies_controller(self, controller):\n self._control_dependencies_stack.append(controller)\n\n def _pop_control_dependencies_controller(self, controller):\n assert self._control_dependencies_stack[-1] is controller\n self._control_dependencies_stack.pop()\n\n def _current_control_dependencies(self):\n ret = set()\n for controller in self._control_dependencies_stack:\n for op in controller.control_inputs:\n ret.add(op)\n return ret\n\n def _control_dependencies_for_inputs(self, input_ops):\n \"\"\"For an op that takes `input_ops` as inputs, compute control inputs.\n\n The returned control dependencies should yield an execution that\n is equivalent to adding all control inputs in\n self._control_dependencies_stack to a newly created op. However,\n this function attempts to prune the returned control dependencies\n by observing that nodes created within the same `with\n control_dependencies(...):` block may have data dependencies that make\n the explicit approach redundant.\n\n Args:\n input_ops: The data input ops for an op to be created.\n\n Returns:\n A list of control inputs for the op to be created.\n \"\"\"\n ret = []\n for controller in self._control_dependencies_stack:\n # If any of the input_ops already depends on the inputs from controller,\n # we say that the new op is dominated (by that input), and we therefore\n # do not need to add control dependencies for this controller's inputs.\n dominated = False\n for op in input_ops:\n if controller.op_in_group(op):\n dominated = True\n break\n if not dominated:\n # Don't add a control input if we already have a data dependency on i.\n # NOTE(mrry): We do not currently track transitive data dependencies,\n # so we may add redundant control inputs.\n ret.extend([c for c in controller.control_inputs if c not in input_ops])\n return ret\n\n def _record_op_seen_by_control_dependencies(self, op):\n \"\"\"Record that the given op depends on all registered control dependencies.\n\n Args:\n op: An Operation.\n \"\"\"\n for controller in self._control_dependencies_stack:\n controller.add_op(op)\n\n def control_dependencies(self, control_inputs):\n \"\"\"Returns a context manager that specifies control dependencies.\n\n Use with the `with` keyword to specify that all operations constructed\n within the context should have control dependencies on\n `control_inputs`. For example:\n\n ```python\n with g.control_dependencies([a, b, c]):\n # `d` and `e` will only run after `a`, `b`, and `c` have executed.\n d = ...\n e = ...\n ```\n\n Multiple calls to `control_dependencies()` can be nested, and in\n that case a new `Operation` will have control dependencies on the union\n of `control_inputs` from all active contexts.\n\n ```python\n with g.control_dependencies([a, b]):\n # Ops constructed here run after `a` and `b`.\n with g.control_dependencies([c, d]):\n # Ops constructed here run after `a`, `b`, `c`, and `d`.\n ```\n\n You can pass None to clear the control dependencies:\n\n ```python\n with g.control_dependencies([a, b]):\n # Ops constructed here run after `a` and `b`.\n with g.control_dependencies(None):\n # Ops constructed here run normally, not waiting for either `a` or `b`.\n with g.control_dependencies([c, d]):\n # Ops constructed here run after `c` and `d`, also not waiting\n # for either `a` or `b`.\n ```\n\n *N.B.* The control dependencies context applies *only* to ops that\n are constructed within the context. Merely using an op or tensor\n in the context does not add a control dependency. The following\n example illustrates this point:\n\n ```python\n # WRONG\n def my_func(pred, tensor):\n t = tf.matmul(tensor, tensor)\n with tf.control_dependencies([pred]):\n # The matmul op is created outside the context, so no control\n # dependency will be added.\n return t\n\n # RIGHT\n def my_func(pred, tensor):\n with tf.control_dependencies([pred]):\n # The matmul op is created in the context, so a control dependency\n # will be added.\n return tf.matmul(tensor, tensor)\n ```\n\n Also note that though execution of ops created under this scope will trigger\n execution of the dependencies, the ops created under this scope might still\n be pruned from a normal tensorflow graph. For example, in the following\n snippet of code the dependencies are never executed:\n\n ```python\n loss = model.loss()\n with tf.control_dependencies(dependencies):\n loss = loss + tf.constant(1) # note: dependencies ignored in the\n # backward pass\n return tf.gradients(loss, model.variables)\n ```\n\n This is because evaluating the gradient graph does not require evaluating\n the constant(1) op created in the forward pass.\n\n Args:\n control_inputs: A list of `Operation` or `Tensor` objects which must be\n executed or computed before running the operations defined in the\n context. Can also be `None` to clear the control dependencies.\n\n Returns:\n A context manager that specifies control dependencies for all\n operations constructed within the context.\n\n Raises:\n TypeError: If `control_inputs` is not a list of `Operation` or\n `Tensor` objects.\n \"\"\"\n if control_inputs is None:\n return self._ControlDependenciesController(self, None)\n # First convert the inputs to ops, and deduplicate them.\n # NOTE(mrry): Other than deduplication, we do not currently track direct\n # or indirect dependencies between control_inputs, which may result in\n # redundant control inputs.\n control_ops = []\n current = self._current_control_dependencies()\n for c in control_inputs:\n # The hasattr(handle) is designed to match ResourceVariables. This is so\n # control dependencies on a variable or on an unread variable don't\n # trigger reads.\n if (isinstance(c, IndexedSlices) or\n (hasattr(c, \"_handle\") and hasattr(c, \"op\"))):\n c = c.op\n c = self.as_graph_element(c)\n if isinstance(c, Tensor):\n c = c.op\n elif not isinstance(c, Operation):\n raise TypeError(\"Control input must be Operation or Tensor: %s\" % c)\n if c not in current:\n control_ops.append(c)\n current.add(c)\n return self._ControlDependenciesController(self, control_ops)\n\n # pylint: disable=g-doc-return-or-yield\n @tf_contextlib.contextmanager\n def _attr_scope(self, attr_map):\n \"\"\"EXPERIMENTAL: A context manager for setting attributes on operators.\n\n This context manager can be used to add additional\n attributes to operators within the scope of the context.\n\n For example:\n\n with ops.Graph().as_default() as g:\n f_1 = Foo() # No extra attributes\n with g._attr_scope({\"_a\": tf.attr_value_pb2.AttrValue(b=False)}):\n f_2 = Foo() # Additional attribute _a=False\n with g._attr_scope({\"_a\": tf.attr_value_pb2.AttrValue(b=True)}):\n f_3 = Foo() # Additional attribute _a=False\n with g._attr_scope({\"_a\": None}):\n f_4 = Foo() # No additional attributes.\n\n Args:\n attr_map: A dictionary mapping attr name strings to AttrValue protocol\n buffers or None.\n\n Returns:\n A context manager that sets the kernel label to be used for one or more\n ops created in that context.\n\n Raises:\n TypeError: If attr_map is not a dictionary mapping\n strings to AttrValue protobufs.\n \"\"\"\n if not isinstance(attr_map, dict):\n raise TypeError(\"attr_map must be a dictionary mapping \"\n \"strings to AttrValue protocol buffers\")\n # The saved_attrs dictionary stores any currently-set labels that\n # will be overridden by this context manager.\n saved_attrs = {}\n # Install the given attribute\n for name, attr in attr_map.items():\n if not (isinstance(name, six.string_types) and\n (isinstance(attr, (type(None), attr_value_pb2.AttrValue)) or\n callable(attr))):\n raise TypeError(\"attr_map must be a dictionary mapping \"\n \"strings to AttrValue protocol buffers or \"\n \"callables that emit AttrValue protocol buffers\")\n try:\n saved_attrs[name] = self._attr_scope_map[name]\n except KeyError:\n pass\n if attr is None:\n del self._attr_scope_map[name]\n else:\n self._attr_scope_map[name] = attr\n try:\n yield # The code within the context runs here.\n finally:\n # Remove the attributes set for this context, and restore any saved\n # attributes.\n for name, attr in attr_map.items():\n try:\n self._attr_scope_map[name] = saved_attrs[name]\n except KeyError:\n del self._attr_scope_map[name]\n\n # pylint: enable=g-doc-return-or-yield\n\n # pylint: disable=g-doc-return-or-yield\n @tf_contextlib.contextmanager\n def _kernel_label_map(self, op_to_kernel_label_map):\n \"\"\"EXPERIMENTAL: A context manager for setting kernel labels.\n\n This context manager can be used to select particular\n implementations of kernels within the scope of the context.\n\n For example:\n\n with ops.Graph().as_default() as g:\n f_1 = Foo() # Uses the default registered kernel for the Foo op.\n with g.kernel_label_map({\"Foo\": \"v_2\"}):\n f_2 = Foo() # Uses the registered kernel with label \"v_2\"\n # for the Foo op.\n with g.kernel_label_map({\"Foo\": \"v_3\"}):\n f_3 = Foo() # Uses the registered kernel with label \"v_3\"\n # for the Foo op.\n with g.kernel_label_map({\"Foo\": \"\"}):\n f_4 = Foo() # Uses the default registered kernel\n # for the Foo op.\n\n Args:\n op_to_kernel_label_map: A dictionary mapping op type strings to kernel\n label strings.\n\n Returns:\n A context manager that sets the kernel label to be used for one or more\n ops created in that context.\n\n Raises:\n TypeError: If op_to_kernel_label_map is not a dictionary mapping\n strings to strings.\n \"\"\"\n if not isinstance(op_to_kernel_label_map, dict):\n raise TypeError(\"op_to_kernel_label_map must be a dictionary mapping \"\n \"strings to strings\")\n # The saved_labels dictionary stores any currently-set labels that\n # will be overridden by this context manager.\n saved_labels = {}\n # Install the given label\n for op_type, label in op_to_kernel_label_map.items():\n if not (isinstance(op_type, six.string_types) and\n isinstance(label, six.string_types)):\n raise TypeError(\"op_to_kernel_label_map must be a dictionary mapping \"\n \"strings to strings\")\n try:\n saved_labels[op_type] = self._op_to_kernel_label_map[op_type]\n except KeyError:\n pass\n self._op_to_kernel_label_map[op_type] = label\n try:\n yield # The code within the context runs here.\n finally:\n # Remove the labels set for this context, and restore any saved labels.\n for op_type, label in op_to_kernel_label_map.items():\n try:\n self._op_to_kernel_label_map[op_type] = saved_labels[op_type]\n except KeyError:\n del self._op_to_kernel_label_map[op_type]\n\n # pylint: enable=g-doc-return-or-yield\n\n @tf_contextlib.contextmanager\n def _override_gradient_function(self, gradient_function_map):\n \"\"\"Specify gradient function for the given op type.\"\"\"\n\n # This is an internal API and we don't need nested context for this.\n assert not self._gradient_function_map\n self._gradient_function_map = gradient_function_map\n yield\n self._gradient_function_map = {}\n\n # pylint: disable=g-doc-return-or-yield\n @tf_contextlib.contextmanager\n def gradient_override_map(self, op_type_map):\n \"\"\"EXPERIMENTAL: A context manager for overriding gradient functions.\n\n This context manager can be used to override the gradient function\n that will be used for ops within the scope of the context.\n\n For example:\n\n ```python\n @tf.RegisterGradient(\"CustomSquare\")\n def _custom_square_grad(op, grad):\n # ...\n\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0)\n s_1 = tf.square(c) # Uses the default gradient for tf.square.\n with g.gradient_override_map({\"Square\": \"CustomSquare\"}):\n s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the\n # gradient of s_2.\n ```\n\n Args:\n op_type_map: A dictionary mapping op type strings to alternative op type\n strings.\n\n Returns:\n A context manager that sets the alternative op type to be used for one\n or more ops created in that context.\n\n Raises:\n TypeError: If `op_type_map` is not a dictionary mapping strings to\n strings.\n \"\"\"\n if not isinstance(op_type_map, dict):\n raise TypeError(\"op_type_map must be a dictionary mapping \"\n \"strings to strings\")\n # The saved_mappings dictionary stores any currently-set mappings that\n # will be overridden by this context manager.\n saved_mappings = {}\n # Install the given label\n for op_type, mapped_op_type in op_type_map.items():\n if not (isinstance(op_type, six.string_types) and\n isinstance(mapped_op_type, six.string_types)):\n raise TypeError(\"op_type_map must be a dictionary mapping \"\n \"strings to strings\")\n try:\n saved_mappings[op_type] = self._gradient_override_map[op_type]\n except KeyError:\n pass\n self._gradient_override_map[op_type] = mapped_op_type\n try:\n yield # The code within the context runs here.\n finally:\n # Remove the labels set for this context, and restore any saved labels.\n for op_type, mapped_op_type in op_type_map.items():\n try:\n self._gradient_override_map[op_type] = saved_mappings[op_type]\n except KeyError:\n del self._gradient_override_map[op_type]\n\n # pylint: enable=g-doc-return-or-yield\n\n def prevent_feeding(self, tensor):\n \"\"\"Marks the given `tensor` as unfeedable in this graph.\"\"\"\n self._unfeedable_tensors.add(tensor)\n\n def is_feedable(self, tensor):\n \"\"\"Returns `True` if and only if `tensor` is feedable.\"\"\"\n return tensor not in self._unfeedable_tensors\n\n def prevent_fetching(self, op):\n \"\"\"Marks the given `op` as unfetchable in this graph.\"\"\"\n self._unfetchable_ops.add(op)\n\n def is_fetchable(self, tensor_or_op):\n \"\"\"Returns `True` if and only if `tensor_or_op` is fetchable.\"\"\"\n if isinstance(tensor_or_op, Tensor):\n return tensor_or_op.op not in self._unfetchable_ops\n else:\n return tensor_or_op not in self._unfetchable_ops\n\n def switch_to_thread_local(self):\n \"\"\"Make device, colocation and dependencies stacks thread-local.\n\n Device, colocation and dependencies stacks are not thread-local be default.\n If multiple threads access them, then the state is shared. This means that\n one thread may affect the behavior of another thread.\n\n After this method is called, the stacks become thread-local. If multiple\n threads access them, then the state is not shared. Each thread uses its own\n value; a thread doesn't affect other threads by mutating such a stack.\n\n The initial value for every thread's stack is set to the current value\n of the stack when `switch_to_thread_local()` was first called.\n \"\"\"\n if not self._stack_state_is_thread_local:\n self._stack_state_is_thread_local = True\n\n @property\n def _device_function_stack(self):\n if self._stack_state_is_thread_local:\n # This may be called from a thread where device_function_stack doesn't yet\n # exist.\n # pylint: disable=protected-access\n if not hasattr(self._thread_local, \"_device_function_stack\"):\n stack_copy_for_this_thread = self._graph_device_function_stack.copy()\n self._thread_local._device_function_stack = stack_copy_for_this_thread\n return self._thread_local._device_function_stack\n # pylint: enable=protected-access\n else:\n return self._graph_device_function_stack\n\n @property\n def _device_functions_outer_to_inner(self):\n user_device_specs = self._device_function_stack.peek_objs()\n device_functions = [spec.function for spec in user_device_specs]\n device_functions_outer_to_inner = list(reversed(device_functions))\n return device_functions_outer_to_inner\n\n def _snapshot_device_function_stack_metadata(self):\n \"\"\"Return device function stack as a list of TraceableObjects.\n\n Returns:\n [traceable_stack.TraceableObject, ...] where each TraceableObject's .obj\n member is a displayable name for the user's argument to Graph.device, and\n the filename and lineno members point to the code location where\n Graph.device was called directly or indirectly by the user.\n \"\"\"\n snapshot = []\n for obj in self._device_function_stack.peek_traceable_objs():\n obj_copy = obj.copy_metadata()\n obj_copy.obj = obj.obj.display_name\n snapshot.append(obj_copy)\n return snapshot\n\n @_device_function_stack.setter\n def _device_function_stack(self, device_function_stack):\n if self._stack_state_is_thread_local:\n # pylint: disable=protected-access\n self._thread_local._device_function_stack = device_function_stack\n # pylint: enable=protected-access\n else:\n self._graph_device_function_stack = device_function_stack\n\n @property\n def _colocation_stack(self):\n \"\"\"Return thread-local copy of colocation stack.\"\"\"\n if self._stack_state_is_thread_local:\n # This may be called from a thread where colocation_stack doesn't yet\n # exist.\n # pylint: disable=protected-access\n if not hasattr(self._thread_local, \"_colocation_stack\"):\n stack_copy_for_this_thread = self._graph_colocation_stack.copy()\n self._thread_local._colocation_stack = stack_copy_for_this_thread\n return self._thread_local._colocation_stack\n # pylint: enable=protected-access\n else:\n return self._graph_colocation_stack\n\n def _snapshot_colocation_stack_metadata(self):\n \"\"\"Return colocation stack metadata as a dictionary.\"\"\"\n return {\n traceable_obj.obj.name: traceable_obj.copy_metadata()\n for traceable_obj in self._colocation_stack.peek_traceable_objs()\n }\n\n @_colocation_stack.setter\n def _colocation_stack(self, colocation_stack):\n if self._stack_state_is_thread_local:\n # pylint: disable=protected-access\n self._thread_local._colocation_stack = colocation_stack\n # pylint: enable=protected-access\n else:\n self._graph_colocation_stack = colocation_stack\n\n @property\n def _control_dependencies_stack(self):\n if self._stack_state_is_thread_local:\n # This may be called from a thread where control_dependencies_stack\n # doesn't yet exist.\n if not hasattr(self._thread_local, \"_control_dependencies_stack\"):\n self._thread_local._control_dependencies_stack = (\n self._graph_control_dependencies_stack[:])\n return self._thread_local._control_dependencies_stack\n else:\n return self._graph_control_dependencies_stack\n\n @_control_dependencies_stack.setter\n def _control_dependencies_stack(self, control_dependencies):\n if self._stack_state_is_thread_local:\n self._thread_local._control_dependencies_stack = control_dependencies\n else:\n self._graph_control_dependencies_stack = control_dependencies\n\n @property\n def _distribution_strategy_stack(self):\n \"\"\"A stack to maintain distribution strategy context for each thread.\"\"\"\n if not hasattr(self._thread_local, \"_distribution_strategy_stack\"):\n self._thread_local._distribution_strategy_stack = [] # pylint: disable=protected-access\n return self._thread_local._distribution_strategy_stack # pylint: disable=protected-access\n\n @_distribution_strategy_stack.setter\n def _distribution_strategy_stack(self, _distribution_strategy_stack):\n self._thread_local._distribution_strategy_stack = ( # pylint: disable=protected-access\n _distribution_strategy_stack)\n\n @property\n def _global_distribute_strategy_scope(self):\n \"\"\"For implementing `tf.distribute.set_strategy()`.\"\"\"\n if not hasattr(self._thread_local, \"distribute_strategy_scope\"):\n self._thread_local.distribute_strategy_scope = None\n return self._thread_local.distribute_strategy_scope\n\n @_global_distribute_strategy_scope.setter\n def _global_distribute_strategy_scope(self, distribute_strategy_scope):\n self._thread_local.distribute_strategy_scope = (distribute_strategy_scope)\n\n @property\n def _auto_cast_variable_read_dtype(self):\n \"\"\"The dtype that instances of `AutoCastVariable` will be casted to.\n\n This is None if `AutoCastVariables` should not be casted.\n\n See `AutoCastVariable` for more information.\n\n Returns:\n The dtype that instances of `AutoCastVariable` will be casted to.\n \"\"\"\n if not hasattr(self._thread_local, \"_auto_cast_variable_read_dtype\"):\n self._thread_local._auto_cast_variable_read_dtype = None # pylint: disable=protected-access\n return self._thread_local._auto_cast_variable_read_dtype # pylint: disable=protected-access\n\n @_auto_cast_variable_read_dtype.setter\n def _auto_cast_variable_read_dtype(self, dtype):\n if dtype:\n dtype = dtypes.as_dtype(dtype)\n self._thread_local._auto_cast_variable_read_dtype = dtype # pylint: disable=protected-access\n\n @tf_contextlib.contextmanager\n def _enable_auto_casting_variables(self, dtype):\n \"\"\"Context manager to automatically cast AutoCastVariables.\n\n If an AutoCastVariable `var` is used under this context manager, it will be\n casted to `dtype` before being used.\n\n See `AutoCastVariable` for more information.\n\n Args:\n dtype: The dtype that AutoCastVariables should be casted to.\n\n Yields:\n Nothing.\n \"\"\"\n prev_read_dtype = self._auto_cast_variable_read_dtype\n try:\n self._auto_cast_variable_read_dtype = dtype\n yield\n finally:\n self._auto_cast_variable_read_dtype = prev_read_dtype\n\n def _mutation_lock(self):\n \"\"\"Returns a lock to guard code that creates & mutates ops.\n\n See the comment for self._group_lock for more info.\n \"\"\"\n return self._group_lock.group(_MUTATION_LOCK_GROUP)\n\n def _session_run_lock(self):\n \"\"\"Returns a lock to guard code for Session.run.\n\n See the comment for self._group_lock for more info.\n \"\"\"\n return self._group_lock.group(_SESSION_RUN_LOCK_GROUP)\n\n\n# TODO(agarwal): currently device directives in an outer eager scope will not\n# apply to inner graph mode code. Fix that.\n\n\n@tf_export(v1=[\"device\"])\ndef device(device_name_or_function):\n \"\"\"Wrapper for `Graph.device()` using the default graph.\n\n See `tf.Graph.device` for more details.\n\n Args:\n device_name_or_function: The device name or function to use in the context.\n\n Returns:\n A context manager that specifies the default device to use for newly\n created ops.\n\n Raises:\n RuntimeError: If eager execution is enabled and a function is passed in.\n \"\"\"\n if context.executing_eagerly():\n if callable(device_name_or_function):\n raise RuntimeError(\n \"tf.device does not support functions when eager execution \"\n \"is enabled.\")\n return context.device(device_name_or_function)\n elif executing_eagerly_outside_functions():\n @tf_contextlib.contextmanager\n def combined(device_name_or_function):\n with get_default_graph().device(device_name_or_function):\n if not callable(device_name_or_function):\n with context.device(device_name_or_function):\n yield\n else:\n yield\n return combined(device_name_or_function)\n else:\n return get_default_graph().device(device_name_or_function)\n\n\n@tf_export(\"device\", v1=[])\ndef device_v2(device_name):\n \"\"\"Specifies the device for ops created/executed in this context.\n\n `device_name` can be fully specified, as in \"/job:worker/task:1/device:cpu:0\",\n or partially specified, containing only a subset of the \"/\"-separated\n fields. Any fields which are specified override device annotations from outer\n scopes. For example:\n\n ```python\n with tf.device('/job:foo'):\n # ops created here have devices with /job:foo\n with tf.device('/job:bar/task:0/device:gpu:2'):\n # ops created here have the fully specified device above\n with tf.device('/device:gpu:1'):\n # ops created here have the device '/job:foo/device:gpu:1'\n ```\n\n Args:\n device_name: The device name to use in the context.\n\n Returns:\n A context manager that specifies the default device to use for newly\n created ops.\n\n Raises:\n RuntimeError: If a function is passed in.\n \"\"\"\n if callable(device_name):\n raise RuntimeError(\"tf.device does not support functions.\")\n return device(device_name)\n\n\n@tf_export(v1=[\"container\"])\ndef container(container_name):\n \"\"\"Wrapper for `Graph.container()` using the default graph.\n\n Args:\n container_name: The container string to use in the context.\n\n Returns:\n A context manager that specifies the default container to use for newly\n created stateful ops.\n \"\"\"\n return get_default_graph().container(container_name)\n\n\ndef _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False):\n if context.executing_eagerly():\n if op is not None:\n if not hasattr(op, \"device\"):\n op = internal_convert_to_tensor_or_indexed_slices(op)\n return device(op.device)\n else:\n return NullContextmanager()\n else:\n default_graph = get_default_graph()\n if isinstance(op, EagerTensor):\n if default_graph.building_function:\n return default_graph.device(op.device)\n else:\n raise ValueError(\"Encountered an Eager-defined Tensor during graph \"\n \"construction, but a function was not being built.\")\n return default_graph._colocate_with_for_gradient(\n op, gradient_uid=gradient_uid, ignore_existing=ignore_existing)\n\n\n# Internal interface to colocate_with. colocate_with has been deprecated from\n# public API. There are still a few internal uses of colocate_with. Add internal\n# only API for those uses to avoid deprecation warning.\ndef colocate_with(op, ignore_existing=False):\n return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing)\n\n\n@deprecation.deprecated(\n date=None, instructions=\"Colocations handled automatically by placer.\")\n@tf_export(v1=[\"colocate_with\"])\ndef _colocate_with(op, ignore_existing=False):\n return colocate_with(op, ignore_existing)\n\n\n@tf_export(\"control_dependencies\")\ndef control_dependencies(control_inputs):\n \"\"\"Wrapper for `Graph.control_dependencies()` using the default graph.\n\n See `tf.Graph.control_dependencies`\n for more details.\n\n When eager execution is enabled, any callable object in the `control_inputs`\n list will be called.\n\n Args:\n control_inputs: A list of `Operation` or `Tensor` objects which must be\n executed or computed before running the operations defined in the context.\n Can also be `None` to clear the control dependencies. If eager execution\n is enabled, any callable object in the `control_inputs` list will be\n called.\n\n Returns:\n A context manager that specifies control dependencies for all\n operations constructed within the context.\n \"\"\"\n if context.executing_eagerly():\n if control_inputs:\n # Excute any pending callables.\n for control in control_inputs:\n if callable(control):\n control()\n return NullContextmanager()\n else:\n return get_default_graph().control_dependencies(control_inputs)\n\n\nclass _DefaultStack(threading.local):\n \"\"\"A thread-local stack of objects for providing implicit defaults.\"\"\"\n\n def __init__(self):\n super(_DefaultStack, self).__init__()\n self._enforce_nesting = True\n self.stack = []\n\n def get_default(self):\n return self.stack[-1] if len(self.stack) >= 1 else None\n\n def reset(self):\n self.stack = []\n\n def is_cleared(self):\n return not self.stack\n\n @property\n def enforce_nesting(self):\n return self._enforce_nesting\n\n @enforce_nesting.setter\n def enforce_nesting(self, value):\n self._enforce_nesting = value\n\n @tf_contextlib.contextmanager\n def get_controller(self, default):\n \"\"\"A context manager for manipulating a default stack.\"\"\"\n self.stack.append(default)\n try:\n yield default\n finally:\n # stack may be empty if reset() was called\n if self.stack:\n if self._enforce_nesting:\n if self.stack[-1] is not default:\n raise AssertionError(\n \"Nesting violated for default stack of %s objects\" %\n type(default))\n self.stack.pop()\n else:\n self.stack.remove(default)\n\n\n_default_session_stack = _DefaultStack() # pylint: disable=protected-access\n\n\ndef default_session(session):\n \"\"\"Python \"with\" handler for defining a default session.\n\n This function provides a means of registering a session for handling\n Tensor.eval() and Operation.run() calls. It is primarily intended for use\n by session.Session, but can be used with any object that implements\n the Session.run() interface.\n\n Use with the \"with\" keyword to specify that Tensor.eval() and Operation.run()\n invocations within the scope of a block should be executed by a particular\n session.\n\n The default session applies to the current thread only, so it is always\n possible to inspect the call stack and determine the scope of a default\n session. If you create a new thread, and wish to use the default session\n in that thread, you must explicitly add a \"with ops.default_session(sess):\"\n block in that thread's function.\n\n Example:\n The following code examples are equivalent:\n\n # 1. Using the Session object directly:\n sess = ...\n c = tf.constant(5.0)\n sess.run(c)\n\n # 2. Using default_session():\n sess = ...\n with ops.default_session(sess):\n c = tf.constant(5.0)\n result = c.eval()\n\n # 3. Overriding default_session():\n sess = ...\n with ops.default_session(sess):\n c = tf.constant(5.0)\n with ops.default_session(...):\n c.eval(session=sess)\n\n Args:\n session: The session to be installed as the default session.\n\n Returns:\n A context manager for the default session.\n \"\"\"\n return _default_session_stack.get_controller(session)\n\n\n@tf_export(v1=[\"get_default_session\"])\ndef get_default_session():\n \"\"\"Returns the default session for the current thread.\n\n The returned `Session` will be the innermost session on which a\n `Session` or `Session.as_default()` context has been entered.\n\n NOTE: The default session is a property of the current thread. If you\n create a new thread, and wish to use the default session in that\n thread, you must explicitly add a `with sess.as_default():` in that\n thread's function.\n\n Returns:\n The default `Session` being used in the current thread.\n \"\"\"\n return _default_session_stack.get_default()\n\n\ndef _eval_using_default_session(tensors, feed_dict, graph, session=None):\n \"\"\"Uses the default session to evaluate one or more tensors.\n\n Args:\n tensors: A single Tensor, or a list of Tensor objects.\n feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,\n numpy ndarrays, TensorProtos, or strings.\n graph: The graph in which the tensors are defined.\n session: (Optional) A different session to use to evaluate \"tensors\".\n\n Returns:\n Either a single numpy ndarray if \"tensors\" is a single tensor; or a list\n of numpy ndarrays that each correspond to the respective element in\n \"tensors\".\n\n Raises:\n ValueError: If no default session is available; the default session\n does not have \"graph\" as its graph; or if \"session\" is specified,\n and it does not have \"graph\" as its graph.\n \"\"\"\n if session is None:\n session = get_default_session()\n if session is None:\n raise ValueError(\"Cannot evaluate tensor using `eval()`: No default \"\n \"session is registered. Use `with \"\n \"sess.as_default()` or pass an explicit session to \"\n \"`eval(session=sess)`\")\n if session.graph is not graph:\n raise ValueError(\"Cannot use the default session to evaluate tensor: \"\n \"the tensor's graph is different from the session's \"\n \"graph. Pass an explicit session to \"\n \"`eval(session=sess)`.\")\n else:\n if session.graph is not graph:\n raise ValueError(\"Cannot use the given session to evaluate tensor: \"\n \"the tensor's graph is different from the session's \"\n \"graph.\")\n return session.run(tensors, feed_dict)\n\n\ndef _run_using_default_session(operation, feed_dict, graph, session=None):\n \"\"\"Uses the default session to run \"operation\".\n\n Args:\n operation: The Operation to be run.\n feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,\n numpy ndarrays, TensorProtos, or strings.\n graph: The graph in which \"operation\" is defined.\n session: (Optional) A different session to use to run \"operation\".\n\n Raises:\n ValueError: If no default session is available; the default session\n does not have \"graph\" as its graph; or if \"session\" is specified,\n and it does not have \"graph\" as its graph.\n \"\"\"\n if session is None:\n session = get_default_session()\n if session is None:\n raise ValueError(\"Cannot execute operation using `run()`: No default \"\n \"session is registered. Use `with \"\n \"sess.as_default():` or pass an explicit session to \"\n \"`run(session=sess)`\")\n if session.graph is not graph:\n raise ValueError(\"Cannot use the default session to execute operation: \"\n \"the operation's graph is different from the \"\n \"session's graph. Pass an explicit session to \"\n \"run(session=sess).\")\n else:\n if session.graph is not graph:\n raise ValueError(\"Cannot use the given session to execute operation: \"\n \"the operation's graph is different from the session's \"\n \"graph.\")\n session.run(operation, feed_dict)\n\n\nclass _DefaultGraphStack(_DefaultStack): # pylint: disable=protected-access\n \"\"\"A thread-local stack of objects for providing an implicit default graph.\"\"\"\n\n def __init__(self):\n super(_DefaultGraphStack, self).__init__()\n self._global_default_graph = None\n\n def get_default(self):\n \"\"\"Override that returns a global default if the stack is empty.\"\"\"\n ret = super(_DefaultGraphStack, self).get_default()\n if ret is None:\n ret = self._GetGlobalDefaultGraph()\n return ret\n\n def _GetGlobalDefaultGraph(self):\n if self._global_default_graph is None:\n # TODO(mrry): Perhaps log that the default graph is being used, or set\n # provide some other feedback to prevent confusion when a mixture of\n # the global default graph and an explicit graph are combined in the\n # same process.\n self._global_default_graph = Graph()\n return self._global_default_graph\n\n def reset(self):\n super(_DefaultGraphStack, self).reset()\n self._global_default_graph = None\n\n @tf_contextlib.contextmanager\n def get_controller(self, default):\n context.context().context_switches.push(default.building_function,\n default.as_default,\n default._device_function_stack)\n try:\n with super(_DefaultGraphStack,\n self).get_controller(default) as g, context.graph_mode():\n yield g\n finally:\n # If an exception is raised here it may be hiding a related exception in\n # the try-block (just above).\n context.context().context_switches.pop()\n\n\n_default_graph_stack = _DefaultGraphStack()\n\n\n# Shared helper used in init_scope and executing_eagerly_outside_functions\n# to obtain the outermost context that is not building a function, and the\n# innermost non empty device stack.\ndef _get_outer_context_and_inner_device_stack():\n \"\"\"Get the outermost context not building a function.\"\"\"\n default_graph = get_default_graph()\n outer_context = None\n innermost_nonempty_device_stack = default_graph._device_function_stack # pylint: disable=protected-access\n\n if not _default_graph_stack.stack:\n # If the default graph stack is empty, then we cannot be building a\n # function. Install the global graph (which, in this case, is also the\n # default graph) as the outer context.\n if default_graph.building_function:\n raise RuntimeError(\"The global graph is building a function.\")\n outer_context = default_graph.as_default\n else:\n # Find a context that is not building a function.\n for stack_entry in reversed(context.context().context_switches.stack):\n if not innermost_nonempty_device_stack:\n innermost_nonempty_device_stack = stack_entry.device_stack\n if not stack_entry.is_building_function:\n outer_context = stack_entry.enter_context_fn\n break\n\n if outer_context is None:\n # As a last resort, obtain the global default graph; this graph doesn't\n # necessarily live on the graph stack (and hence it doesn't necessarily\n # live on the context stack), but it is stored in the graph stack's\n # encapsulating object.\n outer_context = _default_graph_stack._GetGlobalDefaultGraph().as_default # pylint: disable=protected-access\n\n if outer_context is None:\n # Sanity check; this shouldn't be triggered.\n raise RuntimeError(\"All graphs are building functions, and no \"\n \"eager context was previously active.\")\n\n return outer_context, innermost_nonempty_device_stack\n\n\n# pylint: disable=g-doc-return-or-yield,line-too-long\n@tf_export(\"init_scope\")\n@tf_contextlib.contextmanager\ndef init_scope():\n \"\"\"A context manager that lifts ops out of control-flow scopes and function-building graphs.\n\n There is often a need to lift variable initialization ops out of control-flow\n scopes, function-building graphs, and gradient tapes. Entering an\n `init_scope` is a mechanism for satisfying these desiderata. In particular,\n entering an `init_scope` has three effects:\n\n (1) All control dependencies are cleared the moment the scope is entered;\n this is equivalent to entering the context manager returned from\n `control_dependencies(None)`, which has the side-effect of exiting\n control-flow scopes like `tf.cond` and `tf.while_loop`.\n\n (2) All operations that are created while the scope is active are lifted\n into the lowest context on the `context_stack` that is not building a\n graph function. Here, a context is defined as either a graph or an eager\n context. Every context switch, i.e., every installation of a graph as\n the default graph and every switch into eager mode, is logged in a\n thread-local stack called `context_switches`; the log entry for a\n context switch is popped from the stack when the context is exited.\n Entering an `init_scope` is equivalent to crawling up\n `context_switches`, finding the first context that is not building a\n graph function, and entering it. A caveat is that if graph mode is\n enabled but the default graph stack is empty, then entering an\n `init_scope` will simply install a fresh graph as the default one.\n\n (3) The gradient tape is paused while the scope is active.\n\n When eager execution is enabled, code inside an init_scope block runs with\n eager execution enabled even when defining graph functions via\n tf.contrib.eager.defun. For example:\n\n ```python\n tf.compat.v1.enable_eager_execution()\n\n @tf.contrib.eager.defun\n def func():\n # A defun-decorated function constructs TensorFlow graphs,\n # it does not execute eagerly.\n assert not tf.executing_eagerly()\n with tf.init_scope():\n # Initialization runs with eager execution enabled\n assert tf.executing_eagerly()\n ```\n\n Raises:\n RuntimeError: if graph state is incompatible with this initialization.\n \"\"\"\n # pylint: enable=g-doc-return-or-yield,line-too-long\n\n if context.executing_eagerly():\n # Fastpath.\n with tape.stop_recording():\n yield\n else:\n # Retrieve the active name scope: entering an `init_scope` preserves\n # the name scope of the current context.\n scope = get_default_graph().get_name_scope()\n if scope and scope[-1] != \"/\":\n # Names that end with trailing slashes are treated by `name_scope` as\n # absolute.\n scope = scope + \"/\"\n\n outer_context, innermost_nonempty_device_stack = (\n _get_outer_context_and_inner_device_stack())\n\n outer_graph = None\n outer_device_stack = None\n try:\n with outer_context(), name_scope(scope), control_dependencies(\n None), tape.stop_recording():\n context_manager = NullContextmanager\n context_manager_input = None\n if not context.executing_eagerly():\n # The device stack is preserved when lifting into a graph. Eager\n # execution doesn't implement device stacks and in particular it\n # doesn't support device functions, so in general it's not possible\n # to do the same when lifting into the eager context.\n outer_graph = get_default_graph()\n outer_device_stack = outer_graph._device_function_stack # pylint: disable=protected-access\n outer_graph._device_function_stack = innermost_nonempty_device_stack # pylint: disable=protected-access\n elif innermost_nonempty_device_stack is not None:\n for device_spec in innermost_nonempty_device_stack.peek_objs():\n if device_spec.function is None:\n break\n if device_spec.raw_string:\n context_manager = context.device\n context_manager_input = device_spec.raw_string\n break\n # It is currently not possible to have a device function in V2,\n # but in V1 we are unable to apply device functions in eager mode.\n # This means that we will silently skip some of the entries on the\n # device stack in V1 + eager mode.\n\n with context_manager(context_manager_input):\n yield\n finally:\n # If an exception is raised here it may be hiding a related exception in\n # try-block (just above).\n if outer_graph is not None:\n outer_graph._device_function_stack = outer_device_stack # pylint: disable=protected-access\n\n\ndef executing_eagerly_outside_functions():\n \"\"\"Returns True if executing eagerly, even if inside a graph function.\"\"\"\n if context.executing_eagerly():\n return True\n else:\n outer_context, _ = _get_outer_context_and_inner_device_stack()\n with outer_context():\n return context.executing_eagerly()\n\n\ndef inside_function():\n return get_default_graph().building_function\n\n\n@tf_export(v1=[\"enable_eager_execution\"])\ndef enable_eager_execution(config=None, device_policy=None,\n execution_mode=None):\n \"\"\"Enables eager execution for the lifetime of this program.\n\n Eager execution provides an imperative interface to TensorFlow. With eager\n execution enabled, TensorFlow functions execute operations immediately (as\n opposed to adding to a graph to be executed later in a `tf.compat.v1.Session`)\n and\n return concrete values (as opposed to symbolic references to a node in a\n computational graph).\n\n For example:\n\n ```python\n tf.compat.v1.enable_eager_execution()\n\n # After eager execution is enabled, operations are executed as they are\n # defined and Tensor objects hold concrete values, which can be accessed as\n # numpy.ndarray`s through the numpy() method.\n assert tf.multiply(6, 7).numpy() == 42\n ```\n\n Eager execution cannot be enabled after TensorFlow APIs have been used to\n create or execute graphs. It is typically recommended to invoke this function\n at program startup and not in a library (as most libraries should be usable\n both with and without eager execution).\n\n Args:\n config: (Optional.) A `tf.compat.v1.ConfigProto` to use to configure the\n environment in which operations are executed. Note that\n `tf.compat.v1.ConfigProto` is also used to configure graph execution (via\n `tf.compat.v1.Session`) and many options within `tf.compat.v1.ConfigProto`\n are not implemented (or are irrelevant) when eager execution is enabled.\n device_policy: (Optional.) Policy controlling how operations requiring\n inputs on a specific device (e.g., a GPU 0) handle inputs on a different\n device (e.g. GPU 1 or CPU). When set to None, an appropriate value will\n be picked automatically. The value picked may change between TensorFlow\n releases.\n Valid values:\n - tf.contrib.eager.DEVICE_PLACEMENT_EXPLICIT: raises an error if the\n placement is not correct.\n - tf.contrib.eager.DEVICE_PLACEMENT_WARN: copies the tensors which are not\n on the right device but logs a warning.\n - tf.contrib.eager.DEVICE_PLACEMENT_SILENT: silently copies the tensors.\n Note that this may hide performance problems as there is no notification\n provided when operations are blocked on the tensor being copied between\n devices.\n - tf.contrib.eager.DEVICE_PLACEMENT_SILENT_FOR_INT32: silently copies\n int32 tensors, raising errors on the other ones.\n execution_mode: (Optional.) Policy controlling how operations dispatched are\n actually executed. When set to None, an appropriate value will be picked\n automatically. The value picked may change between TensorFlow releases.\n Valid values:\n - tf.contrib.eager.SYNC: executes each operation synchronously.\n - tf.contrib.eager.ASYNC: executes each operation asynchronously. These\n operations may return \"non-ready\" handles.\n\n Raises:\n ValueError: If eager execution is enabled after creating/executing a\n TensorFlow graph, or if options provided conflict with a previous call\n to this function.\n \"\"\"\n _api_usage_gauge.get_cell().set(True)\n if context.default_execution_mode != context.EAGER_MODE:\n return enable_eager_execution_internal(\n config=config,\n device_policy=device_policy,\n execution_mode=execution_mode,\n server_def=None)\n\n\n@tf_export(v1=[\"disable_eager_execution\"])\ndef disable_eager_execution():\n \"\"\"Disables eager execution.\n\n This function can only be called before any Graphs, Ops, or Tensors have been\n created. It can be used at the beginning of the program for complex migration\n projects from TensorFlow 1.x to 2.x.\n \"\"\"\n _api_usage_gauge.get_cell().set(False)\n context.default_execution_mode = context.GRAPH_MODE\n c = context.context_safe()\n if c is not None:\n c._thread_local_data.is_eager = False # pylint: disable=protected-access\n\n\ndef enable_eager_execution_internal(config=None,\n device_policy=None,\n execution_mode=None,\n server_def=None):\n \"\"\"Enables eager execution for the lifetime of this program.\n\n Most of the doc string for enable_eager_execution is relevant here as well.\n\n Args:\n config: See enable_eager_execution doc string\n device_policy: See enable_eager_execution doc string\n execution_mode: See enable_eager_execution doc string\n server_def: (Optional.) A tensorflow::ServerDef proto. Enables execution on\n remote devices. GrpcServers need to be started by creating an identical\n server_def to this, and setting the appropriate task_indexes, so that the\n servers can communicate. It will then be possible to execute operations on\n remote devices.\n\n Raises:\n ValueError\n\n \"\"\"\n if config is not None and not isinstance(config, config_pb2.ConfigProto):\n raise TypeError(\"config must be a tf.ConfigProto, but got %s\" %\n type(config))\n if device_policy not in (None, context.DEVICE_PLACEMENT_EXPLICIT,\n context.DEVICE_PLACEMENT_WARN,\n context.DEVICE_PLACEMENT_SILENT,\n context.DEVICE_PLACEMENT_SILENT_FOR_INT32):\n raise ValueError(\n \"device_policy must be one of None, tf.contrib.eager.DEVICE_PLACEMENT_*\"\n )\n if execution_mode not in (None, context.SYNC, context.ASYNC):\n raise ValueError(\n \"execution_mode must be one of None, tf.contrib.eager.SYNC, \"\n \"tf.contrib.eager.ASYNC\")\n if context.default_execution_mode == context.GRAPH_MODE:\n graph_mode_has_been_used = (\n _default_graph_stack._global_default_graph is not None) # pylint: disable=protected-access\n if graph_mode_has_been_used:\n raise ValueError(\n \"tf.enable_eager_execution must be called at program startup.\")\n context.default_execution_mode = context.EAGER_MODE\n # pylint: disable=protected-access\n with context._context_lock:\n if context._context is None:\n context._set_context_locked(context.Context(\n config=config,\n device_policy=device_policy,\n execution_mode=execution_mode,\n server_def=server_def))\n elif ((config is not None and config is not context._context._config) or\n (device_policy is not None and\n device_policy is not context._context._device_policy) or\n (execution_mode is not None and\n execution_mode is not context._context._execution_mode)):\n raise ValueError(\n \"Trying to change the options of an active eager\"\n \" execution. Context config: %s, specified config:\"\n \" %s. Context device policy: %s, specified device\"\n \" policy: %s. Context execution mode: %s, \"\n \" specified execution mode %s.\" %\n (context._context._config, config, context._context._device_policy,\n device_policy, context._context._execution_mode, execution_mode))\n else:\n # We already created everything, so update the thread local data.\n context._context._thread_local_data.is_eager = True\n\n # Monkey patch to get rid of an unnecessary conditional since the context is\n # now initialized.\n context.context = context.context_safe\n\n\ndef eager_run(main=None, argv=None):\n \"\"\"Runs the program with an optional main function and argv list.\n\n The program will run with eager execution enabled.\n\n Example:\n ```python\n import tensorflow as tf\n # Import subject to future changes:\n from tensorflow.contrib.eager.python import tfe\n\n def main(_):\n u = tf.constant(6.0)\n v = tf.constant(7.0)\n print(u * v)\n\n if __name__ == \"__main__\":\n tfe.run()\n ```\n\n Args:\n main: the main function to run.\n argv: the arguments to pass to it.\n \"\"\"\n enable_eager_execution()\n app.run(main, argv)\n\n\n@tf_export(v1=[\"reset_default_graph\"])\ndef reset_default_graph():\n \"\"\"Clears the default graph stack and resets the global default graph.\n\n NOTE: The default graph is a property of the current thread. This\n function applies only to the current thread. Calling this function while\n a `tf.compat.v1.Session` or `tf.compat.v1.InteractiveSession` is active will\n result in undefined\n behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects\n after calling this function will result in undefined behavior.\n Raises:\n AssertionError: If this function is called within a nested graph.\n \"\"\"\n if not _default_graph_stack.is_cleared():\n raise AssertionError(\"Do not use tf.reset_default_graph() to clear \"\n \"nested graphs. If you need a cleared graph, \"\n \"exit the nesting and create a new graph.\")\n _default_graph_stack.reset()\n\n\n@tf_export(v1=[\"get_default_graph\"])\ndef get_default_graph():\n \"\"\"Returns the default graph for the current thread.\n\n The returned graph will be the innermost graph on which a\n `Graph.as_default()` context has been entered, or a global default\n graph if none has been explicitly created.\n\n NOTE: The default graph is a property of the current thread. If you\n create a new thread, and wish to use the default graph in that\n thread, you must explicitly add a `with g.as_default():` in that\n thread's function.\n\n Returns:\n The default `Graph` being used in the current thread.\n \"\"\"\n return _default_graph_stack.get_default()\n\n\ndef has_default_graph():\n \"\"\"Returns True if there is a default graph.\"\"\"\n return len(_default_graph_stack.stack) >= 1\n\n\ndef get_name_scope():\n \"\"\"Returns the current name scope in the default_graph.\n\n For example:\n\n ```python\n with tf.name_scope('scope1'):\n with tf.name_scope('scope2'):\n print(tf.get_name_scope())\n ```\n would print the string `scope1/scope2`.\n\n Returns:\n A string representing the current name scope.\n \"\"\"\n if context.executing_eagerly():\n return context.context().scope_name.rstrip(\"/\")\n return get_default_graph().get_name_scope()\n\n\ndef _assert_same_graph(original_item, item):\n \"\"\"Fail if the 2 items are from different graphs.\n\n Args:\n original_item: Original item to check against.\n item: Item to check.\n\n Raises:\n ValueError: if graphs do not match.\n \"\"\"\n if original_item.graph is not item.graph:\n raise ValueError(\"%s must be from the same graph as %s.\" %\n (item, original_item))\n\n\ndef _get_graph_from_inputs(op_input_list, graph=None):\n \"\"\"Returns the appropriate graph to use for the given inputs.\n\n This library method provides a consistent algorithm for choosing the graph\n in which an Operation should be constructed:\n\n 1. If the default graph is being used to construct a function, we\n use the default graph.\n 2. If the \"graph\" is specified explicitly, we validate that all of the inputs\n in \"op_input_list\" are compatible with that graph.\n 3. Otherwise, we attempt to select a graph from the first Operation-\n or Tensor-valued input in \"op_input_list\", and validate that all other\n such inputs are in the same graph.\n 4. If the graph was not specified and it could not be inferred from\n \"op_input_list\", we attempt to use the default graph.\n\n Args:\n op_input_list: A list of inputs to an operation, which may include `Tensor`,\n `Operation`, and other objects that may be converted to a graph element.\n graph: (Optional) The explicit graph to use.\n\n Raises:\n TypeError: If op_input_list is not a list or tuple, or if graph is not a\n Graph.\n ValueError: If a graph is explicitly passed and not all inputs are from it,\n or if the inputs are from multiple graphs, or we could not find a graph\n and there was no default graph.\n\n Returns:\n The appropriate graph to use for the given inputs.\n\n \"\"\"\n current_default_graph = get_default_graph()\n if current_default_graph.building_function:\n return current_default_graph\n\n op_input_list = tuple(op_input_list) # Handle generators correctly\n if graph and not isinstance(graph, Graph):\n raise TypeError(\"Input graph needs to be a Graph: %s\" % graph)\n\n # 1. We validate that all of the inputs are from the same graph. This is\n # either the supplied graph parameter, or the first one selected from one\n # the graph-element-valued inputs. In the latter case, we hold onto\n # that input in original_graph_element so we can provide a more\n # informative error if a mismatch is found.\n original_graph_element = None\n for op_input in op_input_list:\n # Determine if this is a valid graph_element.\n # TODO(josh11b): Note that we exclude subclasses of Tensor. Need to clean this\n # up.\n graph_element = None\n if (isinstance(op_input, (Operation, _TensorLike)) and\n ((not isinstance(op_input, Tensor)) or type(op_input) == Tensor)): # pylint: disable=unidiomatic-typecheck\n graph_element = op_input\n else:\n graph_element = _as_graph_element(op_input)\n\n if graph_element is not None:\n if not graph:\n original_graph_element = graph_element\n graph = graph_element.graph\n elif original_graph_element is not None:\n _assert_same_graph(original_graph_element, graph_element)\n elif graph_element.graph is not graph:\n raise ValueError(\"%s is not from the passed-in graph.\" % graph_element)\n\n # 2. If all else fails, we use the default graph, which is always there.\n return graph or current_default_graph\n\n\n@tf_export(v1=[\"GraphKeys\"])\nclass GraphKeys(object):\n \"\"\"Standard names to use for graph collections.\n\n The standard library uses various well-known names to collect and\n retrieve values associated with a graph. For example, the\n `tf.Optimizer` subclasses default to optimizing the variables\n collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is\n specified, but it is also possible to pass an explicit list of\n variables.\n\n The following standard keys are defined:\n\n * `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared\n across distributed environment (model variables are subset of these). See\n `tf.compat.v1.global_variables`\n for more details.\n Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`,\n and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.\n * `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each\n machine. Usually used for temporarily variables, like counters.\n Note: use `tf.contrib.framework.local_variable` to add to this collection.\n * `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the\n model for inference (feed forward). Note: use\n `tf.contrib.framework.model_variable` to add to this collection.\n * `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will\n be trained by an optimizer. See\n `tf.compat.v1.trainable_variables`\n for more details.\n * `SUMMARIES`: the summary `Tensor` objects that have been created in the\n graph. See\n `tf.compat.v1.summary.merge_all`\n for more details.\n * `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to\n produce input for a computation. See\n `tf.compat.v1.train.start_queue_runners`\n for more details.\n * `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also\n keep moving averages. See\n `tf.compat.v1.moving_average_variables`\n for more details.\n * `REGULARIZATION_LOSSES`: regularization losses collected during graph\n construction.\n\n The following standard keys are _defined_, but their collections are **not**\n automatically populated as many of the others are:\n\n * `WEIGHTS`\n * `BIASES`\n * `ACTIVATIONS`\n \"\"\"\n\n # Key to collect Variable objects that are global (shared across machines).\n # Default collection for all variables, except local ones.\n GLOBAL_VARIABLES = \"variables\"\n # Key to collect local variables that are local to the machine and are not\n # saved/restored.\n LOCAL_VARIABLES = \"local_variables\"\n # Key to collect local variables which are used to accumulate interal state\n # to be used in tf.metrics.*.\n METRIC_VARIABLES = \"metric_variables\"\n # Key to collect model variables defined by layers.\n MODEL_VARIABLES = \"model_variables\"\n # Key to collect Variable objects that will be trained by the\n # optimizers.\n TRAINABLE_VARIABLES = \"trainable_variables\"\n # Key to collect summaries.\n SUMMARIES = \"summaries\"\n # Key to collect QueueRunners.\n QUEUE_RUNNERS = \"queue_runners\"\n # Key to collect table initializers.\n TABLE_INITIALIZERS = \"table_initializer\"\n # Key to collect asset filepaths. An asset represents an external resource\n # like a vocabulary file.\n ASSET_FILEPATHS = \"asset_filepaths\"\n # Key to collect Variable objects that keep moving averages.\n MOVING_AVERAGE_VARIABLES = \"moving_average_variables\"\n # Key to collect regularization losses at graph construction.\n REGULARIZATION_LOSSES = \"regularization_losses\"\n # Key to collect concatenated sharded variables.\n CONCATENATED_VARIABLES = \"concatenated_variables\"\n # Key to collect savers.\n SAVERS = \"savers\"\n # Key to collect weights\n WEIGHTS = \"weights\"\n # Key to collect biases\n BIASES = \"biases\"\n # Key to collect activations\n ACTIVATIONS = \"activations\"\n # Key to collect update_ops\n UPDATE_OPS = \"update_ops\"\n # Key to collect losses\n LOSSES = \"losses\"\n # Key to collect BaseSaverBuilder.SaveableObject instances for checkpointing.\n SAVEABLE_OBJECTS = \"saveable_objects\"\n # Key to collect all shared resources used by the graph which need to be\n # initialized once per cluster.\n RESOURCES = \"resources\"\n # Key to collect all shared resources used in this graph which need to be\n # initialized once per session.\n LOCAL_RESOURCES = \"local_resources\"\n # Trainable resource-style variables.\n TRAINABLE_RESOURCE_VARIABLES = \"trainable_resource_variables\"\n\n # Key to indicate various ops.\n INIT_OP = \"init_op\"\n LOCAL_INIT_OP = \"local_init_op\"\n READY_OP = \"ready_op\"\n READY_FOR_LOCAL_INIT_OP = \"ready_for_local_init_op\"\n SUMMARY_OP = \"summary_op\"\n GLOBAL_STEP = \"global_step\"\n\n # Used to count the number of evaluations performed during a single evaluation\n # run.\n EVAL_STEP = \"eval_step\"\n TRAIN_OP = \"train_op\"\n\n # Key for control flow context.\n COND_CONTEXT = \"cond_context\"\n WHILE_CONTEXT = \"while_context\"\n\n # Used to store v2 summary names.\n _SUMMARY_COLLECTION = \"_SUMMARY_V2\"\n\n # List of all collections that keep track of variables.\n _VARIABLE_COLLECTIONS = [\n GLOBAL_VARIABLES,\n LOCAL_VARIABLES,\n METRIC_VARIABLES,\n MODEL_VARIABLES,\n TRAINABLE_VARIABLES,\n MOVING_AVERAGE_VARIABLES,\n CONCATENATED_VARIABLES,\n TRAINABLE_RESOURCE_VARIABLES,\n ]\n\n # Key for streaming model ports.\n # NOTE(yuanbyu): internal and experimental.\n _STREAMING_MODEL_PORTS = \"streaming_model_ports\"\n\n @decorator_utils.classproperty\n @deprecation.deprecated(None, \"Use `tf.GraphKeys.GLOBAL_VARIABLES` instead.\")\n def VARIABLES(cls): # pylint: disable=no-self-argument\n return cls.GLOBAL_VARIABLES\n\n\ndef dismantle_graph(graph):\n \"\"\"Cleans up reference cycles from a `Graph`.\n\n Helpful for making sure the garbage collector doesn't need to run after a\n temporary `Graph` is no longer needed.\n\n Args:\n graph: A `Graph` object to destroy. Neither it nor any of its ops are usable\n after this function runs.\n \"\"\"\n memory.dismantle_ordered_dict(graph._functions) # pylint: disable=protected-access\n\n # Now clean up Operation<->Graph reference cycles by clearing all of the\n # attributes for the Graph and its ops.\n graph_operations = graph.get_operations()\n for op in graph_operations:\n op.__dict__ = {}\n graph.__dict__ = {}\n\n\n@tf_export(v1=[\"add_to_collection\"])\ndef add_to_collection(name, value):\n \"\"\"Wrapper for `Graph.add_to_collection()` using the default graph.\n\n See `tf.Graph.add_to_collection`\n for more details.\n\n Args:\n name: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n value: The value to add to the collection. @compatibility(eager)\n Collections are only supported in eager when variables are created inside\n an EagerVariableStore (e.g. as part of a layer or template).\n @end_compatibility\n \"\"\"\n get_default_graph().add_to_collection(name, value)\n\n\n@tf_export(v1=[\"add_to_collections\"])\ndef add_to_collections(names, value):\n \"\"\"Wrapper for `Graph.add_to_collections()` using the default graph.\n\n See `tf.Graph.add_to_collections`\n for more details.\n\n Args:\n names: The key for the collections. The `GraphKeys` class contains many\n standard names for collections.\n value: The value to add to the collections. @compatibility(eager)\n Collections are only supported in eager when variables are created inside\n an EagerVariableStore (e.g. as part of a layer or template).\n @end_compatibility\n \"\"\"\n get_default_graph().add_to_collections(names, value)\n\n\n@tf_export(v1=[\"get_collection_ref\"])\ndef get_collection_ref(key):\n \"\"\"Wrapper for `Graph.get_collection_ref()` using the default graph.\n\n See `tf.Graph.get_collection_ref`\n for more details.\n\n Args:\n key: The key for the collection. For example, the `GraphKeys` class contains\n many standard names for collections.\n\n Returns:\n The list of values in the collection with the given `name`, or an empty\n list if no value has been added to that collection. Note that this returns\n the collection list itself, which can be modified in place to change the\n collection.\n\n @compatibility(eager)\n Collections are not supported when eager execution is enabled.\n @end_compatibility\n \"\"\"\n return get_default_graph().get_collection_ref(key)\n\n\n@tf_export(v1=[\"get_collection\"])\ndef get_collection(key, scope=None):\n \"\"\"Wrapper for `Graph.get_collection()` using the default graph.\n\n See `tf.Graph.get_collection`\n for more details.\n\n Args:\n key: The key for the collection. For example, the `GraphKeys` class contains\n many standard names for collections.\n scope: (Optional.) If supplied, the resulting list is filtered to include\n only items whose `name` attribute matches using `re.match`. Items without\n a `name` attribute are never returned if a scope is supplied and the\n choice or `re.match` means that a `scope` without special tokens filters\n by prefix.\n\n Returns:\n The list of values in the collection with the given `name`, or\n an empty list if no value has been added to that collection. The\n list contains the values in the order under which they were\n collected.\n\n @compatibility(eager)\n Collections are not supported when eager execution is enabled.\n @end_compatibility\n \"\"\"\n return get_default_graph().get_collection(key, scope)\n\n\ndef get_all_collection_keys():\n \"\"\"Returns a list of collections used in the default graph.\"\"\"\n return get_default_graph().get_all_collection_keys()\n\n\ndef name_scope(name, default_name=None, values=None):\n \"\"\"Internal-only entry point for `name_scope*`.\n\n Internal ops do not use the public API and instead rely on\n `ops.name_scope` regardless of the execution mode. This function\n dispatches to the correct `name_scope*` implementation based on\n the arguments provided and the current mode. Specifically,\n\n * if `values` contains a graph tensor `Graph.name_scope` is used;\n * `name_scope_v1` is used in graph mode;\n * `name_scope_v2` -- in eager mode.\n\n Args:\n name: The name argument that is passed to the op function.\n default_name: The default name to use if the `name` argument is `None`.\n values: The list of `Tensor` arguments that are passed to the op function.\n\n Returns:\n `name_scope*` context manager.\n \"\"\"\n ctx = context.context()\n in_eager_mode = ctx.executing_eagerly()\n if not in_eager_mode:\n return internal_name_scope_v1(name, default_name, values)\n\n name = default_name if name is None else name\n if values:\n # The presence of a graph tensor in `values` overrides the context.\n # TODO(slebedev): this is Keras-specific and should be removed.\n # pylint: disable=unidiomatic-typecheck\n graph_value = next((value for value in values if type(value) == Tensor),\n None)\n # pylint: enable=unidiomatic-typecheck\n if graph_value is not None:\n return graph_value.graph.name_scope(name)\n return name_scope_v2(name or \"\")\n\n\nclass internal_name_scope_v1(object): # pylint: disable=invalid-name\n \"\"\"Graph-only version of `name_scope_v1`.\"\"\"\n\n @property\n def name(self):\n return self._name\n\n def __init__(self, name, default_name=None, values=None):\n \"\"\"Initialize the context manager.\n\n Args:\n name: The name argument that is passed to the op function.\n default_name: The default name to use if the `name` argument is `None`.\n values: The list of `Tensor` arguments that are passed to the op function.\n\n Raises:\n TypeError: if `default_name` is passed in but not a string.\n \"\"\"\n if not (default_name is None or isinstance(default_name, six.string_types)):\n raise TypeError(\n \"`default_name` type (%s) is not a string type. You likely meant to \"\n \"pass this into the `values` kwarg.\" % type(default_name))\n self._name = default_name if name is None else name\n self._default_name = default_name\n self._values = values\n\n def __enter__(self):\n \"\"\"Start the scope block.\n\n Returns:\n The scope name.\n\n Raises:\n ValueError: if neither `name` nor `default_name` is provided\n but `values` are.\n \"\"\"\n if self._name is None and self._values is not None:\n # We only raise an error if values is not None (provided) because\n # currently tf.name_scope(None) (values=None then) is sometimes used as\n # an idiom to reset to top scope.\n raise ValueError(\n \"At least one of name (%s) and default_name (%s) must be provided.\"\n % (self._name, self._default_name))\n\n g = get_default_graph()\n if self._values and not g.building_function:\n # Specialize based on the knowledge that `_get_graph_from_inputs()`\n # ignores `inputs` when building a function.\n g_from_inputs = _get_graph_from_inputs(self._values)\n if g_from_inputs is not g:\n g = g_from_inputs\n self._g_manager = g.as_default()\n self._g_manager.__enter__()\n else:\n self._g_manager = None\n else:\n self._g_manager = None\n\n try:\n self._name_scope = g.name_scope(self._name)\n return self._name_scope.__enter__()\n except:\n if self._g_manager is not None:\n self._g_manager.__exit__(*sys.exc_info())\n raise\n\n def __exit__(self, *exc_info):\n self._name_scope.__exit__(*exc_info)\n if self._g_manager is not None:\n self._g_manager.__exit__(*exc_info)\n\n\n# Named like a function for backwards compatibility with the\n# @tf_contextlib.contextmanager version, which was switched to a class to avoid\n# some object creation overhead.\n@tf_export(v1=[\"name_scope\"])\nclass name_scope_v1(object): # pylint: disable=invalid-name\n \"\"\"A context manager for use when defining a Python op.\n\n This context manager validates that the given `values` are from the\n same graph, makes that graph the default graph, and pushes a\n name scope in that graph (see\n `tf.Graph.name_scope`\n for more details on that).\n\n For example, to define a new Python op called `my_op`:\n\n ```python\n def my_op(a, b, c, name=None):\n with tf.name_scope(name, \"MyOp\", [a, b, c]) as scope:\n a = tf.convert_to_tensor(a, name=\"a\")\n b = tf.convert_to_tensor(b, name=\"b\")\n c = tf.convert_to_tensor(c, name=\"c\")\n # Define some computation that uses `a`, `b`, and `c`.\n return foo_op(..., name=scope)\n ```\n \"\"\"\n\n @property\n def name(self):\n return self._name\n\n def __init__(self, name, default_name=None, values=None):\n \"\"\"Initialize the context manager.\n\n Args:\n name: The name argument that is passed to the op function.\n default_name: The default name to use if the `name` argument is `None`.\n values: The list of `Tensor` arguments that are passed to the op function.\n\n Raises:\n TypeError: if `default_name` is passed in but not a string.\n \"\"\"\n self._name_scope = name_scope(name, default_name, values)\n self._name = default_name if name is None else name\n\n def __enter__(self):\n return self._name_scope.__enter__()\n\n def __exit__(self, *exc_info):\n return self._name_scope.__exit__(*exc_info)\n\n\ndef enter_eager_name_scope(ctx, name):\n \"\"\"Updates the eager context to enter the given name scope.\"\"\"\n old_name = ctx.scope_name\n if not name:\n scope_name = \"\"\n else:\n if name.endswith(\"/\"):\n # A trailing slash breaks out of nested name scopes, indicating a\n # fully specified scope name, for compatibility with Graph.name_scope.\n scope_name = name\n else:\n scope_name = name + \"/\"\n if old_name:\n scope_name = old_name + scope_name\n ctx.scope_name = scope_name\n return scope_name, old_name\n\n\n@tf_export(\"name_scope\", v1=[])\nclass name_scope_v2(object):\n \"\"\"A context manager for use when defining a Python op.\n\n This context manager pushes a name scope, which will make the name of all\n operations added within it have a prefix.\n\n For example, to define a new Python op called `my_op`:\n\n ```python\n def my_op(a, b, c, name=None):\n with tf.name_scope(\"MyOp\") as scope:\n a = tf.convert_to_tensor(a, name=\"a\")\n b = tf.convert_to_tensor(b, name=\"b\")\n c = tf.convert_to_tensor(c, name=\"c\")\n # Define some computation that uses `a`, `b`, and `c`.\n return foo_op(..., name=scope)\n ```\n\n When executed, the Tensors `a`, `b`, `c`, will have names `MyOp/a`, `MyOp/b`,\n and `MyOp/c`.\n\n If the scope name already exists, the name will be made unique by appending\n `_n`. For example, calling `my_op` the second time will generate `MyOp_1/a`,\n etc.\n \"\"\"\n\n def __init__(self, name):\n \"\"\"Initialize the context manager.\n\n Args:\n name: The prefix to use on all names created within the name scope.\n\n Raises:\n ValueError: If name is None, or not a string.\n \"\"\"\n if name is None or not isinstance(name, six.string_types):\n raise ValueError(\"name for name_scope must be a string.\")\n self._name = name\n self._exit_fns = []\n\n @property\n def name(self):\n return self._name\n\n def __enter__(self):\n \"\"\"Start the scope block.\n\n Returns:\n The scope name.\n\n Raises:\n ValueError: if neither `name` nor `default_name` is provided\n but `values` are.\n \"\"\"\n ctx = context.context()\n if ctx.executing_eagerly():\n scope_name, old_scope_name = enter_eager_name_scope(ctx, self._name)\n self._exit_fns.append(\n lambda *a: setattr(ctx, \"scope_name\", old_scope_name))\n else:\n scope = get_default_graph().name_scope(self._name)\n scope_name = scope.__enter__()\n self._exit_fns.append(scope.__exit__)\n return scope_name\n\n def __exit__(self, type_arg, value_arg, traceback_arg):\n exit_fn = self._exit_fns.pop()\n exit_fn(type_arg, value_arg, traceback_arg)\n return False # False values do not suppress exceptions\n\n\ndef strip_name_scope(name, export_scope):\n \"\"\"Removes name scope from a name.\n\n Args:\n name: A `string` name.\n export_scope: Optional `string`. Name scope to remove.\n\n Returns:\n Name with name scope removed, or the original name if export_scope\n is None.\n \"\"\"\n if export_scope:\n if export_scope[-1] == \"/\":\n export_scope = export_scope[:-1]\n\n try:\n # Strips export_scope/, export_scope///,\n # ^export_scope/, loc:@export_scope/.\n str_to_replace = r\"([\\^]|loc:@|^)\" + export_scope + r\"[\\/]+(.*)\"\n return re.sub(str_to_replace, r\"\\1\\2\", compat.as_str(name), count=1)\n except TypeError as e:\n # If the name is not of a type we can process, simply return it.\n logging.warning(e)\n return name\n else:\n return name\n\n\ndef prepend_name_scope(name, import_scope):\n \"\"\"Prepends name scope to a name.\n\n Args:\n name: A `string` name.\n import_scope: Optional `string`. Name scope to add.\n\n Returns:\n Name with name scope added, or the original name if import_scope\n is None.\n \"\"\"\n if import_scope:\n if import_scope[-1] == \"/\":\n import_scope = import_scope[:-1]\n\n try:\n str_to_replace = r\"([\\^]|loc:@|^)(.*)\"\n return re.sub(str_to_replace, r\"\\1\" + import_scope + r\"/\\2\",\n compat.as_str(name))\n except TypeError as e:\n # If the name is not of a type we can process, simply return it.\n logging.warning(e)\n return name\n else:\n return name\n\n\n# pylint: disable=g-doc-return-or-yield\n# pylint: disable=not-context-manager\n@tf_export(v1=[\"op_scope\"])\n@tf_contextlib.contextmanager\ndef op_scope(values, name, default_name=None):\n \"\"\"DEPRECATED. Same as name_scope above, just different argument order.\"\"\"\n logging.warn(\"tf.op_scope(values, name, default_name) is deprecated,\"\n \" use tf.name_scope(name, default_name, values)\")\n with name_scope(name, default_name=default_name, values=values) as scope:\n yield scope\n\n\n_proto_function_registry = registry.Registry(\"proto functions\")\n\n\ndef register_proto_function(collection_name,\n proto_type=None,\n to_proto=None,\n from_proto=None):\n \"\"\"Registers `to_proto` and `from_proto` functions for collection_name.\n\n `to_proto` function converts a Python object to the corresponding protocol\n buffer, and returns the protocol buffer.\n\n `from_proto` function converts protocol buffer into a Python object, and\n returns the object..\n\n Args:\n collection_name: Name of the collection.\n proto_type: Protobuf type, such as `saver_pb2.SaverDef`,\n `variable_pb2.VariableDef`, `queue_runner_pb2.QueueRunnerDef`..\n to_proto: Function that implements Python object to protobuf conversion.\n from_proto: Function that implements protobuf to Python object conversion.\n \"\"\"\n if to_proto and not callable(to_proto):\n raise TypeError(\"to_proto must be callable.\")\n if from_proto and not callable(from_proto):\n raise TypeError(\"from_proto must be callable.\")\n\n _proto_function_registry.register((proto_type, to_proto, from_proto),\n collection_name)\n\n\ndef get_collection_proto_type(collection_name):\n \"\"\"Returns the proto_type for collection_name.\"\"\"\n try:\n return _proto_function_registry.lookup(collection_name)[0]\n except LookupError:\n return None\n\n\ndef get_to_proto_function(collection_name):\n \"\"\"Returns the to_proto function for collection_name.\"\"\"\n try:\n return _proto_function_registry.lookup(collection_name)[1]\n except LookupError:\n return None\n\n\ndef get_from_proto_function(collection_name):\n \"\"\"Returns the from_proto function for collection_name.\"\"\"\n try:\n return _proto_function_registry.lookup(collection_name)[2]\n except LookupError:\n return None\n\n\ndef _operation_conversion_error(op, dtype=None, name=None, as_ref=False):\n \"\"\"Produce a nice error if someone converts an Operation to a Tensor.\"\"\"\n raise TypeError((\"Can't convert Operation '%s' to Tensor \"\n \"(target dtype=%r, name=%r, as_ref=%r)\") %\n (op.name, dtype, name, as_ref))\n\n\ndef _op_to_colocate_with(v, graph):\n \"\"\"Operation object corresponding to v to use for colocation constraints.\"\"\"\n if v is None:\n return None\n if isinstance(v, Operation):\n return v\n # We always want to colocate with the reference op.\n # When 'v' is a ResourceVariable, the reference op is the handle creating op.\n #\n # What this should be is:\n # if isinstance(v, ResourceVariable):\n # return v.handle.op\n # However, that would require a circular import dependency.\n # As of October 2018, there were attempts underway to remove\n # colocation constraints altogether. Assuming that will\n # happen soon, perhaps this hack to work around the circular\n # import dependency is acceptable.\n if hasattr(v, \"handle\") and isinstance(v.handle, Tensor):\n if graph.building_function:\n return graph.capture(v.handle).op\n else:\n return v.handle.op\n return internal_convert_to_tensor_or_indexed_slices(v, as_ref=True).op\n\n\ndef _is_keras_symbolic_tensor(x):\n return hasattr(x, \"graph\") and getattr(x.graph, \"name\", None) == \"keras_graph\"\n\n\ntensor_conversion_registry.register_tensor_conversion_function(\n Operation, _operation_conversion_error)\n\n\n# These symbols were originally defined in this module; import them for\n# backwards compatibility until all references have been updated to access\n# them from the indexed_slices.py module.\nIndexedSlices = indexed_slices.IndexedSlices\nIndexedSlicesValue = indexed_slices.IndexedSlicesValue\nconvert_to_tensor_or_indexed_slices = \\\n indexed_slices.convert_to_tensor_or_indexed_slices\nconvert_n_to_tensor_or_indexed_slices = \\\n indexed_slices.convert_n_to_tensor_or_indexed_slices\ninternal_convert_to_tensor_or_indexed_slices = \\\n indexed_slices.internal_convert_to_tensor_or_indexed_slices\ninternal_convert_n_to_tensor_or_indexed_slices = \\\n indexed_slices.internal_convert_n_to_tensor_or_indexed_slices\nregister_tensor_conversion_function = \\\n tensor_conversion_registry.register_tensor_conversion_function\n\n\n# Helper functions for op wrapper modules generated by `python_op_gen`.\n\n\ndef to_raw_op(f):\n \"\"\"Make a given op wrapper function `f` raw.\n\n Raw op wrappers are not included in the docs, and can only be called\n with keyword arguments.\n\n Args:\n f: An op wrapper function to make raw.\n\n Returns:\n Raw `f`.\n \"\"\"\n # Copy `f` to get a new `__dict__`, otherwise `tf_export` will fail\n # due to double-registration.\n f = types.FunctionType(f.__code__, f.__globals__, f.__name__, f.__defaults__,\n f.__closure__)\n return kwarg_only(do_not_generate_docs(f))\n\n\ndef raise_from_not_ok_status(e, name):\n message = e.message + (\" name: \" + name if name is not None else \"\")\n # pylint: disable=protected-access\n six.raise_from(core._status_to_exception(e.code, message), None)\n # pylint: enable=protected-access\n"
] |
[
[
"tensorflow.python.util.function_utils.get_func_code",
"tensorflow.python.pywrap_tensorflow.TF_OperationGetAttrType",
"tensorflow.python.eager.tape.stop_recording",
"tensorflow.python.eager.context.context",
"tensorflow.python.pywrap_tensorflow.TF_GraphCopyFunction",
"tensorflow.python.pywrap_tensorflow.GetOperationInputs",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.pywrap_tensorflow.TFE_Py_UID",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.util.tf_stack.extract_stack",
"tensorflow.python.util.deprecation.deprecated_args",
"tensorflow.python.pywrap_tensorflow.TF_Output",
"tensorflow.core.framework.attr_value_pb2.NameAttrList",
"tensorflow.python.pywrap_tensorflow.ClearAttr",
"tensorflow.python.pywrap_tensorflow.TFE_Py_InitEagerTensor",
"tensorflow.python.pywrap_tensorflow.TF_OperationName",
"tensorflow.python.pywrap_tensorflow.TF_OperationGetControlOutputs_wrapper",
"tensorflow.python.pywrap_tensorflow.TF_OperationGetControlInputs_wrapper",
"tensorflow.core.framework.function_pb2.GradientDef",
"tensorflow.python.framework.tensor_conversion_registry.register_tensor_conversion_function",
"tensorflow.python.framework.c_api_util.tf_output",
"tensorflow.python.pywrap_tensorflow.TF_OperationNumOutputs",
"tensorflow.python.eager.context.device",
"tensorflow.python.framework.device.is_device_spec",
"tensorflow.python.pywrap_tensorflow.TF_OperationGetAttrValueProto",
"tensorflow.python.pywrap_tensorflow.TF_OperationToNodeDef",
"tensorflow.python.pywrap_tensorflow.TF_OperationOutputType",
"tensorflow.python.pywrap_tensorflow.SetRequireShapeInferenceFns",
"tensorflow.python.pywrap_tensorflow.TF_FinishOperation",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"tensorflow.python.framework.c_api_util.tf_buffer",
"tensorflow.python.framework.registry.Registry",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.framework.c_api_util.new_tf_operations",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.python.pywrap_tensorflow.TF_AddControlInput",
"tensorflow.core.framework.versions_pb2.VersionDef",
"tensorflow.python.util.lock_util.GroupLock",
"tensorflow.python.framework.c_api_util.ScopedTFGraph",
"tensorflow.python.platform.app.run",
"tensorflow.python.eager.tape.record_operation",
"tensorflow.python.util.deprecation.deprecated_endpoints",
"tensorflow.python.pywrap_tensorflow.RemoveAllControlInputs",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.core.framework.op_def_pb2.OpDef",
"tensorflow.python.pywrap_tensorflow.AddControlInput",
"tensorflow.python.pywrap_tensorflow.SetRequestedDevice",
"tensorflow.python.eager.core._status_to_exception",
"tensorflow.python.util.compat.as_str",
"tensorflow.python.pywrap_tensorflow.TF_OperationGetAttrInt",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.tools.docs.doc_controls.do_not_generate_docs",
"tensorflow.python.pywrap_tensorflow.TF_Input",
"tensorflow.python.util.object_identity.ObjectIdentitySet",
"tensorflow.python.pywrap_tensorflow.TF_GraphToGraphDef",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.python.tf2.enabled",
"tensorflow.python.util.memory.dismantle_ordered_dict",
"tensorflow.python.pywrap_tensorflow.TF_DeleteBuffer",
"tensorflow.python.util.deprecation.deprecated_argument_lookup",
"tensorflow.python.pywrap_tensorflow.TF_GetBuffer",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.pywrap_tensorflow.TF_OperationDevice",
"tensorflow.python.eager.context.Context",
"tensorflow.python.eager.context.context_safe",
"tensorflow.python.framework.traceable_stack.TraceableStack",
"tensorflow.python.util.function_utils.get_func_name",
"tensorflow.python.framework.device.merge_device",
"tensorflow.python.pywrap_tensorflow.TF_GraphVersions",
"tensorflow.python.eager.monitoring.BoolGauge",
"tensorflow.python.pywrap_tensorflow.TF_OperationNumInputs",
"tensorflow.python.eager.context.graph_mode",
"tensorflow.python.util.object_identity.Reference",
"tensorflow.python.pywrap_tensorflow.TF_OperationOpType",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.pywrap_tensorflow.SetAttr",
"tensorflow.python.pywrap_tensorflow.TF_OperationGetAttrBool",
"tensorflow.core.framework.attr_value_pb2.AttrValue.ListValue",
"tensorflow.python.ops.control_flow_util.CheckInputFromValidContext",
"tensorflow.core.framework.graph_pb2.GraphDef"
]
] |
sdressler/s64da-benchmark-toolkit
|
[
"d69b4151c3615fa064795e174e95d159a12ac4ed"
] |
[
"s64da_benchmark_toolkit/netdata.py"
] |
[
"\nimport logging\n\nimport requests\nimport pandas\n\n\nLOG = logging.getLogger()\n\nclass Netdata:\n def __init__(self, config):\n self.url = f\"{config['url']}/api/v1/data\"\n self.metrics = config['metrics']\n self.charts = config['charts']\n\n def _get_data(self, timerange):\n data = pandas.DataFrame()\n for chart, dimensions in self.charts.items():\n result = requests.get(self.url, params={\n 'chart': chart,\n 'after': timerange[0],\n 'before': timerange[1],\n 'dimensions': ','.join(dimensions)\n }).json()\n\n columns = ['time']\n columns.extend([f'{chart}.{dimension}' for dimension in dimensions])\n columns = [column.replace('.', '_') for column in columns]\n\n df = pandas.DataFrame(result['data'], columns=columns)\n df = df.set_index('time')\n data = pandas.concat([data, df], axis=1)\n\n return data\n\n def write_stats(self, results, output):\n data = {}\n for name, result in results.items():\n # timerange = (int(result.start), int(result.stop))\n timerange = (result[0], result[1])\n df = self._get_data(timerange)\n data[name] = df.agg(self.metrics)\n\n with open(output, 'w') as output_file:\n for name, df in data.items():\n output_file.write(f'{name}')\n df.to_csv(output_file)\n output_file.write('\\n')\n"
] |
[
[
"pandas.concat",
"pandas.DataFrame"
]
] |
jdherman/eci273
|
[
"86828b2e075258afdd528e86295170e162cc99e3"
] |
[
"L15-reservoir-control-multiobj.py"
] |
[
"import numpy as np \nimport matplotlib.pyplot as plt\nfrom cvxpy import *\nimport seaborn as sns\nsns.set_style('whitegrid')\n\nQ = np.loadtxt('data/FOL-monthly-inflow-TAF.csv', delimiter=',', skiprows=1, usecols=[1])\nT = len(Q)\nK = 975 # reservoir capacity\nd = 150*np.ones(T) # target demand (TAF/day)\ndw = 0.1\n\nresults = []\ni = 1\n\n# weighted sum method\nfor w in np.arange(0,1+dw,dw):\n\n x = Variable(T+1)\n u = Variable(T)\n cost = sum((pos(d - u))**2)\n alteration = sum((u-Q)**2)\n\n obj = Minimize(w*cost + (1-w)*alteration) # sum squared deficit (vector form)\n\n # constraints (define separately, then concatenate the lists)\n c_mass_balance = [x[1:] == x[:-1] - u + Q] # state transition\n c_release = [u >= 0] # release lower/upper bounds\n c_storage = [x >= 0, x <= K] # storage lower/upper bounds\n c_init_final = [x[0] == 500, x[T] >= 200]\n constraints = c_mass_balance + c_release + c_storage + c_init_final\n\n prob = Problem(obj, constraints)\n prob.solve()\n results.append([cost.value, alteration.value])\n\n # plt.subplot(11,1,i)\n # plt.plot(Q, color='blue')\n # plt.plot(u.value, color='red')\n # plt.ylabel('Flow (TAF/m)')\n # plt.legend(['Inflow', 'Outflow'])\n print(i)\n i += 1\n\nplt.show()\n\nresults = np.array(results)\nplt.scatter(results[:,0],results[:,1], s=30, c='k')\nplt.xlabel('Shortage Cost ($)')\nplt.ylabel('Env. Alteration (TAF)')\nplt.show()\n\n"
] |
[
[
"matplotlib.pyplot.scatter",
"numpy.arange",
"numpy.ones",
"numpy.loadtxt",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
EliasVansteenkiste/edge_detection_framework
|
[
"b9b3d74bba78edce8b1b7382d0822966b80a61a5"
] |
[
"configs/pixelnet_pretrained.py"
] |
[
"import numpy as np\nimport torch\nimport torchvision\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import namedtuple\nfrom functools import partial\nfrom PIL import Image\n\nimport data_transforms\nimport data_iterators\nimport pathfinder\nimport utils\nimport app\n\n\n\nrestart_from_save = None\nrng = np.random.RandomState(37148)\n\n# transformations\np_transform = {'patch_size': (320, 320),\n 'channels': 3}\n\n# only lossless augmentations\np_augmentation = {\n 'rot90_values': [0, 1, 2, 3],\n 'flip': [0, 1]\n}\n\n# mean and std values for imagenet\nmean = np.asarray([0.485, 0.456, 0.406])\nmean = mean[:, None, None]\nstd = np.asarray([0.229, 0.224, 0.225])\nstd = std[:, None, None]\n\n\n# data preparation function\ndef data_prep_fun(x, y, random_gen):\n\n downscale_factor = 2\n x = x.resize((x.width//downscale_factor, x.height//downscale_factor))\n y = y.resize((y.width//downscale_factor, y.height//downscale_factor))\n\n x = np.asanyarray(x)\n y = np.asanyarray(y)\n\n x = np.swapaxes(x, 0, 2)\n x = np.swapaxes(x, 1, 2)\n x = x / 255.\n x = x.astype(np.float32)\n\n y = y / 255.\n y = y[None, :, :]\n y = y.astype(np.float32)\n\n x, y = data_transforms.random_crop_x_y(x, y, p_transform['patch_size'][0], p_transform['patch_size'][1], random_gen)\n\n return x, y\n\n\ntrain_data_prep_fun = partial(data_prep_fun, random_gen=rng)\nvalid_data_prep_fun = partial(data_prep_fun, random_gen=np.random.RandomState(0))\n\n# data iterators\nbatch_size = 1\nnbatches_chunk = 1\nchunk_size = batch_size * nbatches_chunk\n\n# dataset1 = app.get_id_pairs('test_data/test1/trainA', 'test_data/test1_hed/trainA')\ndataset1 = app.get_id_pairs('ir2day_3108/trainA', 'hed_ir2day_3108/trainA')\ndataset2 = app.get_id_pairs('ir2day_3108/trainB', 'hed_ir2day_3108/trainB')\nimg_id_pairs = [dataset1, dataset2]\n\nid_pairs = app.train_val_test_split(img_id_pairs, train_fraction=.7, val_fraction=.15, test_fraction=.15)\n\nbad_ids = []\nid_pairs['train'] = [x for x in id_pairs['train'] if x not in bad_ids]\nid_pairs['valid'] = [x for x in id_pairs['valid'] if x not in bad_ids]\nid_pairs['test'] = [x for x in id_pairs['test'] if x not in bad_ids]\n\ntrain_data_iterator = data_iterators.EdgeDataGenerator(mode='all',\n batch_size=chunk_size,\n img_id_pairs=id_pairs['train'],\n data_prep_fun=train_data_prep_fun,\n label_prep_fun=train_data_prep_fun,\n rng=rng,\n full_batch=True, random=True, infinite=True)\n\nvalid_data_iterator = data_iterators.EdgeDataGenerator(mode='all',\n batch_size=chunk_size,\n img_id_pairs=id_pairs['valid'],\n data_prep_fun=valid_data_prep_fun,\n label_prep_fun=valid_data_prep_fun,\n rng=rng,\n full_batch=False, random=False, infinite=False)\n\ntest_data_iterator = data_iterators.EdgeDataGenerator(mode='all',\n batch_size=chunk_size,\n img_id_pairs=id_pairs['test'],\n data_prep_fun=valid_data_prep_fun,\n label_prep_fun=valid_data_prep_fun,\n rng=rng,\n full_batch=False, random=False, infinite=False)\n\nnchunks_per_epoch = train_data_iterator.nsamples // chunk_size\nmax_nchunks = nchunks_per_epoch * 40\nprint('max_nchunks', max_nchunks)\n\nvalidate_every = int(0.1 * nchunks_per_epoch)\nsave_every = int(10 * nchunks_per_epoch)\n\nlearning_rate_schedule = {\n 0: 5e-4,\n int(max_nchunks * 0.3): 2e-4,\n int(max_nchunks * 0.6): 1e-4,\n int(max_nchunks * 0.8): 3e-5,\n int(max_nchunks * 0.9): 1e-5\n}\n\n\n# models\nclass VGG16features(nn.Module):\n def __init__(self, activation=F.relu):\n super(VGG16features, self).__init__()\n\n self.activation = activation\n\n self.init_pad = torch.nn.ReflectionPad2d(32)\n\n self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=(33, 33))\n self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)\n self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n\n self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)\n self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)\n self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n\n self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)\n self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)\n self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)\n self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n\n self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1)\n self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)\n self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)\n self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n\n self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)\n self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)\n self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)\n self.pool5 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, (2. / n) ** .5)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.conv1_1(x)\n x = self.activation(x)\n x = self.conv1_2(x)\n c1 = self.activation(x)\n\n x = self.pool1(c1)\n\n x = self.conv2_1(x)\n x = self.activation(x)\n x = self.conv2_2(x)\n c2 = self.activation(x)\n\n x = self.pool2(c2)\n\n x = self.conv3_1(x)\n x = self.activation(x)\n x = self.conv3_2(x)\n x = self.activation(x)\n x = self.conv3_3(x)\n c3 = self.activation(x)\n\n x = self.pool3(c3)\n\n x = self.conv4_1(x)\n x = self.activation(x)\n x = self.conv4_2(x)\n x = self.activation(x)\n x = self.conv4_3(x)\n c4 = self.activation(x)\n\n x = self.pool4(c4)\n\n x = self.conv5_1(x)\n x = self.activation(x)\n x = self.conv5_2(x)\n x = self.activation(x)\n x = self.conv5_3(x)\n c5 = self.activation(x)\n\n x = self.pool5(c5)\n\n return x\n\n def forward_hypercol(self, x):\n x = self.conv1_1(x)\n x = self.activation(x)\n x = self.conv1_2(x)\n c1 = self.activation(x)\n\n x = self.pool1(c1)\n\n x = self.conv2_1(x)\n x = self.activation(x)\n x = self.conv2_2(x)\n c2 = self.activation(x)\n\n x = self.pool2(c2)\n\n x = self.conv3_1(x)\n x = self.activation(x)\n x = self.conv3_2(x)\n x = self.activation(x)\n x = self.conv3_3(x)\n c3 = self.activation(x)\n\n x = self.pool3(c3)\n\n x = self.conv4_1(x)\n x = self.activation(x)\n x = self.conv4_2(x)\n x = self.activation(x)\n x = self.conv4_3(x)\n c4 = self.activation(x)\n\n x = self.pool4(c4)\n\n x = self.conv5_1(x)\n x = self.activation(x)\n x = self.conv5_2(x)\n x = self.activation(x)\n x = self.conv5_3(x)\n c5 = self.activation(x)\n\n return c1, c2, c3, c4, c5\n\n\n\nclass VGG(nn.Module):\n\n def __init__(self, features, num_classes=1000):\n super(VGG, self).__init__()\n self.features = features\n self.classifier = nn.Sequential(\n nn.Linear(512 * 7 * 7, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, num_classes),\n )\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, (2. / n)**.5)\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n\n\n\n\ndef vgg16(pretrained=False, **kwargs):\n \"\"\"VGG 16-layer model (configuration \"D\")\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n VGG16fs = VGG16features()\n model = VGG(VGG16fs, **kwargs)\n if pretrained:\n state_dict = torch.utils.model_zoo.load_url(torchvision.models.vgg.model_urls['vgg16'])\n new_state_dict = {}\n\n original_layer_ids = set()\n # copy the classifier entries and make a mapping for the feature mappings\n for key in state_dict.keys():\n if 'classifier' in key:\n new_state_dict[key] = state_dict[key]\n elif 'features' in key:\n original_layer_ids.add(int(key.split('.')[1]))\n sorted_original_layer_ids = sorted(list(original_layer_ids))\n\n layer_ids = set()\n for key in model.state_dict().keys():\n if 'classifier' in key:\n continue\n elif 'features' in key:\n layer_id = key.split('.')[1]\n layer_ids.add(layer_id)\n sorted_layer_ids = sorted(list(layer_ids))\n\n for key, value in state_dict.items():\n if 'features' in key:\n original_layer_id = int(key.split('.')[1])\n original_param_id = key.split('.')[2]\n idx = sorted_original_layer_ids.index(original_layer_id)\n new_layer_id = sorted_layer_ids[idx]\n new_key = 'features.' + new_layer_id + '.' + original_param_id\n new_state_dict[new_key] = value\n\n model.load_state_dict(new_state_dict)\n return model, VGG16fs\n\n\n\n\nclass PxlNet(nn.Module):\n def __init__(self, activation=F.relu):\n self.inplanes = 64\n super(PxlNet, self).__init__()\n\n self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear')\n self.upsample3 = nn.Upsample(scale_factor=4, mode='bilinear')\n self.upsample4 = nn.Upsample(scale_factor=8, mode='bilinear')\n self.upsample5 = nn.Upsample(scale_factor=16, mode='bilinear')\n\n self.crop = torch.nn.ReflectionPad2d(-32)\n\n self.drop = nn.Dropout(p=.5)\n\n self.cd1 = nn.Conv2d(1472, 512, kernel_size=1, stride=1, padding=0)\n self.cd2 = nn.Conv2d(512, 512, kernel_size=1, stride=1, padding=0)\n self.cd3 = nn.Conv2d(512, 1, kernel_size=1, stride=1, padding=0)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, (2. / n) ** .5)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n __, VGG16fs = vgg16(pretrained=True)\n self.VGG16fs = VGG16fs\n\n def forward(self, x):\n\n c1, c2, c3, c4, c5 = self.VGG16fs.forward_hypercol(x)\n\n s1 = c1\n s2 = self.upsample2(c2)\n s3 = self.upsample3(c3)\n s4 = self.upsample4(c4)\n s5 = self.upsample5(c5)\n\n hypercols = torch.cat([s1, s2, s3, s4, s5], dim=1)\n\n x = self.crop(hypercols)\n\n x = self.drop(x)\n\n x = self.cd1(x)\n x = self.cd2(x)\n x = self.cd3(x)\n\n x = F.sigmoid(x)\n\n return x\n\n\ndef build_model():\n net = PxlNet()\n return namedtuple('Model', ['l_out'])(net)\n\n\ndef _assert_no_grad(variable):\n assert not variable.requires_grad, \\\n \"nn criterions don't compute the gradient w.r.t. targets - please \" \\\n \"mark these variables as volatile or not requiring gradients\"\n\n\nclass SimpleBCELoss(nn.Module):\n def __init__(self, size_average=True):\n super(SimpleBCELoss, self).__init__()\n self.size_average = size_average\n\n def forward(self, input, target):\n _assert_no_grad(target)\n\n print('input', input.size(), 'target', target.size(), 'max', torch.max(target).data.cpu().numpy(), 'min', torch.min(target).data.cpu().numpy())\n\n return F.binary_cross_entropy(input, target, size_average = self.size_average)\n\n\nclass SimpleMSELoss(nn.Module):\n def __init__(self):\n super(SimpleMSELoss, self).__init__()\n\n def forward(self, input, target):\n _assert_no_grad(target)\n\n sq_err = (target - input) ** 2\n return torch.mean(sq_err)\n\n\nclass WeightedBCELoss(nn.Module):\n def __init__(self, size_average=True):\n super(WeightedBCELoss, self).__init__()\n self.size_average = size_average\n\n def forward(self, input, target):\n _assert_no_grad(target)\n\n beta = 1 - torch.mean(target)\n\n # target pixel = 1 -> weight beta\n # target pixel = 0 -> weight 1-beta\n weights = 1 - beta + (2 * beta - 1) * target\n\n return F.binary_cross_entropy(input, target, weights, self.size_average)\n\n\nclass WeightedMSELoss(nn.Module):\n def __init__(self):\n super(WeightedMSELoss, self).__init__()\n\n def forward(self, input, target):\n _assert_no_grad(target)\n\n err = (target - input)\n sq_err = err**2\n\n sign_err = torch.sign(err)\n is_pos_err = (sign_err + 1) / 2\n is_neg_err = (sign_err - 1) / -2\n\n edge_mass = torch.sum(target)\n empty_mass = torch.sum(1-target)\n total_mass = edge_mass + empty_mass\n\n weight_pos_err = empty_mass / total_mass\n weight_neg_err = edge_mass / total_mass\n\n pos_part = weight_pos_err * is_pos_err * sq_err\n neg_part = weight_neg_err * is_neg_err * sq_err\n\n weighted_sq_errs = neg_part + pos_part\n\n return torch.mean(weighted_sq_errs)\n\n\ndef build_objective():\n return WeightedMSELoss()\n\n\ndef build_objective2():\n return SimpleMSELoss()\n\n\ndef score(preds, gts):\n return app.cont_f_score(preds, gts)\n\n\ndef intermediate_valid_predictions(xs, gts, preds, pid, it_valid, n_save=10):\n path = pathfinder.METADATA_PATH + '/checkpoints/' + pid\n utils.auto_make_dir(path)\n pred_id = 0\n for batch_x, batch_gt, batch_pred in zip(xs, gts, preds):\n for x, gt, pred in zip(batch_x, batch_gt, batch_pred):\n if pred_id >= n_save:\n break\n # save pred\n pred = 255 * pred\n pred = pred.astype(int)\n app.save_image(pred[0], path + '/' + str(it_valid) + '_' + str(pred_id) + '_pred.jpg', mode='L')\n\n # save ground truth\n gt = 255 * gt\n gt = gt.astype(int)\n app.save_image(gt, path + '/' + str(it_valid) + '_' + str(pred_id) + '_real.jpg', mode='L')\n\n # save input\n x = 255 * x\n x = x.astype(int)\n app.save_image(x, path + '/' + str(it_valid) + '_' + str(pred_id) + '_input.jpg', mode='L')\n\n pred_id += 1\n\n\n# # updates\n# def build_updates(model, learning_rate):\n# return optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=0.0002)\n\n# updates\ndef build_updates(model, learning_rate):\n return optim.Adam(model.parameters(), lr=learning_rate)\n"
] |
[
[
"torch.mean",
"torch.max",
"torch.cat",
"numpy.asarray",
"torch.sign",
"torch.sum",
"torch.utils.model_zoo.load_url",
"numpy.swapaxes",
"torch.nn.Dropout",
"torch.nn.functional.sigmoid",
"numpy.asanyarray",
"torch.min",
"torch.nn.Conv2d",
"torch.nn.Linear",
"numpy.random.RandomState",
"torch.nn.ReflectionPad2d",
"torch.nn.MaxPool2d",
"torch.nn.Upsample",
"torch.nn.functional.binary_cross_entropy",
"torch.nn.ReLU"
]
] |
MichaelMonashev/albumentations
|
[
"86acab98a81754c2c2d0609519791059316ad121"
] |
[
"albumentations/augmentations/transforms.py"
] |
[
"from __future__ import absolute_import, division\n\nimport math\nimport random\nimport warnings\nfrom enum import Enum\nfrom types import LambdaType\n\nimport cv2\nimport numpy as np\n\nfrom . import functional as F\nfrom .bbox_utils import denormalize_bbox, normalize_bbox, union_of_bboxes\nfrom ..core.transforms_interface import DualTransform, ImageOnlyTransform, NoOp, to_tuple\nfrom ..core.utils import format_args\n\n__all__ = [\n \"Blur\",\n \"VerticalFlip\",\n \"HorizontalFlip\",\n \"Flip\",\n \"Normalize\",\n \"Transpose\",\n \"RandomCrop\",\n \"RandomGamma\",\n \"RandomRotate90\",\n \"Rotate\",\n \"ShiftScaleRotate\",\n \"CenterCrop\",\n \"OpticalDistortion\",\n \"GridDistortion\",\n \"ElasticTransform\",\n \"RandomGridShuffle\",\n \"HueSaturationValue\",\n \"PadIfNeeded\",\n \"RGBShift\",\n \"RandomBrightness\",\n \"RandomContrast\",\n \"MotionBlur\",\n \"MedianBlur\",\n \"GaussianBlur\",\n \"GaussNoise\",\n \"CLAHE\",\n \"ChannelShuffle\",\n \"InvertImg\",\n \"ToGray\",\n \"JpegCompression\",\n \"ImageCompression\",\n \"Cutout\",\n \"CoarseDropout\",\n \"ToFloat\",\n \"FromFloat\",\n \"Crop\",\n \"CropNonEmptyMaskIfExists\",\n \"RandomScale\",\n \"LongestMaxSize\",\n \"SmallestMaxSize\",\n \"Resize\",\n \"RandomSizedCrop\",\n \"RandomResizedCrop\",\n \"RandomBrightnessContrast\",\n \"RandomCropNearBBox\",\n \"RandomSizedBBoxSafeCrop\",\n \"RandomSnow\",\n \"RandomRain\",\n \"RandomFog\",\n \"RandomSunFlare\",\n \"RandomShadow\",\n \"Lambda\",\n \"ChannelDropout\",\n \"ISONoise\",\n \"Solarize\",\n \"Equalize\",\n \"Posterize\",\n \"Downscale\",\n]\n\n\nclass PadIfNeeded(DualTransform):\n \"\"\"Pad side of the image / max if side is less than desired number.\n\n Args:\n min_height (int): minimal result image height.\n min_width (int): minimal result image width.\n border_mode (OpenCV flag): OpenCV border mode.\n value (int, float, list of int, lisft of float): padding value if border_mode is cv2.BORDER_CONSTANT.\n mask_value (int, float,\n list of int,\n lisft of float): padding value for mask if border_mode is cv2.BORDER_CONSTANT.\n p (float): probability of applying the transform. Default: 1.0.\n\n Targets:\n image, mask, bbox, keypoints\n\n Image types:\n uint8, float32\n\n \"\"\"\n\n def __init__(\n self,\n min_height=1024,\n min_width=1024,\n border_mode=cv2.BORDER_REFLECT_101,\n value=None,\n mask_value=None,\n always_apply=False,\n p=1.0,\n ):\n super(PadIfNeeded, self).__init__(always_apply, p)\n self.min_height = min_height\n self.min_width = min_width\n self.border_mode = border_mode\n self.value = value\n self.mask_value = mask_value\n\n def update_params(self, params, **kwargs):\n params = super(PadIfNeeded, self).update_params(params, **kwargs)\n rows = params[\"rows\"]\n cols = params[\"cols\"]\n\n if rows < self.min_height:\n h_pad_top = int((self.min_height - rows) / 2.0)\n h_pad_bottom = self.min_height - rows - h_pad_top\n else:\n h_pad_top = 0\n h_pad_bottom = 0\n\n if cols < self.min_width:\n w_pad_left = int((self.min_width - cols) / 2.0)\n w_pad_right = self.min_width - cols - w_pad_left\n else:\n w_pad_left = 0\n w_pad_right = 0\n\n params.update(\n {\"pad_top\": h_pad_top, \"pad_bottom\": h_pad_bottom, \"pad_left\": w_pad_left, \"pad_right\": w_pad_right}\n )\n return params\n\n def apply(self, img, pad_top=0, pad_bottom=0, pad_left=0, pad_right=0, **params):\n return F.pad_with_params(\n img, pad_top, pad_bottom, pad_left, pad_right, border_mode=self.border_mode, value=self.value\n )\n\n def apply_to_mask(self, img, pad_top=0, pad_bottom=0, pad_left=0, pad_right=0, **params):\n return F.pad_with_params(\n img, pad_top, pad_bottom, pad_left, pad_right, border_mode=self.border_mode, value=self.mask_value\n )\n\n def apply_to_bbox(self, bbox, pad_top=0, pad_bottom=0, pad_left=0, pad_right=0, rows=0, cols=0, **params):\n x_min, y_min, x_max, y_max = denormalize_bbox(bbox, rows, cols)\n bbox = [x_min + pad_left, y_min + pad_top, x_max + pad_left, y_max + pad_top]\n return normalize_bbox(bbox, rows + pad_top + pad_bottom, cols + pad_left + pad_right)\n\n def apply_to_keypoint(self, keypoint, pad_top=0, pad_bottom=0, pad_left=0, pad_right=0, **params):\n x, y, a, s = keypoint\n return [x + pad_left, y + pad_top, a, s]\n\n def get_transform_init_args_names(self):\n return (\"min_height\", \"min_width\", \"border_mode\", \"value\", \"mask_value\")\n\n\nclass Crop(DualTransform):\n \"\"\"Crop region from image.\n\n Args:\n x_min (int): minimum upper left x coordinate.\n y_min (int): minimum upper left y coordinate.\n x_max (int): maximum lower right x coordinate.\n y_max (int): maximum lower right y coordinate.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, x_min=0, y_min=0, x_max=1024, y_max=1024, always_apply=False, p=1.0):\n super(Crop, self).__init__(always_apply, p)\n self.x_min = x_min\n self.y_min = y_min\n self.x_max = x_max\n self.y_max = y_max\n\n def apply(self, img, **params):\n return F.crop(img, x_min=self.x_min, y_min=self.y_min, x_max=self.x_max, y_max=self.y_max)\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_crop(bbox, x_min=self.x_min, y_min=self.y_min, x_max=self.x_max, y_max=self.y_max, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.crop_keypoint_by_coords(\n keypoint,\n crop_coords=[self.x_min, self.y_min, self.x_max, self.y_max],\n crop_height=self.y_max - self.y_min,\n crop_width=self.x_max - self.x_min,\n rows=params[\"rows\"],\n cols=params[\"cols\"],\n )\n\n def get_transform_init_args_names(self):\n return (\"x_min\", \"y_min\", \"x_max\", \"y_max\")\n\n\nclass VerticalFlip(DualTransform):\n \"\"\"Flip the input vertically around the x-axis.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, **params):\n return F.vflip(img)\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_vflip(bbox, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.keypoint_vflip(keypoint, **params)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass HorizontalFlip(DualTransform):\n \"\"\"Flip the input horizontally around the y-axis.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, **params):\n if img.ndim == 3 and img.shape[2] > 1 and img.dtype == np.uint8:\n # Opencv is faster than numpy only in case of\n # non-gray scale 8bits images\n return F.hflip_cv2(img)\n else:\n return F.hflip(img)\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_hflip(bbox, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.keypoint_hflip(keypoint, **params)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass Flip(DualTransform):\n \"\"\"Flip the input either horizontally, vertically or both horizontally and vertically.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, d=0, **params):\n \"\"\"Args:\n d (int): code that specifies how to flip the input. 0 for vertical flipping, 1 for horizontal flipping,\n -1 for both vertical and horizontal flipping (which is also could be seen as rotating the input by\n 180 degrees).\n \"\"\"\n return F.random_flip(img, d)\n\n def get_params(self):\n # Random int in the range [-1, 1]\n return {\"d\": random.randint(-1, 1)}\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_flip(bbox, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.keypoint_flip(keypoint, **params)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass Transpose(DualTransform):\n \"\"\"Transpose the input by swapping rows and columns.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, **params):\n return F.transpose(img)\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_transpose(bbox, 0, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.keypoint_transpose(keypoint)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass LongestMaxSize(DualTransform):\n \"\"\"Rescale an image so that maximum side is equal to max_size, keeping the aspect ratio of the initial image.\n\n Args:\n max_size (int): maximum size of the image after the transformation.\n interpolation (OpenCV flag): interpolation method. Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, max_size=1024, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1):\n super(LongestMaxSize, self).__init__(always_apply, p)\n self.interpolation = interpolation\n self.max_size = max_size\n\n def apply(self, img, interpolation=cv2.INTER_LINEAR, **params):\n return F.longest_max_size(img, max_size=self.max_size, interpolation=interpolation)\n\n def apply_to_bbox(self, bbox, **params):\n # Bounding box coordinates are scale invariant\n return bbox\n\n def apply_to_keypoint(self, keypoint, **params):\n height = params[\"rows\"]\n width = params[\"cols\"]\n\n scale = self.max_size / max([height, width])\n return F.keypoint_scale(keypoint, scale, scale)\n\n def get_transform_init_args_names(self):\n return (\"max_size\", \"interpolation\")\n\n\nclass SmallestMaxSize(DualTransform):\n \"\"\"Rescale an image so that minimum side is equal to max_size, keeping the aspect ratio of the initial image.\n\n Args:\n max_size (int): maximum size of smallest side of the image after the transformation.\n interpolation (OpenCV flag): interpolation method. Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, max_size=1024, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1):\n super(SmallestMaxSize, self).__init__(always_apply, p)\n self.interpolation = interpolation\n self.max_size = max_size\n\n def apply(self, img, interpolation=cv2.INTER_LINEAR, **params):\n return F.smallest_max_size(img, max_size=self.max_size, interpolation=interpolation)\n\n def apply_to_bbox(self, bbox, **params):\n return bbox\n\n def apply_to_keypoint(self, keypoint, **params):\n height = params[\"rows\"]\n width = params[\"cols\"]\n\n scale = self.max_size / min([height, width])\n return F.keypoint_scale(keypoint, scale, scale)\n\n def get_transform_init_args_names(self):\n return (\"max_size\", \"interpolation\")\n\n\nclass Resize(DualTransform):\n \"\"\"Resize the input to the given height and width.\n\n Args:\n height (int): desired height of the output.\n width (int): desired width of the output.\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, height, width, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1):\n super(Resize, self).__init__(always_apply, p)\n self.height = height\n self.width = width\n self.interpolation = interpolation\n\n def apply(self, img, interpolation=cv2.INTER_LINEAR, **params):\n return F.resize(img, height=self.height, width=self.width, interpolation=interpolation)\n\n def apply_to_bbox(self, bbox, **params):\n # Bounding box coordinates are scale invariant\n return bbox\n\n def apply_to_keypoint(self, keypoint, **params):\n height = params[\"rows\"]\n width = params[\"cols\"]\n scale_x = self.width / width\n scale_y = self.height / height\n return F.keypoint_scale(keypoint, scale_x, scale_y)\n\n def get_transform_init_args_names(self):\n return (\"height\", \"width\", \"interpolation\")\n\n\nclass RandomRotate90(DualTransform):\n \"\"\"Randomly rotate the input by 90 degrees zero or more times.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, factor=0, **params):\n \"\"\"\n Args:\n factor (int): number of times the input will be rotated by 90 degrees.\n \"\"\"\n return np.ascontiguousarray(np.rot90(img, factor))\n\n def get_params(self):\n # Random int in the range [0, 3]\n return {\"factor\": random.randint(0, 3)}\n\n def apply_to_bbox(self, bbox, factor=0, **params):\n return F.bbox_rot90(bbox, factor, **params)\n\n def apply_to_keypoint(self, keypoint, factor=0, **params):\n return F.keypoint_rot90(keypoint, factor, **params)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass Rotate(DualTransform):\n \"\"\"Rotate the input by an angle selected randomly from the uniform distribution.\n\n Args:\n limit ((int, int) or int): range from which a random angle is picked. If limit is a single int\n an angle is picked from (-limit, limit). Default: (-90, 90)\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n border_mode (OpenCV flag): flag that is used to specify the pixel extrapolation method. Should be one of:\n cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.\n Default: cv2.BORDER_REFLECT_101\n value (int, float, list of ints, list of float): padding value if border_mode is cv2.BORDER_CONSTANT.\n mask_value (int, float,\n list of ints,\n list of float): padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n limit=90,\n interpolation=cv2.INTER_LINEAR,\n border_mode=cv2.BORDER_REFLECT_101,\n value=None,\n mask_value=None,\n always_apply=False,\n p=0.5,\n ):\n super(Rotate, self).__init__(always_apply, p)\n self.limit = to_tuple(limit)\n self.interpolation = interpolation\n self.border_mode = border_mode\n self.value = value\n self.mask_value = mask_value\n\n def apply(self, img, angle=0, interpolation=cv2.INTER_LINEAR, **params):\n return F.rotate(img, angle, interpolation, self.border_mode, self.value)\n\n def apply_to_mask(self, img, angle=0, **params):\n return F.rotate(img, angle, cv2.INTER_NEAREST, self.border_mode, self.mask_value)\n\n def get_params(self):\n return {\"angle\": random.uniform(self.limit[0], self.limit[1])}\n\n def apply_to_bbox(self, bbox, angle=0, **params):\n return F.bbox_rotate(bbox, angle, **params)\n\n def apply_to_keypoint(self, keypoint, angle=0, **params):\n return F.keypoint_rotate(keypoint, angle, **params)\n\n def get_transform_init_args_names(self):\n return (\"limit\", \"interpolation\", \"border_mode\", \"value\", \"mask_value\")\n\n\nclass RandomScale(DualTransform):\n \"\"\"Randomly resize the input. Output image size is different from the input image size.\n\n Args:\n scale_limit ((float, float) or float): scaling factor range. If scale_limit is a single float value, the\n range will be (1 - scale_limit, 1 + scale_limit). Default: (0.9, 1.1).\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, scale_limit=0.1, interpolation=cv2.INTER_LINEAR, always_apply=False, p=0.5):\n super(RandomScale, self).__init__(always_apply, p)\n self.scale_limit = to_tuple(scale_limit, bias=1.0)\n self.interpolation = interpolation\n\n def get_params(self):\n return {\"scale\": random.uniform(self.scale_limit[0], self.scale_limit[1])}\n\n def apply(self, img, scale=0, interpolation=cv2.INTER_LINEAR, **params):\n return F.scale(img, scale, interpolation)\n\n def apply_to_bbox(self, bbox, **params):\n # Bounding box coordinates are scale invariant\n return bbox\n\n def apply_to_keypoint(self, keypoint, scale=0, **params):\n return F.keypoint_scale(keypoint, scale, scale)\n\n def get_transform_init_args(self):\n return {\"interpolation\": self.interpolation, \"scale_limit\": to_tuple(self.scale_limit, bias=-1.0)}\n\n\nclass ShiftScaleRotate(DualTransform):\n \"\"\"Randomly apply affine transforms: translate, scale and rotate the input.\n\n Args:\n shift_limit ((float, float) or float): shift factor range for both height and width. If shift_limit\n is a single float value, the range will be (-shift_limit, shift_limit). Absolute values for lower and\n upper bounds should lie in range [0, 1]. Default: (-0.0625, 0.0625).\n scale_limit ((float, float) or float): scaling factor range. If scale_limit is a single float value, the\n range will be (-scale_limit, scale_limit). Default: (-0.1, 0.1).\n rotate_limit ((int, int) or int): rotation range. If rotate_limit is a single int value, the\n range will be (-rotate_limit, rotate_limit). Default: (-45, 45).\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n border_mode (OpenCV flag): flag that is used to specify the pixel extrapolation method. Should be one of:\n cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.\n Default: cv2.BORDER_REFLECT_101\n value (int, float, list of int, list of float): padding value if border_mode is cv2.BORDER_CONSTANT.\n mask_value (int, float,\n list of int,\n list of float): padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image, mask, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n shift_limit=0.0625,\n scale_limit=0.1,\n rotate_limit=45,\n interpolation=cv2.INTER_LINEAR,\n border_mode=cv2.BORDER_REFLECT_101,\n value=None,\n mask_value=None,\n always_apply=False,\n p=0.5,\n ):\n super(ShiftScaleRotate, self).__init__(always_apply, p)\n self.shift_limit = to_tuple(shift_limit)\n self.scale_limit = to_tuple(scale_limit, bias=1.0)\n self.rotate_limit = to_tuple(rotate_limit)\n self.interpolation = interpolation\n self.border_mode = border_mode\n self.value = value\n self.mask_value = mask_value\n\n def apply(self, img, angle=0, scale=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, **params):\n return F.shift_scale_rotate(img, angle, scale, dx, dy, interpolation, self.border_mode, self.value)\n\n def apply_to_mask(self, img, angle=0, scale=0, dx=0, dy=0, **params):\n return F.shift_scale_rotate(img, angle, scale, dx, dy, cv2.INTER_NEAREST, self.border_mode, self.mask_value)\n\n def apply_to_keypoint(\n self, keypoint, angle=0, scale=0, dx=0, dy=0, rows=0, cols=0, interpolation=cv2.INTER_LINEAR, **params\n ):\n return F.keypoint_shift_scale_rotate(keypoint, angle, scale, dx, dy, rows, cols)\n\n def get_params(self):\n return {\n \"angle\": random.uniform(self.rotate_limit[0], self.rotate_limit[1]),\n \"scale\": random.uniform(self.scale_limit[0], self.scale_limit[1]),\n \"dx\": random.uniform(self.shift_limit[0], self.shift_limit[1]),\n \"dy\": random.uniform(self.shift_limit[0], self.shift_limit[1]),\n }\n\n def apply_to_bbox(self, bbox, angle, scale, dx, dy, interpolation=cv2.INTER_LINEAR, **params):\n return F.bbox_shift_scale_rotate(bbox, angle, scale, dx, dy, interpolation=cv2.INTER_LINEAR, **params)\n\n def get_transform_init_args(self):\n return {\n \"shift_limit\": self.shift_limit,\n \"scale_limit\": to_tuple(self.scale_limit, bias=-1.0),\n \"rotate_limit\": self.rotate_limit,\n \"interpolation\": self.interpolation,\n \"border_mode\": self.border_mode,\n \"value\": self.value,\n \"mask_value\": self.mask_value,\n }\n\n\nclass CenterCrop(DualTransform):\n \"\"\"Crop the central part of the input.\n\n Args:\n height (int): height of the crop.\n width (int): width of the crop.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n\n Note:\n It is recommended to use uint8 images as input.\n Otherwise the operation will require internal conversion\n float32 -> uint8 -> float32 that causes worse performance.\n \"\"\"\n\n def __init__(self, height, width, always_apply=False, p=1.0):\n super(CenterCrop, self).__init__(always_apply, p)\n self.height = height\n self.width = width\n\n def apply(self, img, **params):\n return F.center_crop(img, self.height, self.width)\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_center_crop(bbox, self.height, self.width, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.keypoint_center_crop(keypoint, self.height, self.width, **params)\n\n def get_transform_init_args_names(self):\n return (\"height\", \"width\")\n\n\nclass RandomCrop(DualTransform):\n \"\"\"Crop a random part of the input.\n\n Args:\n height (int): height of the crop.\n width (int): width of the crop.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, height, width, always_apply=False, p=1.0):\n super(RandomCrop, self).__init__(always_apply, p)\n self.height = height\n self.width = width\n\n def apply(self, img, h_start=0, w_start=0, **params):\n return F.random_crop(img, self.height, self.width, h_start, w_start)\n\n def get_params(self):\n return {\"h_start\": random.random(), \"w_start\": random.random()}\n\n def apply_to_bbox(self, bbox, **params):\n return F.bbox_random_crop(bbox, self.height, self.width, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n return F.keypoint_random_crop(keypoint, self.height, self.width, **params)\n\n def get_transform_init_args_names(self):\n return (\"height\", \"width\")\n\n\nclass RandomCropNearBBox(DualTransform):\n \"\"\"Crop bbox from image with random shift by x,y coordinates\n\n Args:\n max_part_shift (float): float value in (0.0, 1.0) range. Default 0.3\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, max_part_shift=0.3, always_apply=False, p=1.0):\n super(RandomCropNearBBox, self).__init__(always_apply, p)\n self.max_part_shift = max_part_shift\n\n def apply(self, img, x_min=0, x_max=0, y_min=0, y_max=0, **params):\n return F.clamping_crop(img, x_min, y_min, x_max, y_max)\n\n def get_params_dependent_on_targets(self, params):\n bbox = params[\"cropping_bbox\"]\n h_max_shift = int((bbox[3] - bbox[1]) * self.max_part_shift)\n w_max_shift = int((bbox[2] - bbox[0]) * self.max_part_shift)\n\n x_min = bbox[0] - random.randint(-w_max_shift, w_max_shift)\n x_max = bbox[2] + random.randint(-w_max_shift, w_max_shift)\n\n y_min = bbox[1] - random.randint(-h_max_shift, h_max_shift)\n y_max = bbox[3] + random.randint(-h_max_shift, h_max_shift)\n\n return {\"x_min\": x_min, \"x_max\": x_max, \"y_min\": y_min, \"y_max\": y_max}\n\n def apply_to_bbox(self, bbox, x_min=0, x_max=0, y_min=0, y_max=0, **params):\n h_start = y_min\n w_start = x_min\n return F.bbox_crop(bbox, y_max - y_min, x_max - x_min, h_start, w_start, **params)\n\n def apply_to_keypoint(self, keypoint, x_min=0, x_max=0, y_min=0, y_max=0, **params):\n return F.crop_keypoint_by_coords(\n keypoint,\n crop_coords=[x_min, y_min, x_max, y_max],\n crop_height=y_max - y_min,\n crop_width=x_max - x_min,\n rows=params[\"rows\"],\n cols=params[\"cols\"],\n )\n\n @property\n def targets_as_params(self):\n return [\"cropping_bbox\"]\n\n def get_transform_init_args_names(self):\n return (\"max_part_shift\",)\n\n\nclass _BaseRandomSizedCrop(DualTransform):\n # Base class for RandomSizedCrop and RandomResizedCrop\n\n def __init__(self, height, width, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1.0):\n super(_BaseRandomSizedCrop, self).__init__(always_apply, p)\n self.height = height\n self.width = width\n self.interpolation = interpolation\n\n def apply(self, img, crop_height=0, crop_width=0, h_start=0, w_start=0, interpolation=cv2.INTER_LINEAR, **params):\n crop = F.random_crop(img, crop_height, crop_width, h_start, w_start)\n return F.resize(crop, self.height, self.width, interpolation)\n\n def apply_to_bbox(self, bbox, crop_height=0, crop_width=0, h_start=0, w_start=0, rows=0, cols=0, **params):\n return F.bbox_random_crop(bbox, crop_height, crop_width, h_start, w_start, rows, cols)\n\n def apply_to_keypoint(self, keypoint, crop_height=0, crop_width=0, h_start=0, w_start=0, rows=0, cols=0, **params):\n keypoint = F.keypoint_random_crop(keypoint, crop_height, crop_width, h_start, w_start, rows, cols)\n scale_x = self.width / crop_width\n scale_y = self.height / crop_height\n keypoint = F.keypoint_scale(keypoint, scale_x, scale_y)\n return keypoint\n\n\nclass RandomSizedCrop(_BaseRandomSizedCrop):\n \"\"\"Crop a random part of the input and rescale it to some size.\n\n Args:\n min_max_height ((int, int)): crop size limits.\n height (int): height after crop and resize.\n width (int): width after crop and resize.\n w2h_ratio (float): aspect ratio of crop.\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self, min_max_height, height, width, w2h_ratio=1.0, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1.0\n ):\n super(RandomSizedCrop, self).__init__(\n height=height, width=width, interpolation=interpolation, always_apply=always_apply, p=p\n )\n self.min_max_height = min_max_height\n self.w2h_ratio = w2h_ratio\n\n def get_params(self):\n crop_height = random.randint(self.min_max_height[0], self.min_max_height[1])\n return {\n \"h_start\": random.random(),\n \"w_start\": random.random(),\n \"crop_height\": crop_height,\n \"crop_width\": int(crop_height * self.w2h_ratio),\n }\n\n def get_transform_init_args_names(self):\n return \"min_max_height\", \"height\", \"width\", \"w2h_ratio\", \"interpolation\"\n\n\nclass RandomResizedCrop(_BaseRandomSizedCrop):\n \"\"\"Torchvision's variant of crop a random part of the input and rescale it to some size.\n\n Args:\n height (int): height after crop and resize.\n width (int): width after crop and resize.\n scale ((float, float)): range of size of the origin size cropped\n ratio ((float, float)): range of aspect ratio of the origin aspect ratio cropped\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n height,\n width,\n scale=(0.08, 1.0),\n ratio=(0.75, 1.3333333333333333),\n interpolation=cv2.INTER_LINEAR,\n always_apply=False,\n p=1.0,\n ):\n\n super(RandomResizedCrop, self).__init__(\n height=height, width=width, interpolation=interpolation, always_apply=always_apply, p=p\n )\n self.scale = scale\n self.ratio = ratio\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n area = img.shape[0] * img.shape[1]\n\n for _attempt in range(10):\n target_area = random.uniform(*self.scale) * area\n log_ratio = (math.log(self.ratio[0]), math.log(self.ratio[1]))\n aspect_ratio = math.exp(random.uniform(*log_ratio))\n\n w = int(round(math.sqrt(target_area * aspect_ratio)))\n h = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if 0 < w <= img.shape[1] and 0 < h <= img.shape[0]:\n i = random.randint(0, img.shape[0] - h)\n j = random.randint(0, img.shape[1] - w)\n return {\n \"crop_height\": h,\n \"crop_width\": w,\n \"h_start\": i * 1.0 / (img.shape[0] - h + 1e-10),\n \"w_start\": j * 1.0 / (img.shape[1] - w + 1e-10),\n }\n\n # Fallback to central crop\n in_ratio = img.shape[1] / img.shape[0]\n if in_ratio < min(self.ratio):\n w = img.shape[1]\n h = int(round(w / min(self.ratio)))\n elif in_ratio > max(self.ratio):\n h = img.shape[0]\n w = int(round(h * max(self.ratio)))\n else: # whole image\n w = img.shape[1]\n h = img.shape[0]\n i = (img.shape[0] - h) // 2\n j = (img.shape[1] - w) // 2\n return {\n \"crop_height\": h,\n \"crop_width\": w,\n \"h_start\": i * 1.0 / (img.shape[0] - h + 1e-10),\n \"w_start\": j * 1.0 / (img.shape[1] - w + 1e-10),\n }\n\n def get_params(self):\n return {}\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_transform_init_args_names(self):\n return \"height\", \"width\", \"scale\", \"ratio\", \"interpolation\"\n\n\nclass RandomSizedBBoxSafeCrop(DualTransform):\n \"\"\"Crop a random part of the input and rescale it to some size without loss of bboxes.\n\n Args:\n height (int): height after crop and resize.\n width (int): width after crop and resize.\n erosion_rate (float): erosion rate applied on input image height before crop.\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n p (float): probability of applying the transform. Default: 1.\n\n Targets:\n image, mask, bboxes\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, height, width, erosion_rate=0.0, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1.0):\n super(RandomSizedBBoxSafeCrop, self).__init__(always_apply, p)\n self.height = height\n self.width = width\n self.interpolation = interpolation\n self.erosion_rate = erosion_rate\n\n def apply(self, img, crop_height=0, crop_width=0, h_start=0, w_start=0, interpolation=cv2.INTER_LINEAR, **params):\n crop = F.random_crop(img, crop_height, crop_width, h_start, w_start)\n return F.resize(crop, self.height, self.width, interpolation)\n\n def get_params_dependent_on_targets(self, params):\n img_h, img_w = params[\"image\"].shape[:2]\n if len(params[\"bboxes\"]) == 0: # less likely, this class is for use with bboxes.\n erosive_h = int(img_h * (1.0 - self.erosion_rate))\n crop_height = img_h if erosive_h >= img_h else random.randint(erosive_h, img_h)\n return {\n \"h_start\": random.random(),\n \"w_start\": random.random(),\n \"crop_height\": crop_height,\n \"crop_width\": int(crop_height * img_w / img_h),\n }\n # get union of all bboxes\n x, y, x2, y2 = union_of_bboxes(\n width=img_w, height=img_h, bboxes=params[\"bboxes\"], erosion_rate=self.erosion_rate\n )\n # find bigger region\n bx, by = x * random.random(), y * random.random()\n bx2, by2 = x2 + (1 - x2) * random.random(), y2 + (1 - y2) * random.random()\n bw, bh = bx2 - bx, by2 - by\n crop_height, crop_width = int(img_h * bh), int(img_w * bw)\n h_start = np.clip(0.0 if bh >= 1.0 else by / (1.0 - bh), 0.0, 1.0)\n w_start = np.clip(0.0 if bw >= 1.0 else bx / (1.0 - bw), 0.0, 1.0)\n return {\"h_start\": h_start, \"w_start\": w_start, \"crop_height\": crop_height, \"crop_width\": crop_width}\n\n def apply_to_bbox(self, bbox, crop_height=0, crop_width=0, h_start=0, w_start=0, rows=0, cols=0, **params):\n return F.bbox_random_crop(bbox, crop_height, crop_width, h_start, w_start, rows, cols)\n\n @property\n def targets_as_params(self):\n return [\"image\", \"bboxes\"]\n\n def get_transform_init_args_names(self):\n return (\"height\", \"width\", \"erosion_rate\", \"interpolation\")\n\n\nclass CropNonEmptyMaskIfExists(DualTransform):\n \"\"\"Crop area with mask if mask is non-empty, else make random crop.\n\n Args:\n height (int): vertical size of crop in pixels\n width (int): horizontal size of crop in pixels\n ignore_values (list of int): values to ignore in mask, `0` values are always ignored\n (e.g. if background value is 5 set `ignore_values=[5]` to ignore)\n ignore_channels (list of int): channels to ignore in mask\n (e.g. if background is a first channel set `ignore_channels=[0]` to ignore)\n p (float): probability of applying the transform. Default: 1.0.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, height, width, ignore_values=None, ignore_channels=None, always_apply=False, p=1.0):\n super(CropNonEmptyMaskIfExists, self).__init__(always_apply, p)\n\n if ignore_values is not None and not isinstance(ignore_values, list):\n raise ValueError(\"Expected `ignore_values` of type `list`, got `{}`\".format(type(ignore_values)))\n if ignore_channels is not None and not isinstance(ignore_channels, list):\n raise ValueError(\"Expected `ignore_channels` of type `list`, got `{}`\".format(type(ignore_channels)))\n\n self.height = height\n self.width = width\n self.ignore_values = ignore_values\n self.ignore_channels = ignore_channels\n\n def apply(self, img, x_min=0, x_max=0, y_min=0, y_max=0, **params):\n return F.crop(img, x_min, y_min, x_max, y_max)\n\n def apply_to_bbox(self, bbox, x_min=0, x_max=0, y_min=0, y_max=0, **params):\n return F.bbox_crop(\n bbox, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, rows=params[\"rows\"], cols=params[\"cols\"]\n )\n\n def apply_to_keypoint(self, keypoint, x_min=0, x_max=0, y_min=0, y_max=0, **params):\n return F.crop_keypoint_by_coords(\n keypoint,\n crop_coords=[x_min, y_min, x_max, y_max],\n crop_height=y_max - y_min,\n crop_width=x_max - x_min,\n rows=params[\"rows\"],\n cols=params[\"cols\"],\n )\n\n @property\n def targets_as_params(self):\n return [\"mask\"]\n\n def get_params_dependent_on_targets(self, params):\n mask = params[\"mask\"]\n mask_height, mask_width = mask.shape[:2]\n\n if self.ignore_values is not None:\n ignore_values_np = np.array(self.ignore_values)\n mask = np.where(np.isin(mask, ignore_values_np), 0, mask)\n\n if mask.ndim == 3 and self.ignore_channels is not None:\n target_channels = np.array([ch for ch in range(mask.shape[-1]) if ch not in self.ignore_channels])\n mask = np.take(mask, target_channels, axis=-1)\n\n if self.height > mask_height or self.width > mask_width:\n raise ValueError(\n \"Crop size ({},{}) is larger than image ({},{})\".format(\n self.height, self.width, mask_height, mask_width\n )\n )\n\n if mask.sum() == 0:\n x_min = random.randint(0, mask_width - self.width)\n y_min = random.randint(0, mask_height - self.height)\n else:\n mask = mask.sum(axis=-1) if mask.ndim == 3 else mask\n non_zero_yx = np.argwhere(mask)\n y, x = random.choice(non_zero_yx)\n x_min = x - random.randint(0, self.width - 1)\n y_min = y - random.randint(0, self.height - 1)\n x_min = np.clip(x_min, 0, mask_width - self.width)\n y_min = np.clip(y_min, 0, mask_height - self.height)\n\n x_max = x_min + self.width\n y_max = y_min + self.height\n\n return {\"x_min\": x_min, \"x_max\": x_max, \"y_min\": y_min, \"y_max\": y_max}\n\n def get_transform_init_args_names(self):\n return (\"height\", \"width\", \"ignore_values\", \"ignore_channels\")\n\n\nclass OpticalDistortion(DualTransform):\n \"\"\"\n Args:\n distort_limit (float, (float, float)): If distort_limit is a single float, the range\n will be (-distort_limit, distort_limit). Default: (-0.05, 0.05).\n shift_limit (float, (float, float))): If shift_limit is a single float, the range\n will be (-shift_limit, shift_limit). Default: (-0.05, 0.05).\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n border_mode (OpenCV flag): flag that is used to specify the pixel extrapolation method. Should be one of:\n cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.\n Default: cv2.BORDER_REFLECT_101\n value (int, float, list of ints, list of float): padding value if border_mode is cv2.BORDER_CONSTANT.\n mask_value (int, float,\n list of ints,\n list of float): padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.\n\n Targets:\n image, mask\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n distort_limit=0.05,\n shift_limit=0.05,\n interpolation=cv2.INTER_LINEAR,\n border_mode=cv2.BORDER_REFLECT_101,\n value=None,\n mask_value=None,\n always_apply=False,\n p=0.5,\n ):\n super(OpticalDistortion, self).__init__(always_apply, p)\n self.shift_limit = to_tuple(shift_limit)\n self.distort_limit = to_tuple(distort_limit)\n self.interpolation = interpolation\n self.border_mode = border_mode\n self.value = value\n self.mask_value = mask_value\n\n def apply(self, img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, **params):\n return F.optical_distortion(img, k, dx, dy, interpolation, self.border_mode, self.value)\n\n def apply_to_mask(self, img, k=0, dx=0, dy=0, **params):\n return F.optical_distortion(img, k, dx, dy, cv2.INTER_NEAREST, self.border_mode, self.mask_value)\n\n def get_params(self):\n return {\n \"k\": random.uniform(self.distort_limit[0], self.distort_limit[1]),\n \"dx\": round(random.uniform(self.shift_limit[0], self.shift_limit[1])),\n \"dy\": round(random.uniform(self.shift_limit[0], self.shift_limit[1])),\n }\n\n def get_transform_init_args_names(self):\n return (\"distort_limit\", \"shift_limit\", \"interpolation\", \"border_mode\", \"value\", \"mask_value\")\n\n\nclass GridDistortion(DualTransform):\n \"\"\"\n Args:\n num_steps (int): count of grid cells on each side.\n distort_limit (float, (float, float)): If distort_limit is a single float, the range\n will be (-distort_limit, distort_limit). Default: (-0.03, 0.03).\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n border_mode (OpenCV flag): flag that is used to specify the pixel extrapolation method. Should be one of:\n cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.\n Default: cv2.BORDER_REFLECT_101\n value (int, float, list of ints, list of float): padding value if border_mode is cv2.BORDER_CONSTANT.\n mask_value (int, float,\n list of ints,\n list of float): padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.\n\n Targets:\n image, mask\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n num_steps=5,\n distort_limit=0.3,\n interpolation=cv2.INTER_LINEAR,\n border_mode=cv2.BORDER_REFLECT_101,\n value=None,\n mask_value=None,\n always_apply=False,\n p=0.5,\n ):\n super(GridDistortion, self).__init__(always_apply, p)\n self.num_steps = num_steps\n self.distort_limit = to_tuple(distort_limit)\n self.interpolation = interpolation\n self.border_mode = border_mode\n self.value = value\n self.mask_value = mask_value\n\n def apply(self, img, stepsx=[], stepsy=[], interpolation=cv2.INTER_LINEAR, **params):\n return F.grid_distortion(img, self.num_steps, stepsx, stepsy, interpolation, self.border_mode, self.value)\n\n def apply_to_mask(self, img, stepsx=[], stepsy=[], **params):\n return F.grid_distortion(\n img, self.num_steps, stepsx, stepsy, cv2.INTER_NEAREST, self.border_mode, self.mask_value\n )\n\n def get_params(self):\n stepsx = [1 + random.uniform(self.distort_limit[0], self.distort_limit[1]) for i in range(self.num_steps + 1)]\n stepsy = [1 + random.uniform(self.distort_limit[0], self.distort_limit[1]) for i in range(self.num_steps + 1)]\n return {\"stepsx\": stepsx, \"stepsy\": stepsy}\n\n def get_transform_init_args_names(self):\n return (\"num_steps\", \"distort_limit\", \"interpolation\", \"border_mode\", \"value\", \"mask_value\")\n\n\nclass ElasticTransform(DualTransform):\n \"\"\"Elastic deformation of images as described in [Simard2003]_ (with modifications).\n Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5\n\n .. [Simard2003] Simard, Steinkraus and Platt, \"Best Practices for\n Convolutional Neural Networks applied to Visual Document Analysis\", in\n Proc. of the International Conference on Document Analysis and\n Recognition, 2003.\n\n Args:\n alpha (float):\n sigma (float): Gaussian filter parameter.\n alpha_affine (float): The range will be (-alpha_affine, alpha_affine)\n interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.\n Default: cv2.INTER_LINEAR.\n border_mode (OpenCV flag): flag that is used to specify the pixel extrapolation method. Should be one of:\n cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.\n Default: cv2.BORDER_REFLECT_101\n value (int, float, list of ints, list of float): padding value if border_mode is cv2.BORDER_CONSTANT.\n mask_value (int, float,\n list of ints,\n list of float): padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.\n approximate (boolean): Whether to smooth displacement map with fixed kernel size.\n Enabling this option gives ~2X speedup on large images.\n\n Targets:\n image, mask\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n alpha=1,\n sigma=50,\n alpha_affine=50,\n interpolation=cv2.INTER_LINEAR,\n border_mode=cv2.BORDER_REFLECT_101,\n value=None,\n mask_value=None,\n always_apply=False,\n approximate=False,\n p=0.5,\n ):\n super(ElasticTransform, self).__init__(always_apply, p)\n self.alpha = alpha\n self.alpha_affine = alpha_affine\n self.sigma = sigma\n self.interpolation = interpolation\n self.border_mode = border_mode\n self.value = value\n self.mask_value = mask_value\n self.approximate = approximate\n\n def apply(self, img, random_state=None, interpolation=cv2.INTER_LINEAR, **params):\n return F.elastic_transform(\n img,\n self.alpha,\n self.sigma,\n self.alpha_affine,\n interpolation,\n self.border_mode,\n self.value,\n np.random.RandomState(random_state),\n self.approximate,\n )\n\n def apply_to_mask(self, img, random_state=None, **params):\n return F.elastic_transform(\n img,\n self.alpha,\n self.sigma,\n self.alpha_affine,\n cv2.INTER_NEAREST,\n self.border_mode,\n self.mask_value,\n np.random.RandomState(random_state),\n self.approximate,\n )\n\n def get_params(self):\n return {\"random_state\": random.randint(0, 10000)}\n\n def get_transform_init_args_names(self):\n return (\"alpha\", \"sigma\", \"alpha_affine\", \"interpolation\", \"border_mode\", \"value\", \"mask_value\", \"approximate\")\n\n\nclass RandomGridShuffle(DualTransform):\n \"\"\"\n Random shuffle grid's cells on image.\n\n Args:\n grid ((int, int)): size of grid for splitting image.\n\n Targets:\n image, mask\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, grid=(3, 3), always_apply=False, p=0.5):\n super(RandomGridShuffle, self).__init__(always_apply, p)\n self.grid = grid\n\n def apply(self, img, tiles=None, **params):\n if tiles is None:\n tiles = []\n\n return F.swap_tiles_on_image(img, tiles)\n\n def apply_to_mask(self, img, tiles=None, **params):\n if tiles is None:\n tiles = []\n\n return F.swap_tiles_on_image(img, tiles)\n\n def get_params_dependent_on_targets(self, params):\n height, width = params[\"image\"].shape[:2]\n n, m = self.grid\n\n if n <= 0 or m <= 0:\n raise ValueError(\"Grid's values must be positive. Current grid [%s, %s]\" % (n, m))\n\n if n > height // 2 or m > width // 2:\n raise ValueError(\"Incorrect size cell of grid. Just shuffle pixels of image\")\n\n random_state = np.random.RandomState(random.randint(0, 10000))\n\n height_split = np.linspace(0, height, n + 1, dtype=np.int)\n width_split = np.linspace(0, width, m + 1, dtype=np.int)\n\n height_matrix, width_matrix = np.meshgrid(height_split, width_split, indexing=\"ij\")\n\n index_height_matrix = height_matrix[:-1, :-1]\n index_width_matrix = width_matrix[:-1, :-1]\n\n shifted_index_height_matrix = height_matrix[1:, 1:]\n shifted_index_width_matrix = width_matrix[1:, 1:]\n\n height_tile_sizes = shifted_index_height_matrix - index_height_matrix\n width_tile_sizes = shifted_index_width_matrix - index_width_matrix\n\n tiles_sizes = np.stack((height_tile_sizes, width_tile_sizes), axis=2)\n\n index_matrix = np.indices((n, m))\n new_index_matrix = np.stack(index_matrix, axis=2)\n\n for bbox_size in np.unique(tiles_sizes.reshape(-1, 2), axis=0):\n eq_mat = np.all(tiles_sizes == bbox_size, axis=2)\n new_index_matrix[eq_mat] = random_state.permutation(new_index_matrix[eq_mat])\n\n new_index_matrix = np.split(new_index_matrix, 2, axis=2)\n\n old_x = index_height_matrix[new_index_matrix[0], new_index_matrix[1]].reshape(-1)\n old_y = index_width_matrix[new_index_matrix[0], new_index_matrix[1]].reshape(-1)\n\n shift_x = height_tile_sizes.reshape(-1)\n shift_y = width_tile_sizes.reshape(-1)\n\n curr_x = index_height_matrix.reshape(-1)\n curr_y = index_width_matrix.reshape(-1)\n\n tiles = np.stack([curr_x, curr_y, old_x, old_y, shift_x, shift_y], axis=1)\n\n return {\"tiles\": tiles}\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_transform_init_args_names(self):\n return (\"grid\",)\n\n\nclass Normalize(ImageOnlyTransform):\n \"\"\"Divide pixel values by 255 = 2**8 - 1, subtract mean per channel and divide by std per channel.\n\n Args:\n mean (float, list of float): mean values\n std (float, list of float): std values\n max_pixel_value (float): maximum possible pixel value\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, always_apply=False, p=1.0\n ):\n super(Normalize, self).__init__(always_apply, p)\n self.mean = mean\n self.std = std\n self.max_pixel_value = max_pixel_value\n\n def apply(self, image, **params):\n return F.normalize(image, self.mean, self.std, self.max_pixel_value)\n\n def get_transform_init_args_names(self):\n return (\"mean\", \"std\", \"max_pixel_value\")\n\n\nclass Cutout(ImageOnlyTransform):\n \"\"\"CoarseDropout of the square regions in the image.\n\n Args:\n num_holes (int): number of regions to zero out\n max_h_size (int): maximum height of the hole\n max_w_size (int): maximum width of the hole\n fill_value (int, float, lisf of int, list of float): value for dropped pixels.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n\n Reference:\n | https://arxiv.org/abs/1708.04552\n | https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py\n | https://github.com/aleju/imgaug/blob/master/imgaug/augmenters/arithmetic.py\n \"\"\"\n\n def __init__(self, num_holes=8, max_h_size=8, max_w_size=8, fill_value=0, always_apply=False, p=0.5):\n super(Cutout, self).__init__(always_apply, p)\n self.num_holes = num_holes\n self.max_h_size = max_h_size\n self.max_w_size = max_w_size\n self.fill_value = fill_value\n warnings.warn(\"This class has been deprecated. Please use CoarseDropout\", DeprecationWarning)\n\n def apply(self, image, fill_value=0, holes=[], **params):\n return F.cutout(image, holes, fill_value)\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n height, width = img.shape[:2]\n\n holes = []\n for _n in range(self.num_holes):\n y = random.randint(0, height)\n x = random.randint(0, width)\n\n y1 = np.clip(y - self.max_h_size // 2, 0, height)\n y2 = np.clip(y + self.max_h_size // 2, 0, height)\n x1 = np.clip(x - self.max_w_size // 2, 0, width)\n x2 = np.clip(x + self.max_w_size // 2, 0, width)\n holes.append((x1, y1, x2, y2))\n\n return {\"holes\": holes}\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_transform_init_args_names(self):\n return (\"num_holes\", \"max_h_size\", \"max_w_size\")\n\n\nclass CoarseDropout(ImageOnlyTransform):\n \"\"\"CoarseDropout of the rectangular regions in the image.\n\n Args:\n max_holes (int): Maximum number of regions to zero out.\n max_height (int): Maximum height of the hole.\n min_width (int): Maximum width of the hole.\n min_holes (int): Minimum number of regions to zero out. If `None`,\n `min_holes` is be set to `max_holes`. Default: `None`.\n min_height (int): Minimum height of the hole. Default: None. If `None`,\n `min_height` is set to `max_height`. Default: `None`.\n min_width (int): Minimum width of the hole. If `None`, `min_height` is\n set to `max_width`. Default: `None`.\n fill_value (int, float, lisf of int, list of float): value for dropped pixels.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n\n Reference:\n | https://arxiv.org/abs/1708.04552\n | https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py\n | https://github.com/aleju/imgaug/blob/master/imgaug/augmenters/arithmetic.py\n\n \"\"\"\n\n def __init__(\n self,\n max_holes=8,\n max_height=8,\n max_width=8,\n min_holes=None,\n min_height=None,\n min_width=None,\n fill_value=0,\n always_apply=False,\n p=0.5,\n ):\n super(CoarseDropout, self).__init__(always_apply, p)\n self.max_holes = max_holes\n self.max_height = max_height\n self.max_width = max_width\n self.min_holes = min_holes if min_holes is not None else max_holes\n self.min_height = min_height if min_height is not None else max_height\n self.min_width = min_width if min_width is not None else max_width\n self.fill_value = fill_value\n assert 0 < self.min_holes <= self.max_holes\n assert 0 < self.min_height <= self.max_height\n assert 0 < self.min_width <= self.max_width\n\n def apply(self, image, fill_value=0, holes=[], **params):\n return F.cutout(image, holes, fill_value)\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n height, width = img.shape[:2]\n\n holes = []\n for _n in range(random.randint(self.min_holes, self.max_holes + 1)):\n hole_height = random.randint(self.min_height, self.max_height + 1)\n hole_width = random.randint(self.min_width, self.max_width + 1)\n\n y1 = random.randint(0, height - hole_height)\n x1 = random.randint(0, width - hole_width)\n y2 = y1 + hole_height\n x2 = x1 + hole_width\n holes.append((x1, y1, x2, y2))\n\n return {\"holes\": holes}\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_transform_init_args_names(self):\n return (\"max_holes\", \"max_height\", \"max_width\", \"min_holes\", \"min_height\", \"min_width\")\n\n\nclass ImageCompression(ImageOnlyTransform):\n \"\"\"Decrease Jpeg, WebP compression of an image.\n\n Args:\n quality_lower (float): lower bound on the image quality.\n Should be in [0, 100] range for jpeg and [1, 100] for webp.\n quality_upper (float): upper bound on the image quality.\n Should be in [0, 100] range for jpeg and [1, 100] for webp.\n compression_type (ImageCompressionType): should be ImageCompressionType.JPEG or ImageCompressionType.WEBP.\n Defaul: ImageCompressionType.JPEG\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n class ImageCompressionType(Enum):\n JPEG = 0\n WEBP = 1\n\n def __init__(\n self,\n quality_lower=99,\n quality_upper=100,\n compression_type=ImageCompressionType.JPEG,\n always_apply=False,\n p=0.5,\n ):\n super(ImageCompression, self).__init__(always_apply, p)\n\n self.compression_type = compression_type\n low_thresh_quality_assert = 0\n\n if self.compression_type == ImageCompression.ImageCompressionType.WEBP:\n low_thresh_quality_assert = 1\n\n assert low_thresh_quality_assert <= quality_lower <= 100\n assert low_thresh_quality_assert <= quality_upper <= 100\n\n self.quality_lower = quality_lower\n self.quality_upper = quality_upper\n\n def apply(self, image, quality=100, image_type=\".jpg\", **params):\n return F.image_compression(image, quality, image_type)\n\n def get_params(self):\n image_type = \".jpg\"\n\n if self.compression_type == ImageCompression.ImageCompressionType.WEBP:\n image_type = \".webp\"\n\n return {\"quality\": random.randint(self.quality_lower, self.quality_upper), \"image_type\": image_type}\n\n def get_transform_init_args_names(self):\n return (\"quality_lower\", \"quality_upper\", \"compression_type\")\n\n\nclass JpegCompression(ImageCompression):\n \"\"\"Decrease Jpeg compression of an image.\n\n Args:\n quality_lower (float): lower bound on the jpeg quality. Should be in [0, 100] range\n quality_upper (float): upper bound on the jpeg quality. Should be in [0, 100] range\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, quality_lower=99, quality_upper=100, always_apply=False, p=0.5):\n super(JpegCompression, self).__init__(\n quality_lower=quality_lower,\n quality_upper=quality_upper,\n compression_type=ImageCompression.ImageCompressionType.JPEG,\n always_apply=always_apply,\n p=p,\n )\n warnings.warn(\"This class has been deprecated. Please use ImageCompression\", DeprecationWarning)\n\n def get_transform_init_args(self):\n return {\"quality_lower\": self.quality_lower, \"quality_upper\": self.quality_upper}\n\n\nclass RandomSnow(ImageOnlyTransform):\n \"\"\"Bleach out some pixel values simulating snow.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n snow_point_lower (float): lower_bond of the amount of snow. Should be in [0, 1] range\n snow_point_upper (float): upper_bond of the amount of snow. Should be in [0, 1] range\n brightness_coeff (float): larger number will lead to a more snow on the image. Should be >= 0\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, snow_point_lower=0.1, snow_point_upper=0.3, brightness_coeff=2.5, always_apply=False, p=0.5):\n super(RandomSnow, self).__init__(always_apply, p)\n\n assert 0 <= snow_point_lower <= snow_point_upper <= 1\n assert 0 <= brightness_coeff\n\n self.snow_point_lower = snow_point_lower\n self.snow_point_upper = snow_point_upper\n self.brightness_coeff = brightness_coeff\n\n def apply(self, image, snow_point=0.1, **params):\n return F.add_snow(image, snow_point, self.brightness_coeff)\n\n def get_params(self):\n return {\"snow_point\": random.uniform(self.snow_point_lower, self.snow_point_upper)}\n\n def get_transform_init_args_names(self):\n return (\"snow_point_lower\", \"snow_point_upper\", \"brightness_coeff\")\n\n\nclass RandomRain(ImageOnlyTransform):\n \"\"\"Adds rain effects.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n slant_lower: should be in range [-20, 20].\n slant_upper: should be in range [-20, 20].\n drop_length: should be in range [0, 100].\n drop_width: should be in range [1, 5].\n drop_color (list of (r, g, b)): rain lines color.\n blur_value (int): rainy view are blurry\n brightness_coefficient (float): rainy days are usually shady. Should be in range [0, 1].\n rain_type: One of [None, \"drizzle\", \"heavy\", \"torrestial\"]\n\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n slant_lower=-10,\n slant_upper=10,\n drop_length=20,\n drop_width=1,\n drop_color=(200, 200, 200),\n blur_value=7,\n brightness_coefficient=0.7,\n rain_type=None,\n always_apply=False,\n p=0.5,\n ):\n super(RandomRain, self).__init__(always_apply, p)\n\n assert rain_type in [\"drizzle\", \"heavy\", \"torrential\", None]\n\n assert -20 <= slant_lower <= slant_upper <= 20\n assert 1 <= drop_width <= 5\n assert 0 <= drop_length <= 100\n assert 0 <= brightness_coefficient <= 1\n\n self.slant_lower = slant_lower\n self.slant_upper = slant_upper\n\n self.drop_length = drop_length\n self.drop_width = drop_width\n self.drop_color = drop_color\n self.blur_value = blur_value\n self.brightness_coefficient = brightness_coefficient\n self.rain_type = rain_type\n\n def apply(self, image, slant=10, drop_length=20, rain_drops=[], **params):\n return F.add_rain(\n image,\n slant,\n drop_length,\n self.drop_width,\n self.drop_color,\n self.blur_value,\n self.brightness_coefficient,\n rain_drops,\n )\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n slant = int(random.uniform(self.slant_lower, self.slant_upper))\n\n height, width = img.shape[:2]\n area = height * width\n\n if self.rain_type == \"drizzle\":\n num_drops = area // 770\n drop_length = 10\n elif self.rain_type == \"heavy\":\n num_drops = width * height // 600\n drop_length = 30\n elif self.rain_type == \"torrential\":\n num_drops = area // 500\n drop_length = 60\n else:\n drop_length = self.drop_length\n num_drops = area // 600\n\n rain_drops = []\n\n for _i in range(num_drops): # If You want heavy rain, try increasing this\n if slant < 0:\n x = random.randint(slant, width)\n else:\n x = random.randint(0, width - slant)\n\n y = random.randint(0, height - drop_length)\n\n rain_drops.append((x, y))\n\n return {\"drop_length\": drop_length, \"rain_drops\": rain_drops}\n\n def get_transform_init_args_names(self):\n return (\n \"slant_lower\",\n \"slant_upper\",\n \"drop_length\",\n \"drop_width\",\n \"drop_color\",\n \"blur_value\",\n \"brightness_coefficient\",\n \"rain_type\",\n )\n\n\nclass RandomFog(ImageOnlyTransform):\n \"\"\"Simulates fog for the image\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n fog_coef_lower (float): lower limit for fog intensity coefficient. Should be in [0, 1] range.\n fog_coef_upper (float): upper limit for fog intensity coefficient. Should be in [0, 1] range.\n alpha_coef (float): transparency of the fog circles. Should be in [0, 1] range.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, fog_coef_lower=0.3, fog_coef_upper=1, alpha_coef=0.08, always_apply=False, p=0.5):\n super(RandomFog, self).__init__(always_apply, p)\n\n assert 0 <= fog_coef_lower <= fog_coef_upper <= 1\n assert 0 <= alpha_coef <= 1\n\n self.fog_coef_lower = fog_coef_lower\n self.fog_coef_upper = fog_coef_upper\n self.alpha_coef = alpha_coef\n\n def apply(self, image, fog_coef=0.1, haze_list=[], **params):\n return F.add_fog(image, fog_coef, self.alpha_coef, haze_list)\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n fog_coef = random.uniform(self.fog_coef_lower, self.fog_coef_upper)\n\n height, width = imshape = img.shape[:2]\n\n hw = max(1, int(width // 3 * fog_coef))\n\n haze_list = []\n midx = width // 2 - 2 * hw\n midy = height // 2 - hw\n index = 1\n\n while midx > -hw or midy > -hw:\n for _i in range(hw // 10 * index):\n x = random.randint(midx, width - midx - hw)\n y = random.randint(midy, height - midy - hw)\n haze_list.append((x, y))\n\n midx -= 3 * hw * width // sum(imshape)\n midy -= 3 * hw * height // sum(imshape)\n index += 1\n\n return {\"haze_list\": haze_list, \"fog_coef\": fog_coef}\n\n def get_transform_init_args_names(self):\n return (\"fog_coef_lower\", \"fog_coef_upper\", \"alpha_coef\")\n\n\nclass RandomSunFlare(ImageOnlyTransform):\n \"\"\"Simulates Sun Flare for the image\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n flare_roi (float, float, float, float): region of the image where flare will\n appear (x_min, y_min, x_max, y_max). All values should be in range [0, 1].\n angle_lower (float): should be in range [0, `angle_upper`].\n angle_upper (float): should be in range [`angle_lower`, 1].\n num_flare_circles_lower (int): lower limit for the number of flare circles.\n Should be in range [0, `num_flare_circles_upper`].\n num_flare_circles_upper (int): upper limit for the number of flare circles.\n Should be in range [`num_flare_circles_lower`, inf].\n src_radius (int):\n src_color ((int, int, int)): color of the flare\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n flare_roi=(0, 0, 1, 0.5),\n angle_lower=0,\n angle_upper=1,\n num_flare_circles_lower=6,\n num_flare_circles_upper=10,\n src_radius=400,\n src_color=(255, 255, 255),\n always_apply=False,\n p=0.5,\n ):\n super(RandomSunFlare, self).__init__(always_apply, p)\n\n (flare_center_lower_x, flare_center_lower_y, flare_center_upper_x, flare_center_upper_y) = flare_roi\n\n assert 0 <= flare_center_lower_x < flare_center_upper_x <= 1\n assert 0 <= flare_center_lower_y < flare_center_upper_y <= 1\n assert 0 <= angle_lower < angle_upper <= 1\n assert 0 <= num_flare_circles_lower < num_flare_circles_upper\n\n self.flare_center_lower_x = flare_center_lower_x\n self.flare_center_upper_x = flare_center_upper_x\n\n self.flare_center_lower_y = flare_center_lower_y\n self.flare_center_upper_y = flare_center_upper_y\n\n self.angle_lower = angle_lower\n self.angle_upper = angle_upper\n self.num_flare_circles_lower = num_flare_circles_lower\n self.num_flare_circles_upper = num_flare_circles_upper\n\n self.src_radius = src_radius\n self.src_color = src_color\n\n def apply(self, image, flare_center_x=0.5, flare_center_y=0.5, circles=[], **params):\n\n return F.add_sun_flare(image, flare_center_x, flare_center_y, self.src_radius, self.src_color, circles)\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n height, width = img.shape[:2]\n\n angle = 2 * math.pi * random.uniform(self.angle_lower, self.angle_upper)\n\n flare_center_x = random.uniform(self.flare_center_lower_x, self.flare_center_upper_x)\n flare_center_y = random.uniform(self.flare_center_lower_y, self.flare_center_upper_y)\n\n flare_center_x = int(width * flare_center_x)\n flare_center_y = int(height * flare_center_y)\n\n num_circles = random.randint(self.num_flare_circles_lower, self.num_flare_circles_upper)\n\n circles = []\n\n x = []\n y = []\n\n for rand_x in range(0, width, 10):\n rand_y = math.tan(angle) * (rand_x - flare_center_x) + flare_center_y\n x.append(rand_x)\n y.append(2 * flare_center_y - rand_y)\n\n for _i in range(num_circles):\n alpha = random.uniform(0.05, 0.2)\n r = random.randint(0, len(x) - 1)\n rad = random.randint(1, max(height // 100 - 2, 2))\n\n r_color = random.randint(max(self.src_color[0] - 50, 0), self.src_color[0])\n g_color = random.randint(max(self.src_color[0] - 50, 0), self.src_color[0])\n b_color = random.randint(max(self.src_color[0] - 50, 0), self.src_color[0])\n\n circles += [(alpha, (int(x[r]), int(y[r])), pow(rad, 3), (r_color, g_color, b_color))]\n\n return {\"circles\": circles, \"flare_center_x\": flare_center_x, \"flare_center_y\": flare_center_y}\n\n def get_transform_init_args(self):\n return {\n \"flare_roi\": (\n self.flare_center_lower_x,\n self.flare_center_lower_y,\n self.flare_center_upper_x,\n self.flare_center_upper_y,\n ),\n \"angle_lower\": self.angle_lower,\n \"angle_upper\": self.angle_upper,\n \"num_flare_circles_lower\": self.num_flare_circles_lower,\n \"num_flare_circles_upper\": self.num_flare_circles_upper,\n \"src_radius\": self.src_radius,\n \"src_color\": self.src_color,\n }\n\n\nclass RandomShadow(ImageOnlyTransform):\n \"\"\"Simulates shadows for the image\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n shadow_roi (float, float, float, float): region of the image where shadows\n will appear (x_min, y_min, x_max, y_max). All values should be in range [0, 1].\n num_shadows_lower (int): Lower limit for the possible number of shadows.\n Should be in range [0, `num_shadows_upper`].\n num_shadows_upper (int): Lower limit for the possible number of shadows.\n Should be in range [`num_shadows_lower`, inf].\n shadow_dimension (int): number of edges in the shadow polygons\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(\n self,\n shadow_roi=(0, 0.5, 1, 1),\n num_shadows_lower=1,\n num_shadows_upper=2,\n shadow_dimension=5,\n always_apply=False,\n p=0.5,\n ):\n super(RandomShadow, self).__init__(always_apply, p)\n\n (shadow_lower_x, shadow_lower_y, shadow_upper_x, shadow_upper_y) = shadow_roi\n\n assert 0 <= shadow_lower_x <= shadow_upper_x <= 1\n assert 0 <= shadow_lower_y <= shadow_upper_y <= 1\n assert 0 <= num_shadows_lower <= num_shadows_upper\n\n self.shadow_roi = shadow_roi\n\n self.num_shadows_lower = num_shadows_lower\n self.num_shadows_upper = num_shadows_upper\n\n self.shadow_dimension = shadow_dimension\n\n def apply(self, image, vertices_list=[], **params):\n return F.add_shadow(image, vertices_list)\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n height, width = img.shape[:2]\n\n num_shadows = random.randint(self.num_shadows_lower, self.num_shadows_upper)\n\n x_min, y_min, x_max, y_max = self.shadow_roi\n\n x_min = int(x_min * width)\n x_max = int(x_max * width)\n y_min = int(y_min * height)\n y_max = int(y_max * height)\n\n vertices_list = []\n\n for _index in range(num_shadows):\n vertex = []\n for _dimension in range(self.shadow_dimension):\n vertex.append((random.randint(x_min, x_max), random.randint(y_min, y_max)))\n\n vertices = np.array([vertex], dtype=np.int32)\n vertices_list.append(vertices)\n\n return {\"vertices_list\": vertices_list}\n\n def get_transform_init_args_names(self):\n return (\"shadow_roi\", \"num_shadows_lower\", \"num_shadows_upper\", \"shadow_dimension\")\n\n\nclass HueSaturationValue(ImageOnlyTransform):\n \"\"\"Randomly change hue, saturation and value of the input image.\n\n Args:\n hue_shift_limit ((int, int) or int): range for changing hue. If hue_shift_limit is a single int, the range\n will be (-hue_shift_limit, hue_shift_limit). Default: (-20, 20).\n sat_shift_limit ((int, int) or int): range for changing saturation. If sat_shift_limit is a single int,\n the range will be (-sat_shift_limit, sat_shift_limit). Default: (-30, 30).\n val_shift_limit ((int, int) or int): range for changing value. If val_shift_limit is a single int, the range\n will be (-val_shift_limit, val_shift_limit). Default: (-20, 20).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, always_apply=False, p=0.5):\n super(HueSaturationValue, self).__init__(always_apply, p)\n self.hue_shift_limit = to_tuple(hue_shift_limit)\n self.sat_shift_limit = to_tuple(sat_shift_limit)\n self.val_shift_limit = to_tuple(val_shift_limit)\n\n def apply(self, image, hue_shift=0, sat_shift=0, val_shift=0, **params):\n return F.shift_hsv(image, hue_shift, sat_shift, val_shift)\n\n def get_params(self):\n return {\n \"hue_shift\": random.uniform(self.hue_shift_limit[0], self.hue_shift_limit[1]),\n \"sat_shift\": random.uniform(self.sat_shift_limit[0], self.sat_shift_limit[1]),\n \"val_shift\": random.uniform(self.val_shift_limit[0], self.val_shift_limit[1]),\n }\n\n def get_transform_init_args_names(self):\n return (\"hue_shift_limit\", \"sat_shift_limit\", \"val_shift_limit\")\n\n\nclass Solarize(ImageOnlyTransform):\n \"\"\"Invert all pixel values above a threshold.\n\n Args:\n threshold ((int, int) or int, or (float, float) or float): range for solarizing threshold.\n If threshold is a single value, the range will be [threshold, threshold]. Default: 128.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n any\n \"\"\"\n\n def __init__(self, threshold=128, always_apply=False, p=0.5):\n super(Solarize, self).__init__(always_apply, p)\n\n if isinstance(threshold, (int, float)):\n self.threshold = to_tuple(threshold, low=threshold)\n else:\n self.threshold = to_tuple(threshold, low=0)\n\n def apply(self, image, threshold=0, **params):\n return F.solarize(image, threshold)\n\n def get_params(self):\n return {\"threshold\": random.uniform(self.threshold[0], self.threshold[1])}\n\n def get_transform_init_args_names(self):\n return (\"threshold\",)\n\n\nclass Posterize(ImageOnlyTransform):\n \"\"\"Reduce the number of bits for each color channel.\n\n Args:\n num_bits ((int, int) or int,\n or list of ints [r, g, b],\n or list of ints [[r1, r1], [g1, g2], [b1, b2]]): number of high bits.\n If num_bits is a single value, the range will be [num_bits, num_bits].\n Must be in range [0, 8]. Default: 4.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8\n \"\"\"\n\n def __init__(self, num_bits=4, always_apply=False, p=0.5):\n super(Posterize, self).__init__(always_apply, p)\n\n if isinstance(num_bits, (list, tuple)):\n if len(num_bits) == 3:\n self.num_bits = [to_tuple(i, 0) for i in num_bits]\n else:\n self.num_bits = to_tuple(num_bits, 0)\n else:\n self.num_bits = to_tuple(num_bits, num_bits)\n\n def apply(self, image, num_bits=1, **params):\n return F.posterize(image, num_bits)\n\n def get_params(self):\n if len(self.num_bits) == 3:\n return {\"num_bits\": [random.randint(i[0], i[1]) for i in self.num_bits]}\n return {\"num_bits\": random.randint(self.num_bits[0], self.num_bits[1])}\n\n def get_transform_init_args_names(self):\n return (\"num_bits\",)\n\n\nclass Equalize(ImageOnlyTransform):\n \"\"\"Equalize the image histogram.\n\n Args:\n mode (str): {'cv', 'pil'}. Use OpenCV or Pillow equalization method.\n by_channels (bool): If True, use equalization by channels separately,\n else convert image to YCbCr representation and use equalization by `Y` channel.\n mask (np.ndarray, callable): If given, only the pixels selected by\n the mask are included in the analysis. Maybe 1 channel or 3 channel array or callable.\n Function signature must include `image` argument.\n mask_params (list of str): Params for mask function.\n\n Targets:\n image\n\n Image types:\n uint8\n\n \"\"\"\n\n def __init__(self, mode=\"cv\", by_channels=True, mask=None, mask_params=(), always_apply=False, p=0.5):\n modes = [\"cv\", \"pil\"]\n if mode not in modes:\n raise ValueError(\"Unsupported equalization mode. Supports: {}. \" \"Got: {}\".format(modes, mode))\n\n super(Equalize, self).__init__(always_apply, p)\n self.mode = mode\n self.by_channels = by_channels\n self.mask = mask\n self.mask_params = mask_params\n\n def apply(self, image, mask=None, **params):\n return F.equalize(image, mode=self.mode, by_channels=self.by_channels, mask=mask)\n\n def get_params_dependent_on_targets(self, params):\n if not callable(self.mask):\n return {\"mask\": self.mask}\n\n return {\"mask\": self.mask(**params)}\n\n @property\n def targets_as_params(self):\n return [\"image\"] + list(self.mask_params)\n\n def get_transform_init_args_names(self):\n return (\"mode\", \"by_channels\")\n\n\nclass RGBShift(ImageOnlyTransform):\n \"\"\"Randomly shift values for each channel of the input RGB image.\n\n Args:\n r_shift_limit ((int, int) or int): range for changing values for the red channel. If r_shift_limit is a single\n int, the range will be (-r_shift_limit, r_shift_limit). Default: (-20, 20).\n g_shift_limit ((int, int) or int): range for changing values for the green channel. If g_shift_limit is a\n single int, the range will be (-g_shift_limit, g_shift_limit). Default: (-20, 20).\n b_shift_limit ((int, int) or int): range for changing values for the blue channel. If b_shift_limit is a single\n int, the range will be (-b_shift_limit, b_shift_limit). Default: (-20, 20).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, r_shift_limit=20, g_shift_limit=20, b_shift_limit=20, always_apply=False, p=0.5):\n super(RGBShift, self).__init__(always_apply, p)\n self.r_shift_limit = to_tuple(r_shift_limit)\n self.g_shift_limit = to_tuple(g_shift_limit)\n self.b_shift_limit = to_tuple(b_shift_limit)\n\n def apply(self, image, r_shift=0, g_shift=0, b_shift=0, **params):\n return F.shift_rgb(image, r_shift, g_shift, b_shift)\n\n def get_params(self):\n return {\n \"r_shift\": random.uniform(self.r_shift_limit[0], self.r_shift_limit[1]),\n \"g_shift\": random.uniform(self.g_shift_limit[0], self.g_shift_limit[1]),\n \"b_shift\": random.uniform(self.b_shift_limit[0], self.b_shift_limit[1]),\n }\n\n def get_transform_init_args_names(self):\n return (\"r_shift_limit\", \"g_shift_limit\", \"b_shift_limit\")\n\n\nclass RandomBrightnessContrast(ImageOnlyTransform):\n \"\"\"Randomly change brightness and contrast of the input image.\n\n Args:\n brightness_limit ((float, float) or float): factor range for changing brightness.\n If limit is a single float, the range will be (-limit, limit). Default: (-0.2, 0.2).\n contrast_limit ((float, float) or float): factor range for changing contrast.\n If limit is a single float, the range will be (-limit, limit). Default: (-0.2, 0.2).\n brightness_by_max (Boolean): If True adjust contrast by image dtype maximum,\n else adjust contrast by image mean.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, brightness_limit=0.2, contrast_limit=0.2, brightness_by_max=True, always_apply=False, p=0.5):\n super(RandomBrightnessContrast, self).__init__(always_apply, p)\n self.brightness_limit = to_tuple(brightness_limit)\n self.contrast_limit = to_tuple(contrast_limit)\n self.brightness_by_max = brightness_by_max\n\n def apply(self, img, alpha=1.0, beta=0.0, **params):\n return F.brightness_contrast_adjust(img, alpha, beta, self.brightness_by_max)\n\n def get_params(self):\n return {\n \"alpha\": 1.0 + random.uniform(self.contrast_limit[0], self.contrast_limit[1]),\n \"beta\": 0.0 + random.uniform(self.brightness_limit[0], self.brightness_limit[1]),\n }\n\n def get_transform_init_args_names(self):\n return (\"brightness_limit\", \"contrast_limit\", \"brightness_by_max\")\n\n\nclass RandomBrightness(RandomBrightnessContrast):\n \"\"\"Randomly change brightness of the input image.\n\n Args:\n limit ((float, float) or float): factor range for changing brightness.\n If limit is a single float, the range will be (-limit, limit). Default: (-0.2, 0.2).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, limit=0.2, always_apply=False, p=0.5):\n super(RandomBrightness, self).__init__(\n brightness_limit=limit, contrast_limit=0, always_apply=always_apply, p=p\n )\n warnings.warn(\"This class has been deprecated. Please use RandomBrightnessContrast\", DeprecationWarning)\n\n def get_transform_init_args(self):\n return {\"limit\": self.brightness_limit}\n\n\nclass RandomContrast(RandomBrightnessContrast):\n \"\"\"Randomly change contrast of the input image.\n\n Args:\n limit ((float, float) or float): factor range for changing contrast.\n If limit is a single float, the range will be (-limit, limit). Default: (-0.2, 0.2).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, limit=0.2, always_apply=False, p=0.5):\n super(RandomContrast, self).__init__(brightness_limit=0, contrast_limit=limit, always_apply=always_apply, p=p)\n warnings.warn(\"This class has been deprecated. Please use RandomBrightnessContrast\", DeprecationWarning)\n\n def get_transform_init_args(self):\n return {\"limit\": self.contrast_limit}\n\n\nclass Blur(ImageOnlyTransform):\n \"\"\"Blur the input image using a random-sized kernel.\n\n Args:\n blur_limit (int, (int, int)): maximum kernel size for blurring the input image.\n Should be in range [3, inf). Default: (3, 7).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, blur_limit=7, always_apply=False, p=0.5):\n super(Blur, self).__init__(always_apply, p)\n self.blur_limit = to_tuple(blur_limit, 3)\n\n def apply(self, image, ksize=3, **params):\n return F.blur(image, ksize)\n\n def get_params(self):\n return {\"ksize\": random.choice(np.arange(self.blur_limit[0], self.blur_limit[1] + 1, 2))}\n\n def get_transform_init_args_names(self):\n return (\"blur_limit\",)\n\n\nclass MotionBlur(Blur):\n \"\"\"Apply motion blur to the input image using a random-sized kernel.\n\n Args:\n blur_limit (int): maximum kernel size for blurring the input image.\n Should be in range [3, inf). Default: (3, 7).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, kernel=None, **params):\n return F.motion_blur(img, kernel=kernel)\n\n def get_params(self):\n ksize = random.choice(np.arange(self.blur_limit[0], self.blur_limit[1] + 1, 2))\n assert ksize > 2\n kernel = np.zeros((ksize, ksize), dtype=np.uint8)\n xs, xe = random.randint(0, ksize - 1), random.randint(0, ksize - 1)\n if xs == xe:\n ys, ye = random.sample(range(ksize), 2)\n else:\n ys, ye = random.randint(0, ksize - 1), random.randint(0, ksize - 1)\n cv2.line(kernel, (xs, ys), (xe, ye), 1, thickness=1)\n return {\"kernel\": kernel}\n\n\nclass MedianBlur(Blur):\n \"\"\"Blur the input image using using a median filter with a random aperture linear size.\n\n Args:\n blur_limit (int): maximum aperture linear size for blurring the input image.\n Must be odd and in range [3, inf). Default: (3, 7).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, blur_limit=7, always_apply=False, p=0.5):\n super(MedianBlur, self).__init__(blur_limit, always_apply, p)\n\n def apply(self, image, ksize=3, **params):\n return F.median_blur(image, ksize)\n\n\nclass GaussianBlur(Blur):\n \"\"\"Blur the input image using using a Gaussian filter with a random kernel size.\n\n Args:\n blur_limit (int): maximum Gaussian kernel size for blurring the input image.\n Must be zero or odd and in range [3, inf). Default: (3, 7).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, blur_limit=7, always_apply=False, p=0.5):\n super(GaussianBlur, self).__init__(blur_limit, always_apply, p)\n\n def apply(self, image, ksize=3, **params):\n return F.gaussian_blur(image, ksize)\n\n\nclass GaussNoise(ImageOnlyTransform):\n \"\"\"Apply gaussian noise to the input image.\n\n Args:\n var_limit ((float, float) or float): variance range for noise. If var_limit is a single float, the range\n will be (0, var_limit). Default: (10.0, 50.0).\n mean (float): mean of the noise. Default: 0\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, var_limit=(10.0, 50.0), mean=0, always_apply=False, p=0.5):\n super(GaussNoise, self).__init__(always_apply, p)\n if isinstance(var_limit, tuple):\n if var_limit[0] < 0:\n raise ValueError(\"Lower var_limit should be non negative.\")\n if var_limit[1] < 0:\n raise ValueError(\"Upper var_limit should be non negative.\")\n self.var_limit = var_limit\n elif isinstance(var_limit, (int, float)):\n if var_limit < 0:\n raise ValueError(\" var_limit should be non negative.\")\n\n self.var_limit = (0, var_limit)\n\n self.mean = mean\n\n def apply(self, img, gauss=None, **params):\n return F.gauss_noise(img, gauss=gauss)\n\n def get_params_dependent_on_targets(self, params):\n image = params[\"image\"]\n var = random.uniform(self.var_limit[0], self.var_limit[1])\n sigma = var ** 0.5\n random_state = np.random.RandomState(random.randint(0, 2 ** 32 - 1))\n\n gauss = random_state.normal(self.mean, sigma, image.shape)\n return {\"gauss\": gauss}\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def get_transform_init_args_names(self):\n return (\"var_limit\",)\n\n\nclass ISONoise(ImageOnlyTransform):\n \"\"\"\n Apply camera sensor noise.\n\n Args:\n color_shift (float, float): variance range for color hue change.\n Measured as a fraction of 360 degree Hue angle in HLS colorspace.\n intensity ((float, float): Multiplicative factor that control strength\n of color and luminace noise.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8\n \"\"\"\n\n def __init__(self, color_shift=(0.01, 0.05), intensity=(0.1, 0.5), always_apply=False, p=0.5):\n super(ISONoise, self).__init__(always_apply, p)\n self.intensity = intensity\n self.color_shift = color_shift\n\n def apply(self, img, color_shift=0.05, intensity=1.0, random_state=None, **params):\n return F.iso_noise(img, color_shift, intensity, np.random.RandomState(random_state))\n\n def get_params(self):\n return {\n \"color_shift\": random.uniform(self.color_shift[0], self.color_shift[1]),\n \"intensity\": random.uniform(self.intensity[0], self.intensity[1]),\n \"random_state\": random.randint(0, 65536),\n }\n\n def get_transform_init_args_names(self):\n return (\"intensity\", \"color_shift\")\n\n\nclass CLAHE(ImageOnlyTransform):\n \"\"\"Apply Contrast Limited Adaptive Histogram Equalization to the input image.\n\n Args:\n clip_limit (float or (float, float)): upper threshold value for contrast limiting.\n If clip_limit is a single float value, the range will be (1, clip_limit). Default: (1, 4).\n tile_grid_size ((int, int)): size of grid for histogram equalization. Default: (8, 8).\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8\n \"\"\"\n\n def __init__(self, clip_limit=4.0, tile_grid_size=(8, 8), always_apply=False, p=0.5):\n super(CLAHE, self).__init__(always_apply, p)\n self.clip_limit = to_tuple(clip_limit, 1)\n self.tile_grid_size = tuple(tile_grid_size)\n\n def apply(self, img, clip_limit=2, **params):\n return F.clahe(img, clip_limit, self.tile_grid_size)\n\n def get_params(self):\n return {\"clip_limit\": random.uniform(self.clip_limit[0], self.clip_limit[1])}\n\n def get_transform_init_args_names(self):\n return (\"clip_limit\", \"tile_grid_size\")\n\n\nclass ChannelDropout(ImageOnlyTransform):\n \"\"\"Randomly Drop Channels in the input Image.\n\n Args:\n channel_drop_range (int, int): range from which we choose the number of channels to drop.\n fill_value (int, float): pixel value for the dropped channel.\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, uint16, unit32, float32\n \"\"\"\n\n def __init__(self, channel_drop_range=(1, 1), fill_value=0, always_apply=False, p=0.5):\n super(ChannelDropout, self).__init__(always_apply, p)\n\n self.channel_drop_range = channel_drop_range\n\n self.min_channels = channel_drop_range[0]\n self.max_channels = channel_drop_range[1]\n\n assert 1 <= self.min_channels <= self.max_channels\n\n self.fill_value = fill_value\n\n def apply(self, img, channels_to_drop=(0,), **params):\n return F.channel_dropout(img, channels_to_drop, self.fill_value)\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n\n num_channels = img.shape[-1]\n\n if len(img.shape) == 2 or num_channels == 1:\n raise NotImplementedError(\"Images has one channel. ChannelDropout is not defined.\")\n\n if self.max_channels >= num_channels:\n raise ValueError(\"Can not drop all channels in ChannelDropout.\")\n\n num_drop_channels = random.randint(self.min_channels, self.max_channels)\n\n channels_to_drop = random.sample(range(num_channels), k=num_drop_channels)\n\n return {\"channels_to_drop\": channels_to_drop}\n\n def get_transform_init_args_names(self):\n return (\"channel_drop_range\", \"fill_value\")\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n\nclass ChannelShuffle(ImageOnlyTransform):\n \"\"\"Randomly rearrange channels of the input RGB image.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n @property\n def targets_as_params(self):\n return [\"image\"]\n\n def apply(self, img, channels_shuffled=[0, 1, 2], **params):\n return F.channel_shuffle(img, channels_shuffled)\n\n def get_params_dependent_on_targets(self, params):\n img = params[\"image\"]\n ch_arr = list(range(img.shape[2]))\n random.shuffle(ch_arr)\n return {\"channels_shuffled\": ch_arr}\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass InvertImg(ImageOnlyTransform):\n \"\"\"Invert the input image by subtracting pixel values from 255.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8\n \"\"\"\n\n def apply(self, img, **params):\n return F.invert(img)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass RandomGamma(ImageOnlyTransform):\n \"\"\"\n Args:\n gamma_limit (float or (float, float)): If gamma_limit is a single float value,\n the range will be (-gamma_limit, gamma_limit). Default: (80, 120).\n eps (float): value for exclude division by zero.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, gamma_limit=(80, 120), eps=1e-7, always_apply=False, p=0.5):\n super(RandomGamma, self).__init__(always_apply, p)\n self.gamma_limit = to_tuple(gamma_limit)\n self.eps = eps\n\n def apply(self, img, gamma=1, **params):\n return F.gamma_transform(img, gamma=gamma, eps=self.eps)\n\n def get_params(self):\n return {\"gamma\": random.randint(self.gamma_limit[0], self.gamma_limit[1]) / 100.0}\n\n def get_transform_init_args_names(self):\n return (\"gamma_limit\", \"eps\")\n\n\nclass ToGray(ImageOnlyTransform):\n \"\"\"Convert the input RGB image to grayscale. If the mean pixel value for the resulting image is greater\n than 127, invert the resulting grayscale image.\n\n Args:\n p (float): probability of applying the transform. Default: 0.5.\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def apply(self, img, **params):\n return F.to_gray(img)\n\n def get_transform_init_args_names(self):\n return ()\n\n\nclass ToFloat(ImageOnlyTransform):\n \"\"\"Divide pixel values by `max_value` to get a float32 output array where all values lie in the range [0, 1.0].\n If `max_value` is None the transform will try to infer the maximum value by inspecting the data type of the input\n image.\n\n See Also:\n :class:`~albumentations.augmentations.transforms.FromFloat`\n\n Args:\n max_value (float): maximum possible input value. Default: None.\n p (float): probability of applying the transform. Default: 1.0.\n\n Targets:\n image\n\n Image types:\n any type\n\n \"\"\"\n\n def __init__(self, max_value=None, always_apply=False, p=1.0):\n super(ToFloat, self).__init__(always_apply, p)\n self.max_value = max_value\n\n def apply(self, img, **params):\n return F.to_float(img, self.max_value)\n\n def get_transform_init_args_names(self):\n return (\"max_value\",)\n\n\nclass FromFloat(ImageOnlyTransform):\n \"\"\"Take an input array where all values should lie in the range [0, 1.0], multiply them by `max_value` and then\n cast the resulted value to a type specified by `dtype`. If `max_value` is None the transform will try to infer\n the maximum value for the data type from the `dtype` argument.\n\n This is the inverse transform for :class:`~albumentations.augmentations.transforms.ToFloat`.\n\n Args:\n max_value (float): maximum possible input value. Default: None.\n dtype (string or numpy data type): data type of the output. See the `'Data types' page from the NumPy docs`_.\n Default: 'uint16'.\n p (float): probability of applying the transform. Default: 1.0.\n\n Targets:\n image\n\n Image types:\n float32\n\n .. _'Data types' page from the NumPy docs:\n https://docs.scipy.org/doc/numpy/user/basics.types.html\n \"\"\"\n\n def __init__(self, dtype=\"uint16\", max_value=None, always_apply=False, p=1.0):\n super(FromFloat, self).__init__(always_apply, p)\n self.dtype = np.dtype(dtype)\n self.max_value = max_value\n\n def apply(self, img, **params):\n return F.from_float(img, self.dtype, self.max_value)\n\n def get_transform_init_args(self):\n return {\"dtype\": self.dtype.name, \"max_value\": self.max_value}\n\n\nclass Downscale(ImageOnlyTransform):\n \"\"\"Decreases image quality by downscaling and upscaling back.\n\n Args:\n scale_min (float): lower bound on the image scale. Should be < 1.\n scale_max (float): lower bound on the image scale. Should be .\n interpolation: cv2 interpolation method. cv2.INTER_NEAREST by default\n\n Targets:\n image\n\n Image types:\n uint8, float32\n \"\"\"\n\n def __init__(self, scale_min=0.25, scale_max=0.25, interpolation=cv2.INTER_NEAREST, always_apply=False, p=0.5):\n super(Downscale, self).__init__(always_apply, p)\n assert scale_min <= scale_max, \"Expected scale_min be less or equal scale_max, got {} {}\".format(\n scale_min, scale_max\n )\n assert scale_max < 1, \"Expected scale_max to be less than 1, got {}\".format(scale_max)\n self.scale_min = scale_min\n self.scale_max = scale_max\n self.interpolation = interpolation\n\n def apply(self, image, scale, interpolation, **params):\n return F.downscale(image, scale=scale, interpolation=interpolation)\n\n def get_params(self):\n return {\"scale\": np.random.uniform(self.scale_min, self.scale_max), \"interpolation\": self.interpolation}\n\n def get_transform_init_args_names(self):\n return \"scale_min\", \"scale_max\", \"interpolation\"\n\n\nclass Lambda(NoOp):\n \"\"\"A flexible transformation class for using user-defined transformation functions per targets.\n Function signature must include **kwargs to accept optinal arguments like interpolation method, image size, etc:\n\n Args:\n image (callable): Image transformation function.\n mask (callable): Mask transformation function.\n keypoint (callable): Keypoint transformation function.\n bbox (callable): BBox transformation function.\n always_apply (bool): Indicates whether this transformation should be always applied.\n p (float): probability of applying the transform. Default: 1.0.\n\n Targets:\n image, mask, bboxes, keypoints\n\n Image types:\n Any\n\n \"\"\"\n\n def __init__(self, image=None, mask=None, keypoint=None, bbox=None, name=None, always_apply=False, p=1.0):\n super(Lambda, self).__init__(always_apply, p)\n\n self.name = name\n self.custom_apply_fns = {target_name: F.noop for target_name in (\"image\", \"mask\", \"keypoint\", \"bbox\")}\n for target_name, custom_apply_fn in {\"image\": image, \"mask\": mask, \"keypoint\": keypoint, \"bbox\": bbox}.items():\n if custom_apply_fn is not None:\n if isinstance(custom_apply_fn, LambdaType):\n warnings.warn(\n \"Using lambda is incompatible with multiprocessing. \"\n \"Consider using regular functions or partial().\"\n )\n\n self.custom_apply_fns[target_name] = custom_apply_fn\n\n def apply(self, img, **params):\n fn = self.custom_apply_fns[\"image\"]\n return fn(img, **params)\n\n def apply_to_mask(self, mask, **params):\n fn = self.custom_apply_fns[\"mask\"]\n return fn(mask, **params)\n\n def apply_to_bbox(self, bbox, **params):\n fn = self.custom_apply_fns[\"bbox\"]\n return fn(bbox, **params)\n\n def apply_to_keypoint(self, keypoint, **params):\n fn = self.custom_apply_fns[\"keypoint\"]\n return fn(keypoint, **params)\n\n def _to_dict(self):\n if self.name is None:\n raise ValueError(\n \"To make a Lambda transform serializable you should provide the `name` argument, \"\n \"e.g. `Lambda(name='my_transform', image=<some func>, ...)`.\"\n )\n return {\"__type__\": \"Lambda\", \"__name__\": self.name}\n\n def __repr__(self):\n state = {\"name\": self.name}\n state.update(self.custom_apply_fns.items())\n state.update(self.get_base_init_args())\n return \"{name}({args})\".format(name=self.__class__.__name__, args=format_args(state))\n"
] |
[
[
"numpy.isin",
"numpy.rot90",
"numpy.split",
"numpy.take",
"numpy.linspace",
"numpy.clip",
"numpy.arange",
"numpy.indices",
"numpy.stack",
"numpy.dtype",
"numpy.argwhere",
"numpy.all",
"numpy.random.uniform",
"numpy.array",
"numpy.meshgrid",
"numpy.zeros",
"numpy.random.RandomState"
]
] |
alx/joliGAN
|
[
"f6350d78a73a2d705a22f80d97b6565f4372a3db",
"f6350d78a73a2d705a22f80d97b6565f4372a3db"
] |
[
"data/online_creation.py",
"models/modules/resnet_architecture/mobile_resnet_generator.py"
] |
[
"import math\nimport numpy as np\nimport random\nfrom PIL import Image\nimport torchvision.transforms.functional as F\nfrom torchvision.transforms import InterpolationMode\nfrom tqdm import tqdm\n\ndef crop_image(img_path,bbox_path,mask_delta,crop_delta,mask_square,crop_dim,output_dim):\n\n img = np.array(Image.open(img_path))\n\n with open(bbox_path,'r')as f:\n bboxes=[]\n \n for line in f:\n if len(line)>2:# to make sure the current line is a real bbox\n bboxes.append(line)\n elif line != \"\" or line != \" \":\n print(\"%s does not describe a bbox\"%line)\n\n if len(bboxes)==0:\n print('There is no bbox.')\n\n #Creation of a blank mask\n mask = np.zeros(img.shape[:2],dtype=np.uint8)\n\n #A bbox of reference will be used to compute the crop\n idx_bbox_ref = random.randint(0,len(bboxes)-1)\n \n for i,cur_bbox in enumerate(bboxes):\n bbox = cur_bbox.split()\n cat = int(bbox[0])\n xmin =math.floor(int(bbox[1]))\n ymin =math.floor(int(bbox[2]))\n xmax =math.floor(int(bbox[3]))\n ymax =math.floor(int(bbox[4]))\n \n if i == idx_bbox_ref:\n x_min_ref = xmin\n x_max_ref = xmax\n y_min_ref = ymin\n y_max_ref = ymax\n \n if mask_delta > 0: # increase mask box so that it can fit the reconstructed object (for semantic loss)\n ymin -= mask_delta\n ymax += mask_delta\n xmin -= mask_delta\n xmax += mask_delta\n \n if mask_square:\n sdiff = (xmax-xmin)-(ymax-ymin)\n if sdiff > 0:\n ymax += int(sdiff/2)\n ymin -= int(sdiff/2)\n else:\n xmax += -int(sdiff/2)\n xmin -= -int(sdiff/2)\n \n xmin = max(0,xmin)\n ymin = max(0,ymin)\n xmax = min(xmax,img.shape[1])\n ymax = min(ymax,img.shape[0])\n \n mask[ymin:ymax,xmin:xmax] = np.full((ymax-ymin,xmax-xmin), cat)\n\n height = y_max_ref - y_min_ref\n width = x_max_ref - x_min_ref\n \n crop_size_min = max(height,width,crop_dim-crop_delta)\n crop_size_max = max(height,width,crop_dim+crop_delta)\n\n crop_size = random.randint(crop_size_min,crop_size_max)\n\n x_crop_min = max(0,x_max_ref-crop_size)\n x_crop_max = min(x_min_ref,img.shape[1]-crop_size)\n\n y_crop_min = max(0,y_max_ref-crop_size)\n y_crop_max = min(y_min_ref,img.shape[0]-crop_size) \n\n x_crop = random.randint(x_crop_min,x_crop_max)\n y_crop = random.randint(y_crop_min,y_crop_max)\n \n img = img[y_crop:y_crop+crop_size,x_crop:x_crop+crop_size,:]\n img = Image.fromarray(img)\n img = F.resize(img,output_dim)\n \n mask = mask[y_crop:y_crop+crop_size ,x_crop:x_crop+crop_size]\n mask = Image.fromarray(mask)\n mask = F.resize(mask,output_dim, interpolation=InterpolationMode.NEAREST)\n \n return img,mask\n\ndef sanitize_paths(paths_img,paths_bb=None,mask_delta=None,crop_delta=None,mask_square=None,crop_dim=None,output_dim=None,max_dataset_size=float(\"inf\"),verbose=False):\n return_paths_img=[]\n return_paths_bb=[]\n\n if paths_bb is None:\n paths_bb = [None for k in range(len(paths_img))]\n \n for path_img,path_bb in zip(paths_img,paths_bb):\n if len(return_paths_img) >= max_dataset_size :\n break\n \n failed=False\n try:\n Image.open(path_img)\n if path_bb is not None:\n try:\n crop_image(path_img,path_bb,mask_delta=mask_delta,crop_delta=0,mask_square=mask_square,crop_dim=crop_dim+crop_delta,output_dim=output_dim)\n except Exception as e:\n failed=True\n error=e\n except Exception as e:\n failed=True\n error=e\n \n if failed :\n if verbose:\n print(\"failed\",path_img,path_bb)\n print(error)\n else:\n return_paths_img.append(path_img)\n return_paths_bb.append(path_bb)\n\n print('%d images deleted over %d,remaining %d images' % (len(paths_img)-len(return_paths_img),len(paths_img),len(return_paths_img)))\n \n return return_paths_img,return_paths_bb\n \ndef write_paths_file(img_paths,label_paths,file_path):\n try:\n with open(file_path, 'w') as f:\n for img_path,label_path in zip(img_paths,label_paths):\n if label_path is None:\n label_path=''\n cur_line = img_path + \" \" + label_path\n f.write(cur_line)\n f.write('\\n')\n except Exception as e:\n print('failed saving sanitized paths file at ',file_path)\n print(e)\n\n print('sanitized paths file saved at ',file_path)\n \n",
"import functools\n\nimport torch\nfrom torch import nn\n\nfrom models.modules.mobile_modules import SeparableConv2d\n\n#from models.networks import WBlock, NBlock\nfrom ...networks import init_net\nfrom ..utils import spectral_norm,normal_init\n\nimport math\nimport sys\n\nimport torch.nn.functional as F\n\nclass MobileResnetBlock(nn.Module):\n def __init__(self, dim, padding_type, norm_layer, dropout_rate, use_bias):\n super(MobileResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, dropout_rate, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, dropout_rate, use_bias):\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 == 'zeros':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [\n SeparableConv2d(in_channels=dim, out_channels=dim,\n kernel_size=3, padding=p, stride=1),\n norm_layer(dim), nn.ReLU(True)\n ]\n conv_block += [nn.Dropout(dropout_rate)]\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 == 'zeros':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [\n SeparableConv2d(in_channels=dim, out_channels=dim,\n kernel_size=3, padding=p, stride=1),\n norm_layer(dim)\n ]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n out = x + self.conv_block(x)\n return out\n\n\nclass MobileResnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, ngf, norm_layer=nn.InstanceNorm2d,\n dropout_rate=0.0, n_blocks=9, padding_type='reflect',\n wplus=True,\n img_size=128, img_size_dec=128,opt=None):\n assert (n_blocks >= 0)\n super(MobileResnetGenerator, self).__init__()\n self.opt=opt\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 self.encoder=MobileResnetEncoder(input_nc, output_nc, ngf, norm_layer,\n dropout_rate, n_blocks, padding_type,\n wplus,\n img_size, img_size_dec)\n\n self.decoder=MobileResnetDecoder(input_nc, output_nc, ngf, norm_layer,\n dropout_rate, n_blocks, padding_type,\n wplus,\n img_size, img_size_dec)\n \n def forward(self, input, extract_layer_ids=[], encode_only=False):\n if -1 in extract_layer_ids: #if -1 is in extract_layer_ids, the output of the encoder will be returned (features just after the last layer) \n extract_layer_ids.append(len(self.encoder))\n if len(extract_layer_ids) > 0:\n feat,feats=self.encoder(input,extract_layer_ids=extract_layer_ids, encode_only=encode_only)\n if encode_only:\n return feats\n else:\n output=self.decoder(feat)\n return output, feats # return both output and intermediate features\n else:\n \"\"\"Standard forward\"\"\"\n output = self.encoder(input)\n output = self.decoder(output)\n return output \n\nclass MobileResnetEncoder(nn.Module):\n def __init__(self, input_nc, output_nc, ngf, norm_layer=nn.InstanceNorm2d,\n dropout_rate=0, n_blocks=9, padding_type='reflect',\n wplus=True,\n img_size=128, img_size_dec=128):\n assert (n_blocks >= 0)\n self.wplus = wplus\n super(MobileResnetEncoder, 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\n n_blocks1 = n_blocks // 3\n n_blocks2 = n_blocks1\n n_blocks3 = n_blocks - n_blocks1 - n_blocks2\n\n for i in range(n_blocks1):\n model += [MobileResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer,\n dropout_rate=dropout_rate,\n use_bias=use_bias)]\n\n for i in range(n_blocks2):\n model += [MobileResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer,\n dropout_rate=dropout_rate,\n use_bias=use_bias)]\n\n for i in range(n_blocks3):\n model += [MobileResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer,\n dropout_rate=dropout_rate,\n use_bias=use_bias)]\n self.model = nn.Sequential(*model)\n \n def forward(self, input, extract_layer_ids=[],encode_only=False):\n if -1 in extract_layer_ids:\n extract_layer_ids.append(len(self.encoder))\n if len(extract_layer_ids) > 0:\n feat = input\n feats = []\n for layer_id, layer in enumerate(self.model):\n # print(layer_id, layer)\n feat = layer(feat)\n if layer_id in extract_layer_ids:\n # print(\"%d: adding the output of %s %d\" % (layer_id, layer.__class__.__name__, feat.size(1)))\n feats.append(feat)\n else:\n # print(\"%d: skipping %s %d\" % (layer_id, layer.__class__.__name__, feat.size(1)))\n pass\n if layer_id == extract_layer_ids[-1] and encode_only:\n # print('encoder only return features')\n return None,feats # return intermediate features alone; stop in the last layers\n\n return feat, feats # return both output and intermediate features\n else:\n \"\"\"Standard forward\"\"\"\n output = self.model(input)\n return output\n\nclass MobileResnetDecoder(nn.Module):\n def __init__(self, input_nc, output_nc, ngf, norm_layer=nn.InstanceNorm2d,\n dropout_rate=0, n_blocks=9, padding_type='reflect', decoder=True,\n wplus=True,\n img_size=128, img_size_dec=128):\n assert (n_blocks >= 0)\n super(MobileResnetDecoder, 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 = []\n\n n_downsampling = 2\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 self.model = nn.Sequential(*model)\n \n def forward(self, input):\n return self.model(input)\n\n\nclass MobileResnetBlock_attn(nn.Module):\n def __init__(self, channel, kernel, stride, padding_type):\n super(MobileResnetBlock_attn, self).__init__()\n self.channel = channel\n self.kernel = kernel\n self.stride = stride\n self.padding = 1\n self.padding_type = padding_type\n self.conv1 = SeparableConv2d(channel, channel, kernel, stride, padding=self.padding, padding_mode=self.padding_type)\n self.conv1_norm = nn.InstanceNorm2d(channel)\n self.conv2 = SeparableConv2d(channel, channel, kernel, stride, padding=self.padding, padding_mode=self.padding_type)\n self.conv2_norm = nn.InstanceNorm2d(channel)\n\n # weight_init\n def weight_init(self, mean, std):\n for m in self._modules:\n normal_init(self._modules[m], mean, std)\n\n def forward(self, input):\n x = F.relu(self.conv1_norm(self.conv1(input)))\n x = self.conv2_norm(self.conv2(x))\n\n return input + x\n\nclass MobileResnetGenerator_attn(nn.Module):\n # initializers\n def __init__(self, input_nc, output_nc, ngf=64, n_blocks=9, use_spectral=False,size=128,padding_type='reflect',opt=None): #nb_mask_attn : nombre de masques d'attention, nb_mask_input : nb de masques d'attention qui vont etre appliqués a l'input\n super(MobileResnetGenerator_attn, self).__init__()\n self.opt = opt\n self.input_nc = input_nc\n self.output_nc = output_nc\n self.ngf = ngf\n self.nb = n_blocks\n self.nb_mask_attn = self.opt.G_attn_nb_mask_attn\n self.padding_type = padding_type\n self.nb_mask_input = self.opt.G_attn_nb_mask_input\n self.conv1 = spectral_norm(nn.Conv2d(input_nc, ngf, 7, 1, 0),use_spectral)\n self.conv1_norm = nn.InstanceNorm2d(ngf)\n self.conv2 = spectral_norm(nn.Conv2d(ngf, ngf * 2, 3, 2, 1),use_spectral)\n self.conv2_norm = nn.InstanceNorm2d(ngf * 2)\n self.conv3 = spectral_norm(nn.Conv2d(ngf * 2, ngf * 4, 3, 2, 1),use_spectral)\n self.conv3_norm = nn.InstanceNorm2d(ngf * 4)\n\n self.resnet_blocks = []\n for i in range(n_blocks):\n self.resnet_blocks.append(MobileResnetBlock_attn(ngf * 4, 3, 1, self.padding_type))\n self.resnet_blocks[i].weight_init(0, 0.02)\n\n self.resnet_blocks = nn.Sequential(*self.resnet_blocks)\n\n self.deconv1_content = spectral_norm(nn.ConvTranspose2d(ngf * 4, ngf * 2, 3, 2, 1, 1),use_spectral)\n self.deconv1_norm_content = nn.InstanceNorm2d(ngf * 2)\n self.deconv2_content = spectral_norm(nn.ConvTranspose2d(ngf * 2, ngf, 3, 2, 1, 1),use_spectral)\n self.deconv2_norm_content = nn.InstanceNorm2d(ngf) \n self.deconv3_content = spectral_norm(nn.Conv2d(ngf, 3 * (self.nb_mask_attn-self.nb_mask_input), 7, 1, 0),use_spectral)#self.nb_mask_attn-nb_mask_input: nombre d'images générées ou les masques d'attention vont etre appliqués\n\n self.deconv1_attention = spectral_norm(nn.ConvTranspose2d(ngf * 4, ngf * 2, 3, 2, 1, 1),use_spectral)\n self.deconv1_norm_attention = nn.InstanceNorm2d(ngf * 2)\n self.deconv2_attention = spectral_norm(nn.ConvTranspose2d(ngf * 2, ngf, 3, 2, 1, 1),use_spectral)\n self.deconv2_norm_attention = nn.InstanceNorm2d(ngf)\n self.deconv3_attention = nn.Conv2d(ngf,self.nb_mask_attn, 1, 1, 0)\n \n self.tanh = nn.Tanh()\n\n # weight_init\n def weight_init(self, mean, std):\n for m in self._modules:\n normal_init(self._modules[m], mean, std)\n\n # forward method\n def forward(self, input, extract_layer_ids=[], encode_only=False,get_attention_masks=False):\n if self.padding_type == 'reflect':\n x = F.pad(input, (3, 3, 3, 3), 'reflect')\n else:\n x = F.pad(input, (3, 3, 3, 3), 'constant', 0)\n x = F.relu(self.conv1_norm(self.conv1(x)))\n x = F.relu(self.conv2_norm(self.conv2(x)))\n x = F.relu(self.conv3_norm(self.conv3(x)))\n\n if -1 in extract_layer_ids: #if -1 is in extract_layer_ids, the output of the encoder will be returned (features just after the last layer) \n extract_layer_ids.append(len(self.resnet_blocks))\n if len(extract_layer_ids) > 0:\n feat=x\n feats=[]\n for layer_id, layer in enumerate(self.resnet_blocks):\n feat = layer(feat)\n if layer_id in extract_layer_ids:\n feats.append(feat)\n if encode_only:\n return feats\n else:\n x=feat\n else:\n x = self.resnet_blocks(x)\n \n x_content = F.relu(self.deconv1_norm_content(self.deconv1_content(x)))\n x_content = F.relu(self.deconv2_norm_content(self.deconv2_content(x_content)))\n if self.padding_type == 'reflect':\n x_content = F.pad(x_content, (3, 3, 3, 3), 'reflect')\n else:\n x_content = F.pad(x_content, (3, 3, 3, 3), 'constant', 0)\n content = self.deconv3_content(x_content)\n image = self.tanh(content)\n\n images = []\n\n for i in range(self.nb_mask_attn - self.nb_mask_input):\n images.append(image[:, 3*i:3*(i+1), :, :])\n\n x_attention = F.relu(self.deconv1_norm_attention(self.deconv1_attention(x)))\n x_attention = F.relu(self.deconv2_norm_attention(self.deconv2_attention(x_attention)))\n attention = self.deconv3_attention(x_attention)\n\n softmax_ = nn.Softmax(dim=1)\n attention = softmax_(attention)\n\n attentions =[]\n \n for i in range(self.nb_mask_attn):\n attentions.append(attention[:, i:i+1, :, :].repeat(1, 3, 1, 1))\n\n outputs = []\n \n for i in range(self.nb_mask_attn-self.nb_mask_input):\n outputs.append(images[i]*attentions[i])\n for i in range(self.nb_mask_attn-self.nb_mask_input,self.nb_mask_attn):\n outputs.append(input * attentions[i])\n\n if get_attention_masks:\n return images,attentions,outputs\n \n o = outputs[0]\n for i in range(1,self.nb_mask_attn):\n o += outputs[i]\n return o\n\n def get_attention_masks(self,input):\n return self.forward(input,get_attention_masks=True)\n"
] |
[
[
"numpy.zeros",
"numpy.full"
],
[
"torch.nn.Sequential",
"torch.nn.Softmax",
"torch.nn.Dropout",
"torch.nn.ReflectionPad2d",
"torch.nn.ConvTranspose2d",
"torch.nn.Conv2d",
"torch.nn.Tanh",
"torch.nn.InstanceNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.pad",
"torch.nn.ReplicationPad2d"
]
] |
hzursa/Play-Reader
|
[
"d3486fd8306fecc92439606736edbda5a4b1e381"
] |
[
"genderbyname.py"
] |
[
"import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import MultinomialNB\ndef features(name):\n return{\n 'first-letter':name[0],\n 'first2-letter':name[0:2],\n 'first3-letter':name[0:3],\n 'last-letter':name[-1],\n 'last2-letter':name[-2:],\n 'last3-letter':name[-3:],\n\n }\nfeatures = np.vectorize(features)\nbaby= pd.read_csv(\"data/name.csv\")\nbaby.columns=['name','sex']\nbaby=baby.drop_duplicates()\nbaby.sex = pd.to_numeric(baby.sex, errors='coerce')\nbaby.head()\ndf_X=features(baby.name)\ndf_y = baby.sex\ndfX_train,dfX_test,dfy_train,dfy_test = train_test_split(df_X,df_y,test_size = 0.2)\ndv = DictVectorizer()\ndv.fit_transform(dfX_train)\ndclf = MultinomialNB()\nmy_xfeatures = dv.transform(dfX_train)\ndclf.fit(my_xfeatures,dfy_train)\nmnames=[\"king\",\"sir\",\"lord\",\"prince\"]\nfnames=[\"queen\",\"lady\",\"princess\",\"nurse\"]\ndef genderclassify(name):\n for mname in mnames:\n if mname in name:\n return 0\n for fname in fnames:\n if fname in name:\n return 1\n vector = dv.transform(features([name])).toarray()\n return dclf.predict(vector)[0]\n \n"
] |
[
[
"pandas.read_csv",
"sklearn.naive_bayes.MultinomialNB",
"sklearn.model_selection.train_test_split",
"numpy.vectorize",
"sklearn.feature_extraction.DictVectorizer",
"pandas.to_numeric"
]
] |
MasazI/python-r-stan-bayesian-model
|
[
"05a224958a3f5cbea207001465ac12b6862d9d9f"
] |
[
"2-5.py"
] |
[
"###############\n#\n# Translate R to Python Copyright (c) 2019 Masahiro Imai Released under the MIT license\n#\n###############\n\nimport os\n\nimport pystan\nimport pandas\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nimport arviz as az\n\nfile_beer_sales_1 = pandas.read_csv('2-4-1-beer-sales-1.csv')\nprint(file_beer_sales_1.head())\n\nsample_size = len(file_beer_sales_1)\n\nstan_data = {\n 'N': sample_size,\n 'sales':file_beer_sales_1['sales']\n}\n\nif not os.path.exists('2-4-1-calc-mean-variance.pkl'):\n print(\"Please execute 2-4.py in advance.\")\n exit()\n\nsm = pickle.load(open('2-4-1-calc-mean-variance.pkl', 'rb'))\nmcmc_result = sm.sampling(\n data=stan_data,\n seed=1,\n chains=4,\n iter=2000,\n warmup=1000,\n thin=1\n)\n\n# reference http://statmodeling.hatenablog.com/entry/pystan-rstanbook-chap5-1\nms = mcmc_result.extract(permuted=False, inc_warmup=False)\n\nprint(type(ms))\nprint(ms.shape)\n\nprint(ms[0, 0, 0])\nprint(ms[:, 0, 0])\nprint(ms[:, 0, 0].shape)\nprint(ms[:, :, 0].shape)\n\nmu_mcmc_vec = ms[:, :, 0].reshape(4000)\nprint(mu_mcmc_vec.shape)\n\n# median\nprint(np.median(mu_mcmc_vec))\n\n# mean\nprint(np.mean(mu_mcmc_vec))\n\nprint(np.quantile(mu_mcmc_vec, q=0.025))\nprint(np.quantile(mu_mcmc_vec, q=0.975))\n\niter_from = mcmc_result.sim['warmup']\niter_range = np.arange(0, ms.shape[0])\n\nparaname = mcmc_result.sim['fnames_oi']\n\nprint(paraname)\n\npalette = sns.color_palette()\nplt.figure()\n\n# traceplot\nfor pi in range(len(paraname)):\n plt.subplot(3, 1, pi+1)\n plt.tight_layout()\n [plt.plot(iter_range + 1, ms[iter_range,ci,pi], color=palette[ci]) for ci in range(ms.shape[1])]\n plt.title(paraname[pi])\nplt.show()\n\n#\nfor pi in range(len(paraname)):\n plt.subplot(3, 1, pi+1)\n plt.tight_layout()\n [sns.kdeplot(ms[iter_range,ci,pi], color=palette[ci]) for ci in range(ms.shape[1])]\n plt.title(paraname[pi])\nplt.show()\n\nmcmc_result.plot()\n\nplt.show()\n\n# using arviz instead of bayesplot\n#az.plot_density(data=mcmc_result, var_names=['mu']);\naz.plot_trace(data=mcmc_result)\nplt.show()\n\naz.plot_forest(data=mcmc_result, kind='ridgeplot', combined=True)\nplt.show()\n\naz.plot_autocorr(data=mcmc_result)\nplt.show()\n\n"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"numpy.arange",
"numpy.median",
"numpy.quantile",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"numpy.mean",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
quic-bharathr/aimet
|
[
"c6ffd3c31c290fe0913b50831d58534f6df61d76",
"363308217dca3fc52644bdda31e69e356397adaf"
] |
[
"NightlyTests/torch/test_quantize_resnet18.py",
"TrainingExtensions/tensorflow/src/python/aimet_tensorflow/examples/test_models.py"
] |
[
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n# \n# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. 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 notice, \n# this list of conditions and the following disclaimer in the documentation \n# and/or other materials provided with the distribution.\n# \n# 3. Neither the name of the copyright holder nor the names of its contributors \n# may be used to endorse or promote products derived from this software \n# without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# \n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport unittest\nimport copy\nimport torch.optim as optim\nimport numpy as np\nfrom torchvision import models\nfrom torch.optim import lr_scheduler\n\nfrom aimet_torch.quantsim import QuantizationSimModel\nfrom aimet_torch.qc_quantize_op import QcQuantizeWrapper\n\nfrom aimet_torch.examples.imagenet_dataloader import ImageNetDataLoader\nfrom aimet_torch.utils import IterFirstX, is_leaf_module\nfrom aimet_torch.examples.supervised_classification_pipeline import create_stand_alone_supervised_classification_evaluator,\\\n create_supervised_classification_trainer\n\ntwo_class_image_dir = './data/tiny-imagenet-2'\nimage_size = 224\nbatch_size = 50\nnum_workers = 1\n\n\ndef model_train(model, epochs, callback=None):\n \"\"\"\n :param model: model\n :param epochs: number of epochs\n :return: accuracy after each epoch on training , validation data\n \"\"\"\n\n data_loader = ImageNetDataLoader(two_class_image_dir, image_size, batch_size, num_workers)\n criterion = nn.CrossEntropyLoss().cuda()\n lr = 0.01\n momentum = 0.9\n lr_step_size = 0.01\n lr_gamma = 0.01\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=lr_step_size, gamma=lr_gamma)\n\n trainer, evaluator = create_supervised_classification_trainer(model=model, loss_fn=criterion, optimizer=optimizer,\n val_loader=data_loader.val_loader,\n learning_rate_scheduler=exp_lr_scheduler,\n use_cuda=True,\n callback=callback)\n\n trainer.run(data_loader.train_loader, max_epochs=epochs)\n return trainer.state.metrics['top_1_accuracy'], evaluator.state.metrics['top_1_accuracy']\n\n\ndef model_eval(model, early_stopping_iterations):\n \"\"\"\n :param model: model to be evaluated\n :param early_stopping_iterations: if None, data loader will iterate over entire validation data\n :return: top_1_accuracy on validation data\n \"\"\"\n\n use_cuda = next(model.parameters()).is_cuda\n\n data_loader = ImageNetDataLoader(two_class_image_dir, image_size, batch_size, num_workers)\n if early_stopping_iterations is not None:\n # wrapper around validation data loader to run only 'X' iterations to save time\n val_loader = IterFirstX(data_loader.val_loader, early_stopping_iterations)\n else:\n # iterate over entire validation data set\n val_loader = data_loader.val_loader\n\n criterion = nn.CrossEntropyLoss().cuda()\n evaluator = create_stand_alone_supervised_classification_evaluator(model, criterion, use_cuda=use_cuda)\n evaluator.run(val_loader)\n return evaluator.state.metrics['top_1_accuracy']\n\n\ndef check_if_layer_weights_are_updating(trainer, model):\n \"\"\"\n :param trainer: The handler function's first argument is the 'Engine' object it is bound to\n :param model: model\n \"\"\"\n # Creating an alias for easier reference\n f = check_if_layer_weights_are_updating\n\n print(\"\")\n print(\"checking weights for iteration = {}\".format(trainer.state.iteration))\n\n # get the initial weight values of conv1 layer of first block\n conv1_w_value = model.classifier[0]._module_to_wrap.weight\n\n if trainer.state.iteration != 1:\n assert not np.allclose(conv1_w_value.cpu().detach().numpy(), f.conv1_w_value_old.numpy())\n else:\n f.conv1_w_value_old = conv1_w_value.cpu().detach().clone()\n\n\nclass QuantizeAcceptanceTests(unittest.TestCase):\n\n def test_quantize_resnet18(self):\n\n torch.cuda.empty_cache()\n\n # Train the model using tiny imagenet data\n model = models.resnet18(pretrained=False)\n _ = model_train(model, epochs=2)\n model = model.to(torch.device('cuda'))\n\n # layers_to_ignore = [model.conv1]\n sim = QuantizationSimModel(model, quant_scheme='tf', default_param_bw=8, default_output_bw=8)\n\n print(sim.model)\n\n # If 'iterations'set to None, will iterate over all the validation data\n sim.compute_encodings(model_eval, forward_pass_callback_args=400)\n quantized_model_accuracy = model_eval(model=sim.model, early_stopping_iterations=None)\n\n print(\"Quantized model accuracy=\", quantized_model_accuracy)\n self.assertGreaterEqual(quantized_model_accuracy, 0.5)\n\n def test_memory_leak_during_quantization_train(self):\n\n # First get baseline numbers\n base_pre_model_load_mark = torch.cuda.memory_allocated()\n model = models.vgg16(pretrained=True)\n model = model.to(torch.device('cuda'))\n base_model_loaded_mark = torch.cuda.memory_allocated()\n\n _ = model_train(model=model, epochs=2)\n base_model_train_mark = torch.cuda.memory_allocated()\n base_model_train_delta = base_model_train_mark - base_model_loaded_mark\n\n print(\"Usage Report ------\")\n print(\"Model pre-load = {}\".format(base_pre_model_load_mark))\n print(\"Model load = {}\".format(base_model_loaded_mark))\n print(\"Model train delta = {}\".format(base_model_train_delta))\n\n del model\n baseline_leaked_mem = torch.cuda.memory_allocated() - base_pre_model_load_mark\n print(\"Leaked during train = {}\".format(baseline_leaked_mem))\n\n model = models.vgg16(pretrained=True)\n model = model.to(torch.device('cuda'))\n base_model_loaded_mark = torch.cuda.memory_allocated()\n #\n # # Now use AIMET\n sim = QuantizationSimModel(model, quant_scheme='tf_enhanced', default_param_bw=8, default_output_bw=4)\n sim.compute_encodings(model_eval, forward_pass_callback_args=1)\n\n print(sim.model)\n aimet_model_quantize_mark = torch.cuda.memory_allocated()\n aimet_model_quantize_delta = aimet_model_quantize_mark - base_model_loaded_mark\n\n _ = model_train(model=sim.model, epochs=2,\n callback=check_if_layer_weights_are_updating)\n\n aimet_model_train_mark = torch.cuda.memory_allocated()\n aimet_model_train_delta = aimet_model_train_mark - aimet_model_quantize_mark\n leaked_memory = aimet_model_train_delta - base_model_train_delta + baseline_leaked_mem\n\n print(\"\")\n print(\"Usage Report ------\")\n print(\"Model load = {}\".format(base_model_loaded_mark))\n print(\"AIMET quantize delta = {}\".format(aimet_model_quantize_delta))\n print(\"AIMET train delta = {}\".format(aimet_model_train_delta))\n print(\"Leaked memory = {}\".format(leaked_memory))\n\n # During training, the memory is held for a longer duration by PyTorch.\n # Often, this test fails with the following assert failing.\n # When the test is run individually, this test may still fail.\n # The tolerance is bumped up to take care of the situation where all tests are run.\n self.assertLessEqual(leaked_memory, 1000000)\n\n def test_memory_leak_during_quantization_eval(self):\n\n # First get baseline numbers\n base_pre_model_load_mark = torch.cuda.memory_allocated()\n model = models.vgg16(pretrained=True)\n model = model.to(torch.device('cuda'))\n base_model_loaded_mark = torch.cuda.memory_allocated()\n\n _ = model_eval(model=model, early_stopping_iterations=10)\n base_model_eval_mark = torch.cuda.memory_allocated()\n base_model_eval_delta = base_model_eval_mark - base_model_loaded_mark\n\n print(\"Usage Report ------\")\n print(\"Model pre-load = {}\".format(base_pre_model_load_mark))\n print(\"Model load = {}\".format(base_model_loaded_mark))\n print(\"Model eval delta = {}\".format(base_model_eval_delta))\n\n del model\n print(\"Leaked during eval = {}\".format(torch.cuda.memory_allocated() - base_pre_model_load_mark))\n\n model = models.vgg16(pretrained=True)\n model = model.to(torch.device('cuda'))\n base_model_loaded_mark = torch.cuda.memory_allocated()\n\n # Now use AIMET\n sim = QuantizationSimModel(model, quant_scheme='tf_enhanced', default_param_bw=8, default_output_bw=4)\n sim.compute_encodings(model_eval, forward_pass_callback_args=1)\n\n aimet_model_quantize_mark = torch.cuda.memory_allocated()\n aimet_model_quantize_delta = aimet_model_quantize_mark - base_model_loaded_mark\n\n for i in range(1):\n _ = model_eval(model=sim.model, early_stopping_iterations=10)\n\n aimet_model_eval_mark = torch.cuda.memory_allocated()\n aimet_model_eval_delta = aimet_model_eval_mark - aimet_model_quantize_mark\n\n print(\"\")\n print(\"Usage Report ------\")\n print(\"Model load = {}\".format(base_model_loaded_mark))\n print(\"AIMET quantize delta = {}\".format(aimet_model_quantize_delta))\n print(\"AIMET eval delta = {}\".format(aimet_model_eval_delta))\n\n self.assertEqual(0, aimet_model_eval_delta)\n\n\n\n",
"# /usr/bin/env python3.5\n# -*- mode: python -*-\n# =============================================================================\n# @@-COPYRIGHT-START-@@\n#\n# Copyright (c) 2020, Qualcomm Innovation Center, Inc. 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 notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# @@-COPYRIGHT-END-@@\n# =============================================================================\n\"\"\" Models for use in unit testing \"\"\"\n\n# pylint: disable=no-name-in-module\n# pylint: disable=no-member\n# Including above pylint disables since pylint complains about certain module members not found, when they actually\n# are there.\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense, Conv2D, BatchNormalization, Flatten, AvgPool2D, MaxPool2D\n\n\ndef single_residual():\n \"\"\" Function for returning single residual model \"\"\"\n\n inputs = tf.keras.Input(shape=(16, 16, 3,))\n x = tf.keras.layers.Conv2D(16, (3, 3))(inputs)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x)\n x = tf.nn.relu(x)\n x = tf.keras.layers.MaxPool2D()(x)\n residual = x\n residual = tf.keras.layers.Conv2D(8, (1, 1))(residual)\n residual = tf.nn.relu(residual)\n\n x = tf.keras.layers.Conv2D(8, (1, 1))(x)\n x = tf.keras.layers.Conv2D(8, (1, 1))(x)\n x = tf.keras.layers.BatchNormalization(momentum=.4, epsilon=.25)(x)\n x = tf.add(x, residual)\n x = tf.nn.relu(x)\n\n x = tf.keras.layers.Conv2D(8, (3, 3))(x)\n x = tf.keras.layers.AvgPool2D()(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(2, activation=tf.nn.softmax, name=\"single_residual\")(x)\n\n return outputs\n\n\ndef keras_model():\n \"\"\" Function for returning a basic keras model \"\"\"\n\n model = Sequential([\n Conv2D(8, (2, 2), input_shape=(16, 16, 3,)),\n BatchNormalization(momentum=.3, epsilon=.65),\n AvgPool2D(),\n MaxPool2D(),\n BatchNormalization(momentum=.4, epsilon=.25),\n Conv2D(4, (2, 2), activation=tf.nn.tanh, kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=.5)),\n Flatten(),\n Dense(2, activation='softmax', name=\"keras_model\")])\n return model\n\n\ndef keras_model_functional():\n \"\"\" Function for returning basic keras model defined functionally \"\"\"\n is_training = tf.placeholder_with_default(tf.constant(True), shape=(), name='is_training')\n inputs = tf.keras.Input(shape=(32, 32, 3,))\n x = tf.keras.layers.Conv2D(32, (3, 3))(inputs)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=True)\n with tf.variable_scope(\"scope_1\"):\n x = tf.keras.layers.Conv2D(16, (2, 2), activation=tf.nn.tanh)(x)\n x = tf.keras.layers.BatchNormalization(momentum=.4, epsilon=.25)(x, training=is_training)\n x = tf.keras.layers.Conv2D(8, (2, 2), activation=tf.nn.tanh)(x)\n x = tf.keras.layers.BatchNormalization(momentum=.5, epsilon=.35)(x, training=False)\n x = tf.keras.layers.Conv2D(4, (2, 2), activation=tf.nn.relu6)(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"keras_model_functional\")(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\ndef tf_slim_basic_model(inp):\n \"\"\" Function for returning basic tf slim model \"\"\"\n is_training = tf.placeholder_with_default(tf.constant(True), shape=(), name='is_training')\n net = slim.conv2d(inp, 32, [3, 3])\n net = slim.batch_norm(net, decay=.7, epsilon=.65, is_training=True)\n net = slim.conv2d(net, 16, [2, 2])\n net = slim.batch_norm(net, decay=.6, epsilon=.25, scale=True, is_training=is_training)\n net = slim.conv2d(net, 8, [2, 2])\n net = slim.batch_norm(net, decay=.5, epsilon=.35, scale=True, is_training=False)\n net = slim.conv2d(net, 4, [2, 2])\n net = slim.flatten(net)\n net = slim.fully_connected(net, num_outputs=10, activation_fn=tf.nn.softmax, scope=\"tf_slim_model\")\n return net\n\n\ndef tf_slim_with_softmax(inp):\n \"\"\" Function for returning tf slim model ending in softmax \"\"\"\n net = slim.conv2d(inp, 32, [3, 3])\n net = slim.batch_norm(net, decay=.7, epsilon=.65, is_training=False)\n net = slim.conv2d(net, 16, [2, 2])\n net = slim.batch_norm(net, decay=.6, epsilon=.25, is_training=False)\n net = slim.softmax(net)\n return net\n\n\ndef split_and_concat_model():\n \"\"\" Function for returning keras model with splits and concats \"\"\"\n x = tf.keras.Input(shape=[224, 224, 3, ])\n # TODO: implement split for the following commented out method of splitting\n # y1 = x[:, :100, :, :]\n # y2 = x[:, 101:, :, :]\n y1, y2 = tf.split(x, [100, 124], 1)\n y1 = tf.nn.relu(y1)\n y2 = tf.keras.layers.BatchNormalization()(y2)\n z = tf.keras.layers.concatenate([y1, y2], axis=1)\n z = tf.keras.layers.Flatten()(z)\n output = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"split_and_concat_model\")(z)\n return output\n\n\ndef concat_model():\n \"\"\" Function for returning model with concat \"\"\"\n x = tf.keras.Input(shape=[10, 10, 3, ])\n x1 = tf.keras.layers.Conv2D(5, (2, 2))(x)\n x2 = tf.keras.layers.Conv2D(6, (2, 2))(x)\n x3 = tf.keras.layers.Conv2D(7, (2, 2))(x)\n z = tf.keras.layers.concatenate([x2, x1, x3], axis=-1)\n z1 = tf.keras.layers.Conv2D(10, (2, 2))(z)\n z2 = tf.keras.layers.Conv2D(10, (2, 2))(z)\n z = tf.add(z1, z2)\n z = tf.keras.layers.Flatten()(z)\n output = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"concat_model\")(z)\n return output\n\n\ndef upsample_model():\n \"\"\" Returns a model that can be used to test inserting upsample ops \"\"\"\n\n inputs = tf.keras.Input(shape=(16, 16, 3,))\n x = tf.keras.layers.Conv2D(8, (2, 2))(inputs)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x)\n x = tf.nn.relu(x)\n x = tf.keras.layers.MaxPool2D()(x)\n residual = x\n\n x = tf.keras.layers.Conv2D(8, (1, 1))(x)\n x = tf.keras.layers.Conv2D(8, (1, 1))(x)\n x = tf.keras.layers.BatchNormalization(momentum=.4, epsilon=.25)(x)\n x = tf.add(x, residual)\n x = tf.nn.relu(x)\n\n x = tf.keras.layers.Conv2D(4, (1, 1))(x)\n x = tf.keras.layers.AvgPool2D()(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(2, activation=tf.nn.softmax, name=\"upsample_model\")(x)\n return outputs\n\n\ndef dropout_keras_model():\n \"\"\" Returns a keras model with a dropout module (also tests identity op, which is how dropout is represented when\n model is in inference mode \"\"\"\n\n inputs = tf.keras.Input(shape=(10, 10, 3,))\n x = tf.keras.layers.Conv2D(16, (3, 3))(inputs)\n x = tf.keras.layers.Dropout(rate=.4)(x)\n x = tf.identity(x)\n x = tf.keras.layers.Conv2D(8, (2, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"dropout_keras_model\")(x)\n return outputs\n\n\ndef dropout_slim_model():\n \"\"\" Returns a slim model with a dropout module (also tests identity op, which is how dropout is represented when\n model is in inference mode \"\"\"\n\n inputs = tf.keras.Input(shape=(10, 10, 3,))\n x = slim.conv2d(inputs, 16, [3, 3])\n x = slim.dropout(x, keep_prob=.6)\n x = tf.identity(x)\n x = slim.conv2d(x, 8, [2, 2])\n x = slim.flatten(x)\n outputs = slim.fully_connected(x, num_outputs=10, activation_fn=tf.nn.softmax, scope=\"dropout_slim_model\")\n return outputs\n\n\ndef model_with_postprocessing_nodes():\n \"\"\" Returns a model with postprocessing nodes, that is expected to break mask propagation if included in\n connected graph \"\"\"\n\n inputs = tf.keras.Input(shape=(10, 10, 3,))\n x = tf.keras.layers.Conv2D(16, (3, 3))(inputs)\n _ = tf.keras.layers.MaxPool2D()(x)\n x = tf.keras.layers.Conv2D(8, (2, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n x = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"model_with_postprocessing_nodes\")(x)\n\n labels_placeholder = tf.placeholder_with_default(tf.constant(1, shape=(1, 10)),\n shape=[None, 10],\n name='labels')\n\n confidences = tf.nn.softmax(x, axis=1, name='confidences')\n categorical_preds = tf.argmax(confidences, axis=1, name='categorical_preds')\n categorical_labels = tf.argmax(labels_placeholder, axis=1, name='categorical_labels')\n correct_predictions = tf.equal(categorical_labels, categorical_preds)\n _ = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='top1-acc')\n _ = tf.reduce_mean(tf.cast(tf.nn.in_top_k(predictions=confidences,\n targets=tf.cast(categorical_labels, tf.int32),\n k=5), tf.float32), name='top5-acc')\n\n\ndef pad_model():\n \"\"\" Returns a model with various pad modules \"\"\"\n\n inputs = tf.keras.Input(shape=(10, 10, 3,))\n x = tf.keras.layers.Conv2D(16, (1, 1))(inputs)\n x = tf.pad(x, tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]]))\n x = tf.keras.layers.Conv2D(8, (2, 2))(x)\n x = tf.pad(x, tf.constant([[0, 0], [1, 1], [1, 1], [1, 1]]))\n x = tf.keras.layers.Conv2D(8, (2, 2))(x)\n x = tf.pad(x, tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]]), constant_values=2)\n x = tf.keras.layers.Conv2D(8, (2, 2))(x)\n x = tf.pad(x, tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]]), mode='SYMMETRIC')\n x = tf.keras.layers.Conv2D(8, (2, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"pad_model\")(x)\n return outputs\n\n\ndef depthwise_conv2d_model():\n \"\"\" Returns a model with depthwise conv2d \"\"\"\n\n inputs = tf.keras.Input(shape=(10, 10, 3,))\n x = tf.keras.layers.Conv2D(16, (1, 1))(inputs)\n x = tf.keras.layers.SeparableConv2D(10, (2, 2))(x)\n x = tf.keras.layers.DepthwiseConv2D(3, (1, 1))(x)\n x = tf.keras.layers.Conv2D(8, (1, 1))(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"depthwise_conv2d_model\")(x)\n return outputs\n\n\ndef multiple_input_model():\n \"\"\" Returns a model with multiple inputs \"\"\"\n\n input1 = tf.keras.Input(name='input1', shape=(10, 10, 3))\n input2 = tf.keras.Input(name='input2', shape=(12, 12, 3))\n x1 = tf.keras.layers.Conv2D(8, (1, 1), name='conv1a')(input1)\n x2 = tf.keras.layers.Conv2D(8, (3, 3), name='conv1b')(input2)\n x = tf.keras.layers.add([x1, x2])\n x = tf.keras.layers.Conv2D(4, (1, 1), name='conv2')(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(2, activation=tf.nn.softmax, name=\"multiple_input_model\")(x)\n\n return outputs\n\n\ndef minimum_maximum_model():\n \"\"\" Returns a model with minimum and maximum operations \"\"\"\n inputs = tf.keras.Input(shape=(32, 32, 3,))\n x = tf.keras.layers.Conv2D(32, (3, 3))(inputs)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=False)\n x = tf.minimum(x, .2)\n x = tf.maximum(x, .5)\n x = tf.keras.layers.Conv2D(16, (2, 2), activation=tf.nn.tanh)(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"minimum_maximum_model\")(x)\n return outputs\n\n\ndef model_with_upsample_already_present():\n \"\"\" Function for returning basic keras model defined functionally \"\"\"\n inputs = tf.keras.Input(shape=(8, 8, 3,))\n x = tf.keras.layers.Conv2D(8, (3, 3))(inputs)\n with tf.name_scope(\"upsample\"):\n unstacked = tf.unstack(x, axis=-1)\n zeros = tf.zeros_like(unstacked[0])\n current_index = 0\n\n for index in [0, 3, 4, 6, 7, 8, 9, 11]:\n while current_index < index:\n unstacked.insert(current_index, zeros)\n current_index += 1\n current_index += 1\n\n stack = tf.stack(unstacked, axis=-1)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(stack, training=False)\n x = tf.keras.layers.Conv2D(4, (2, 2), activation=tf.nn.tanh)(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"model_with_upsample_already_present\")(x)\n return outputs\n\n\ndef model_with_multiple_downsamples():\n \"\"\" Function returning model containing multiple downsamples, in different name scopes \"\"\"\n inputs = tf.keras.Input(shape=(8, 8, 10,))\n with tf.name_scope('downsample'):\n gather_1 = tf.gather(inputs, [1, 2, 3, 4, 5, 6, 7, 8], axis=-1)\n conv2d = tf.keras.layers.Conv2D(16, [2, 2])(gather_1)\n # gather_2 will be in same downsample namescope, but named GatherV2_1\n gather_2 = tf.gather(conv2d, [1, 2, 3, 4, 5, 6], axis=-1)\n with tf.name_scope('downsample'):\n conv2d_1 = tf.keras.layers.Conv2D(16, [2, 2])(gather_2)\n # gather_3 will be in a different namescope, downsample_1\n gather_3 = tf.gather(conv2d_1, [1, 2, 3, 4], axis=-1)\n conv2d_2 = tf.keras.layers.Conv2D(16, [2, 2])(gather_3)\n x = tf.keras.layers.Flatten()(conv2d_2)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"multiple_downsamples\")(x)\n return outputs\n\n\ndef model_with_multiple_training_tensors():\n \"\"\" Return model with multiple batchnorms using different training tensors \"\"\"\n\n inputs = tf.keras.Input(shape=(32, 32, 3,))\n # Should create a keras learning phase tensor\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(inputs)\n is_training = tf.placeholder_with_default(False, [], name='is_training')\n # Should attach to second is_training tensor\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=is_training)\n is_training_2 = tf.placeholder_with_default(False, [], name='is_training_2')\n # Should attach to third is_training_2 tensor\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=is_training_2)\n # Should not have a training tensor\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=True)\n # Should not have a training tensor\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x, training=False)\n return x\n\n\ndef model_with_three_convs():\n \"\"\" Return model with three conv layers \"\"\"\n\n inputs = tf.keras.Input(shape=(8, 8, 3,))\n x = tf.keras.layers.Conv2D(8, (2, 2))(inputs)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x)\n x = tf.keras.layers.Conv2D(6, (2, 2))(x)\n x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(x)\n x = tf.keras.layers.Conv2D(4, (2, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10, activation=tf.nn.softmax, name=\"three_convs\")(x)\n return outputs\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.cuda.empty_cache",
"torch.device",
"torch.cuda.memory_allocated",
"torch.optim.lr_scheduler.StepLR"
],
[
"tensorflow.python.keras.layers.Flatten",
"tensorflow.python.keras.layers.Dense",
"tensorflow.stack",
"tensorflow.equal",
"tensorflow.minimum",
"tensorflow.cast",
"tensorflow.contrib.slim.flatten",
"tensorflow.python.keras.layers.Conv2D",
"tensorflow.python.keras.layers.BatchNormalization",
"tensorflow.keras.Input",
"tensorflow.placeholder_with_default",
"tensorflow.keras.layers.Conv2D",
"tensorflow.gather",
"tensorflow.add",
"tensorflow.name_scope",
"tensorflow.python.keras.layers.AvgPool2D",
"tensorflow.keras.layers.AvgPool2D",
"tensorflow.python.keras.layers.MaxPool2D",
"tensorflow.argmax",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.DepthwiseConv2D",
"tensorflow.unstack",
"tensorflow.keras.layers.Dense",
"tensorflow.identity",
"tensorflow.keras.Model",
"tensorflow.zeros_like",
"tensorflow.contrib.slim.fully_connected",
"tensorflow.keras.layers.add",
"tensorflow.contrib.slim.softmax",
"tensorflow.split",
"tensorflow.contrib.slim.batch_norm",
"tensorflow.nn.relu",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.contrib.slim.dropout",
"tensorflow.maximum",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.layers.MaxPool2D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.SeparableConv2D",
"tensorflow.contrib.slim.conv2d",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.variable_scope",
"tensorflow.keras.layers.Dropout"
]
] |
NovemberChopin/GuideLine
|
[
"d49b3b527a5e54f3ee734c8d5245efb89150d594"
] |
[
"BSpline/parameter_selection.py"
] |
[
"import numpy as np\n\n# 参数域均匀分布\ndef uniform_spaced(n):\n '''\n Calculate parameters using the uniform spaced method.\n :param n: the number of the data points\n :return: parameters\n '''\n parameters = np.linspace(0, 1, n)\n return parameters\n\n# 根据数据点弦长关系分割参数域\ndef chord_length(n, P):\n '''\n Calculate parameters using the chord length method.\n :param n: the number of the data points\n :param P: data points\n :return: parameters\n '''\n parameters = np.zeros((1, n))\n for i in range(1, n):\n dis = 0\n for j in range(len(P)):\n dis = dis + (P[j][i] - P[j][i-1])**2\n dis = np.sqrt(dis)\n parameters[0][i] = parameters[0][i-1] + dis\n for i in range(1, n):\n parameters[0][i] = parameters[0][i]/parameters[0][n-1]\n return parameters[0]\n\n#根据数据点弦长的指数结果分割参数域; 通过计算得到的参数域,可以通过求取平均的方式计算节点向量。 \ndef centripetal(n, P):\n '''\n Calculate parameters using the centripetal method.\n :param n: the number of data points\n :param P: data points\n :return: parameters\n '''\n a = 0.5\n parameters = np.zeros((1, n))\n for i in range(1, n):\n dis = 0\n for j in range(len(P)):\n dis = dis + (P[j][i]-P[j][i-1])**2\n dis = np.sqrt(dis)\n parameters[0][i] = parameters[0][i-1] + np.power(dis, a)\n for i in range(1, n):\n parameters[0][i] = parameters[0][i] / parameters[0][n-1]\n return parameters[0]\n\n\ndef knot_vector(param, k, N):\n '''\n Generate knot vector.\n :param param: parameters\n :param k: degree\n :param N: the number of data points\n :return: knot vector\n '''\n m = N + k\n \n knot = np.zeros((1, m+1))\n # print(knot.size)\n for i in range(k + 1):\n knot[0][i] = 0\n for i in range(m - k, m + 1):\n knot[0][i] = 1\n for i in range(k + 1, m - k):\n for j in range(i - k, i):\n knot[0][i] = knot[0][i] + param[j]\n knot[0][i] = knot[0][i] / k\n return knot[0]\n"
] |
[
[
"numpy.zeros",
"numpy.sqrt",
"numpy.linspace",
"numpy.power"
]
] |
thomasperrot/aes-square-attack
|
[
"cdc63f4552324a91fa0e7d9bb14cd481bff65740"
] |
[
"aes/square.py"
] |
[
"import binascii\nimport logging\nfrom concurrent.futures import ProcessPoolExecutor\nfrom functools import partial\nfrom typing import Callable, Iterable, List, Tuple\n\nimport numpy as np\n\nfrom .common import S_BOX, State\nfrom .key_expension import get_first_key\n\nSQUARE_ROUNDS = 4\nREVERSED_S_BOX = {v: k for k, v in S_BOX.items()}\n\n\ndef crack_key(encrypt_ds: Callable[[Iterable[State]], List[State]], rounds: int = SQUARE_ROUNDS) -> bytes:\n last_key = crack_last_key(encrypt_ds)\n logging.info(f\"[+] Found last key: {binascii.hexlify(last_key).decode()}\")\n cracked_key = get_first_key(last_key, rounds + 1)\n return cracked_key\n\n\ndef crack_last_key(encrypt_ds: Callable[[Iterable[State]], List[State]]) -> bytes:\n last_bytes = [0] * 16\n positions = list(range(16))\n logging.info(\"Gathering encrypted delta set...\")\n encrypted_ds = gather_encrypted_delta_sets(encrypt_ds)\n position_guesser = partial(guess_position, encrypted_ds)\n logging.info(\"Cracking key...\")\n with ProcessPoolExecutor() as executor:\n for position, found_byte in zip(positions, executor.map(position_guesser, positions)):\n last_bytes[position] = found_byte\n logging.info(\"Finished cracking key\")\n return bytes(last_bytes)\n\n\ndef gather_encrypted_delta_sets(encrypt_ds: Callable[[Iterable[State]], List[State]]) -> Iterable[Iterable[State]]:\n encrypted_ds = []\n for inactive_value in range(0x10):\n logging.debug(f\"[ ] Encrypting delta set {hex(inactive_value)}...\")\n ds = get_delta_set(inactive_value)\n encrypted_ds.append(encrypt_ds(ds))\n return encrypted_ds\n\n\ndef guess_position(encrypted_delta_sets: Iterable[Iterable[State]], position: int) -> int:\n position_in_state = (position % 4, position // 4)\n for encrypted_delta_set in encrypted_delta_sets:\n correct_guesses = []\n for guess in range(0x100):\n reversed_bytes = reverse_state(guess, position_in_state, encrypted_delta_set)\n if is_guess_correct(reversed_bytes):\n correct_guesses.append(guess)\n if len(correct_guesses) == 1:\n break\n else:\n raise RuntimeError(f\"Could not find byte for position {position}\")\n return correct_guesses[0]\n\n\ndef reverse_state(guess: int, position: Tuple[int, int], encrypted_ds: Iterable[State]) -> List[int]:\n r = []\n i, j = position\n for s in encrypted_ds:\n before_add_round_key = s[i, j] ^ guess\n before_sub_byte = REVERSED_S_BOX[before_add_round_key]\n r.append(before_sub_byte)\n return r\n\n\ndef is_guess_correct(reversed_bytes: Iterable[int]) -> bool:\n r = 0\n for i in reversed_bytes:\n r ^= i\n return r == 0\n\n\ndef get_delta_set(inactive_value: int) -> List[State]:\n base_state = np.full((4, 4), inactive_value)\n delta_set = []\n for i in range(256):\n state = base_state.copy()\n state[0, 0] = i\n delta_set.append(state)\n return delta_set\n"
] |
[
[
"numpy.full"
]
] |
ska-sa/mkatsim
|
[
"94f0e5fb28bf3f9c18f0559f9049636db2abcc27"
] |
[
"mkatsim/subarray/telescopearray.py"
] |
[
"#! /usr/bin/python\n## Display array antenna locations on EARTH grid using astropy coordinates\n\nimport numpy\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\n# Copied library functions\ndef shoot(lon, lat, azimuth, maxdist=None):\n \"\"\"Shooter Function\n Original javascript on http://williams.best.vwh.net/gccalc.htm\n Translated to python by Thomas Lecocq\n \"\"\"\n import numpy as np\n glat1 = lat * np.pi / 180.\n glon1 = lon * np.pi / 180.\n s = maxdist / 1.852\n faz = azimuth * np.pi / 180.\n\n EPS= 0.00000000005\n if ((np.abs(np.cos(glat1))<EPS) and not (np.abs(np.sin(faz))<EPS)):\n alert(\"Only N-S courses are meaningful, starting at a pole!\")\n\n a=6378.13/1.852\n f=1/298.257223563\n r = 1 - f\n tu = r * np.tan(glat1)\n sf = np.sin(faz)\n cf = np.cos(faz)\n if (cf==0):\n b=0.\n else:\n b=2. * np.arctan2(tu, cf)\n\n cu = 1. / np.sqrt(1 + tu * tu)\n su = tu * cu\n sa = cu * sf\n c2a = 1 - sa * sa\n x = 1. + np.sqrt(1. + c2a * (1. / (r * r) - 1.))\n x = (x - 2.) / x\n c = 1. - x\n c = (x * x / 4. + 1.) / c\n d = (0.375 * x * x - 1.) * x\n tu = s / (r * a * c)\n y = tu\n c = y + 1\n while (np.abs (y - c) > EPS):\n\n sy = np.sin(y)\n cy = np.cos(y)\n cz = np.cos(b + y)\n e = 2. * cz * cz - 1.\n c = y\n x = e * cy\n y = e + e - 1.\n y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) * d / 4. - cz) * sy * d + tu\n\n b = cu * cy * cf - su * sy\n c = r * np.sqrt(sa * sa + b * b)\n d = su * cy + cu * sy * cf\n glat2 = (np.arctan2(d, c) + np.pi) % (2*np.pi) - np.pi\n c = cu * cy - su * sy * cf\n x = np.arctan2(sy * sf, c)\n c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16.\n d = ((e * cy * c + cz) * sy * c + y) * sa\n glon2 = ((glon1 + x - (1. - c) * d * f + np.pi) % (2*np.pi)) - np.pi\n\n baz = (np.arctan2(sa, b) + np.pi) % (2 * np.pi)\n\n glon2 *= 180./np.pi\n glat2 *= 180./np.pi\n baz *= 180./np.pi\n\n return (glon2, glat2, baz)\n\ndef equi(m, centerlon, centerlat, radius, *args, **kwargs):\n glon1 = centerlon\n glat1 = centerlat\n X = []\n Y = []\n for azimuth in range(0, 360):\n glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius)\n X.append(glon2)\n Y.append(glat2)\n X.append(X[0])\n Y.append(Y[0])\n\n #~ m.plot(X,Y,**kwargs)\n #Should work, but doesn't...\n X,Y = m(X,Y)\n plt.plot(X,Y,**kwargs)\n\n# Show simple layout for quick look\ndef show_layout(\n array, # antenna location array\n subname='MeerKAT', # name of telescope array\n savegraph=False, # output to PNG image\n ):\n [arr_names, arr_lat, arr_lon] = build_array(array)\n plt.figure(facecolor='white')\n ax1 = plt.axes(frameon=False)\n plt.plot(arr_lon, arr_lat, 'ro', alpha=0.3)\n ax1.axes.get_yaxis().set_visible(False)\n ax1.axes.get_xaxis().set_visible(False)\n plt.title(str(subname))\n if savegraph:\n plt.savefig('%s_SimpleArray.png' % subname, dpi=300)\n\n# Show overlap of subarray on MeerKAT array layout\ndef show_subarray(\n array_ref, # array reference location\n array, # MeerKAT full array layout\n subarray, # Subarray to display\n subname=None, # Name of subarray to display\n savegraph=False,\n radii=True,\n ):\n# def mkat_subarr(mkat, subarray=None, antennalist=[], savegraph=False):\n [arr_names, arr_lat, arr_lon] = build_array(array)\n [subarr_names, subarr_lat, subarr_lon] = build_array(subarray)\n\n # Earth projection\n m = Basemap(projection='merc',\n lat_0=array_ref.latitude.value,\n lon_0=array_ref.longitude.value,\n llcrnrlon=numpy.min(arr_lon)-0.005,\n llcrnrlat=numpy.min(arr_lat)-0.005,\n urcrnrlon=numpy.max(arr_lon)+0.005,\n urcrnrlat=numpy.max(arr_lat)+0.005)\n # set regular grid and map projected coordinates\n arr_x, arr_y = m(arr_lon, arr_lat)\n subarr_x, subarr_y = m(subarr_lon, subarr_lat)\n # # Array layout\n plt.figure(figsize=(20, 13))\n # draw parallels.\n parallels = numpy.arange(-30.73, -30.69, .01)\n m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)\n # draw meridians\n meridians = numpy.arange(21.41, 21.48, .01)\n m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)\n m.drawmapboundary(fill_color='white')\n m.scatter(arr_x, arr_y, 5, marker='o', color='c', label='MeerKAT antennas')\n m.scatter(subarr_x, subarr_y, 10, marker='o', color='k', label='SubArray')\n if radii:\n equi(m, array_ref.longitude.value, array_ref.latitude.value, radius=0.5,lw=1., linestyle='--', label='0.5 deg')\n equi(m, array_ref.longitude.value, array_ref.latitude.value, radius=1,lw=1., linestyle='--', label='1 deg')\n equi(m, array_ref.longitude.value, array_ref.latitude.value, radius=2,lw=1., linestyle='--', label='2 deg')\n equi(m, array_ref.longitude.value, array_ref.latitude.value, radius=3,lw=1., linestyle='--', label='3 deg')\n cntr = 0\n for x, y in zip(subarr_x, subarr_y):\n plt.text(x, y, subarray.keys()[cntr], fontsize=6, ha='center', va='baseline', color='k') # noqa\n cntr += 1\n plt.title('SubArray %s' % subname)\n plt.legend(loc=0, numpoints=1)\n if savegraph:\n if subname is None:\n plt.savefig('SubArrayLayout.png')\n else:\n plt.savefig('Sub%sLayout.png' % subname)\n\n# Generate layout map using Mercator projection\ndef generate_map(\n ref_location, # array geodetic (LAT,LON) reference\n array, # antenna location array\n subname='MeerKAT', # name of telescope array\n savegraph=False, # output to PNG image\n ):\n [arr_names, arr_lat, arr_lon] = build_array(array)\n # Earth projection\n m = Basemap(projection='merc',\n lat_0=ref_location.latitude.value,\n lon_0=ref_location.longitude.value,\n llcrnrlon=numpy.min(arr_lon)-0.005,\n llcrnrlat=numpy.min(arr_lat)-0.005,\n urcrnrlon=numpy.max(arr_lon)+0.005,\n urcrnrlat=numpy.max(arr_lat)+0.005)\n # set regular grid and map projected coordinates\n ref_x, ref_y = m(ref_location.longitude.value, ref_location.latitude.value)\n arr_x, arr_y = m(arr_lon, arr_lat)\n # Array layout\n plt.figure(figsize=(20, 13), facecolor='white')\n # draw parallels.\n parallels = numpy.arange(-30.73, -30.69, .01)\n m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)\n # draw meridians\n meridians = numpy.arange(21.41, 21.48, .01)\n m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)\n m.drawmapboundary(fill_color='white')\n m.scatter(ref_x, ref_y, 1000, marker='+', color='r', label='Array reference') # noqa\n cntr = 0\n for x, y in zip(arr_x, arr_y):\n plt.text(x, y, arr_names[cntr], fontsize=6, ha='center', va='baseline', color='k') # noqa\n cntr += 1\n plt.title('Detail Map: %s Layout' % subname)\n plt.legend(loc=0, numpoints=1, ncol=1, prop={'size': 10}, scatterpoints=1)\n if savegraph:\n plt.savefig('%s_ArrayLayout.png' % subname, dpi=300)\n\n# Utility script to extract antenna (LAT,LON) positions for plotting\ndef build_array(\n array_antennas, # ENU coordinates from astropy\n ):\n # Get array\n arr_latitude = []\n arr_longitude = []\n arr_names = []\n for antenna in array_antennas:\n arr_names.append(antenna)\n arr_latitude.append(array_antennas[antenna].latitude.value)\n arr_longitude.append(array_antennas[antenna].longitude.value)\n return [arr_names, arr_latitude, arr_longitude]\n\n# Save subarray in ITRF geo-centric coordinate file\ndef save_array(\n subarray, # Geo-centric coordinates of subarray\n ):\n out_str = 'X Y Z diameter station mount\\n'\n for ant in subarray.keys():\n itrf = subarray[ant]\n out_str += ('%f %f %f 13.5 %s ALT-AZ\\n' %\n (itrf.x.value, itrf.y.value, itrf.z.value, ant))\n\n fout = open('subarray.itrf', 'w')\n fout.write(out_str)\n fout.close()\n\n# -fin-\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.sqrt",
"matplotlib.pyplot.title",
"numpy.abs",
"numpy.min",
"numpy.arange",
"numpy.cos",
"matplotlib.pyplot.savefig",
"numpy.sin",
"numpy.arctan2",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axes",
"numpy.tan",
"numpy.max",
"matplotlib.pyplot.text",
"matplotlib.pyplot.figure"
]
] |
trangvu/ape-npi
|
[
"4ae2cd6ed1be773dfe1513458d5e7adae0d46283"
] |
[
"translate/translation_model.py"
] |
[
"import tensorflow as tf\nimport os\nimport pickle\nimport re\nimport time\nimport numpy as np\nimport sys\nimport math\nimport shutil\nimport itertools\nfrom collections import OrderedDict\nfrom translate import utils, evaluation, import_graph\nfrom translate.seq2seq_model import Seq2SeqModel\nfrom subprocess import Popen, PIPE\nfrom translate.summary_logger import Logger\nfrom translate.import_graph import ImportGraph\n\n\nclass TranslationModel:\n def __init__(self, encoders, decoders, checkpoint_dir, learning_rate, learning_rate_decay_factor,\n batch_size, keep_best=1, dev_prefix=None, name=None, ref_ext=None,\n pred_edits=False, dual_output=False, binary=None, truncate_lines=True, ensemble=False,\n checkpoints=None, beam_size=1, len_normalization=1, lexicon=None, debug=False, **kwargs):\n\n self.batch_size = batch_size\n self.character_level = {}\n self.binary = []\n self.debug = debug\n\n for encoder_or_decoder in encoders + decoders:\n encoder_or_decoder.ext = encoder_or_decoder.ext or encoder_or_decoder.name\n self.character_level[encoder_or_decoder.ext] = encoder_or_decoder.character_level\n self.binary.append(encoder_or_decoder.get('binary', False))\n\n self.encoders, self.decoders = encoders, decoders\n\n self.char_output = decoders[0].character_level\n\n self.src_ext = [encoder.ext for encoder in encoders]\n self.trg_ext = [decoder.ext for decoder in decoders]\n\n self.extensions = self.src_ext + self.trg_ext\n\n self.ref_ext = ref_ext\n if self.ref_ext is not None:\n self.binary.append(False)\n\n self.pred_edits = pred_edits\n self.dual_output = dual_output\n\n self.dev_prefix = dev_prefix\n self.name = name\n\n self.max_input_len = [encoder.max_len for encoder in encoders]\n self.max_output_len = [decoder.max_len for decoder in decoders]\n self.beam_size = beam_size\n\n if truncate_lines:\n self.max_len = None # we let seq2seq.get_batch handle long lines (by truncating them)\n else: # the line reader will drop lines that are too long\n self.max_len = dict(zip(self.extensions, self.max_input_len + self.max_output_len))\n\n self.learning_rate = tf.Variable(learning_rate, trainable=False, name='learning_rate', dtype=tf.float32)\n self.learning_rate_decay_op = self.learning_rate.assign(self.learning_rate * learning_rate_decay_factor)\n\n with tf.device('/cpu:0'):\n self.global_step = tf.Variable(0, trainable=False, name='global_step')\n self.baseline_step = tf.Variable(0, trainable=False, name='baseline_step')\n\n self.filenames = utils.get_filenames(extensions=self.extensions, dev_prefix=dev_prefix, name=name,\n ref_ext=ref_ext, binary=self.binary, **kwargs)\n utils.debug('reading vocabularies')\n self.vocabs = None\n self.src_vocab, self.trg_vocab = None, None\n self.read_vocab()\n\n for encoder_or_decoder, vocab in zip(encoders + decoders, self.vocabs):\n if vocab:\n if encoder_or_decoder.vocab_size: # reduce vocab size\n vocab.reverse[:] = vocab.reverse[:encoder_or_decoder.vocab_size]\n for token, token_id in list(vocab.vocab.items()):\n if token_id >= encoder_or_decoder.vocab_size:\n del vocab.vocab[token]\n else:\n encoder_or_decoder.vocab_size = len(vocab.reverse)\n\n utils.debug('creating model')\n\n self.models = []\n if ensemble and checkpoints is not None:\n for i, _ in enumerate(checkpoints, 1):\n with tf.variable_scope('model_{}'.format(i)):\n model = Seq2SeqModel(encoders, decoders, self.learning_rate, self.global_step, name=name,\n pred_edits=pred_edits, dual_output=dual_output,\n baseline_step=self.baseline_step, **kwargs)\n self.models.append(model)\n self.seq2seq_model = self.models[0]\n else:\n self.seq2seq_model = Seq2SeqModel(encoders, decoders, self.learning_rate, self.global_step, name=name,\n pred_edits=pred_edits, dual_output=dual_output,\n baseline_step=self.baseline_step, **kwargs)\n self.models.append(self.seq2seq_model)\n\n self.seq2seq_model.create_beam_op(self.models, len_normalization)\n\n self.summary_logger = Logger(kwargs['log_dir'])\n\n self.batch_iterator = None\n self.dev_batches = None\n self.train_size = None\n self.saver = None\n self.keep_best = keep_best\n self.checkpoint_dir = checkpoint_dir\n self.epoch = None\n\n self.training = utils.AttrDict() # used to keep track of training\n\n if lexicon:\n with open(lexicon) as lexicon_file:\n self.lexicon = dict(line.split() for line in lexicon_file)\n else:\n self.lexicon = None\n\n def read_data(self, max_train_size, max_dev_size, read_ahead=10, batch_mode='standard', shuffle=True,\n crash_test=False, **kwargs):\n utils.debug('reading training data')\n self.batch_iterator, self.train_size = utils.get_batch_iterator(\n self.filenames.train, self.extensions, self.vocabs, self.batch_size,\n max_size=max_train_size, character_level=self.character_level, max_seq_len=self.max_len,\n read_ahead=read_ahead, mode=batch_mode, shuffle=shuffle, binary=self.binary, crash_test=crash_test\n )\n\n utils.debug('reading development data')\n\n dev_sets = [\n utils.read_dataset(dev, self.extensions, self.vocabs, max_size=max_dev_size,\n character_level=self.character_level, binary=self.binary)[0]\n for dev in self.filenames.dev\n ]\n # subset of the dev set whose loss is periodically evaluated\n self.dev_batches = [utils.get_batches(dev_set, batch_size=self.batch_size) for dev_set in dev_sets]\n\n def read_vocab(self):\n # don't try reading vocabulary for encoders that take pre-computed features\n self.vocabs = [\n None if binary else utils.initialize_vocabulary(vocab_path)\n for vocab_path, binary in zip(self.filenames.vocab, self.binary)\n ]\n self.src_vocab, self.trg_vocab = self.vocabs[:len(self.src_ext)], self.vocabs[len(self.src_ext):]\n\n def decode_sentence(self, sentence_tuple, remove_unk=False):\n return next(self.decode_batch([sentence_tuple], remove_unk))\n\n def decode_batch(self, sentence_tuples, batch_size, remove_unk=False, fix_edits=True, unk_replace=False,\n align=False, reverse=False, output=None, execute_edit=True):\n if batch_size == 1:\n batches = ([sentence_tuple] for sentence_tuple in sentence_tuples) # lazy\n else:\n batch_count = int(math.ceil(len(sentence_tuples) / batch_size))\n batches = [sentence_tuples[i * batch_size:(i + 1) * batch_size] for i in range(batch_count)]\n\n def map_to_ids(sentence_tuple):\n token_ids = [\n sentence if vocab is None else\n utils.sentence_to_token_ids(sentence, vocab.vocab, character_level=self.character_level.get(ext))\n for ext, vocab, sentence in zip(self.extensions, self.vocabs, sentence_tuple)\n ]\n return token_ids\n\n line_id = 0\n for batch_id, batch in enumerate(batches):\n token_ids = list(map(map_to_ids, batch))\n batch_token_ids, batch_weights = self.seq2seq_model.greedy_decoding(token_ids, beam_size=self.beam_size,\n align=unk_replace or align or self.debug)\n batch_token_ids = zip(*batch_token_ids)\n\n for sentence_id, (src_tokens, trg_token_ids) in enumerate(zip(batch, batch_token_ids)):\n line_id += 1\n trg_tokens = []\n\n for trg_token_ids_, vocab in zip(trg_token_ids, self.trg_vocab):\n trg_token_ids_ = list(trg_token_ids_) # from np array to list\n if utils.EOS_ID in trg_token_ids_:\n trg_token_ids_ = trg_token_ids_[:trg_token_ids_.index(utils.EOS_ID)]\n\n trg_tokens_ = [vocab.reverse[i] if i < len(vocab.reverse) else utils._UNK\n for i in trg_token_ids_]\n trg_tokens.append(trg_tokens_)\n\n if align:\n weights_ = batch_weights[sentence_id].squeeze()\n max_len_ = weights_.shape[1]\n\n if self.binary[0]:\n src_tokens_ = None\n else:\n src_tokens_ = src_tokens[0].split()[:max_len_ - 1] + [utils._EOS]\n src_tokens_ = [token if token in self.src_vocab[0].vocab else utils._UNK for token in src_tokens_]\n weights_ = weights_[:,:len(src_tokens_)]\n\n trg_tokens_ = trg_tokens[0][:weights_.shape[0] - 1] + [utils._EOS]\n weights_ = weights_[:len(trg_tokens_)]\n output_file = output and '{}.{}.pdf'.format(output, line_id)\n utils.heatmap(src_tokens_, trg_tokens_, weights_, reverse=reverse, output_file=output_file)\n\n if self.debug or unk_replace:\n weights = batch_weights[sentence_id]\n src_words = src_tokens[0].split()\n align_ids = np.argmax(weights[:,:len(src_words)], axis=1)\n else:\n align_ids = [0] * len(trg_tokens[0])\n def replace(token, align_id):\n if self.debug and (not unk_replace or token == utils._UNK):\n suffix = '({})'.format(align_id)\n else:\n suffix = ''\n if token == utils._UNK and unk_replace:\n token = src_words[align_id]\n if not token[0].isupper() and self.lexicon is not None and token in self.lexicon:\n token = self.lexicon[token]\n return token + suffix\n\n trg_tokens[0] = [replace(token, align_id) for align_id, token in zip(align_ids, trg_tokens[0])]\n\n if self.pred_edits:\n # first output is ops, second output is words\n if execute_edit:\n raw_hypothesis = ' '.join('_'.join(tokens) for tokens in zip(*trg_tokens))\n src_words = src_tokens[0].split()\n trg_tokens = utils.reverse_edits(src_words, trg_tokens, fix=fix_edits)\n trg_tokens = [token for token in trg_tokens if token not in utils._START_VOCAB]\n else:\n trg_tokens = trg_tokens[0]\n raw_hypothesis = ''.join(trg_tokens) if self.char_output else ' '.join(trg_tokens)\n else:\n trg_tokens = trg_tokens[0]\n raw_hypothesis = ''.join(trg_tokens) if self.char_output else ' '.join(trg_tokens)\n\n if remove_unk:\n trg_tokens = [token for token in trg_tokens if token != utils._UNK]\n\n if self.char_output:\n hypothesis = ''.join(trg_tokens)\n else:\n hypothesis = ' '.join(trg_tokens).replace('@@ ', '') # merge subwords units\n\n yield hypothesis, raw_hypothesis\n\n\n def align(self, output=None, align_encoder_id=0, reverse=False, max_test_size=None, **kwargs):\n if len(self.filenames.test) != len(self.extensions):\n raise Exception('wrong number of input files')\n\n binary = self.binary and any(self.binary)\n\n paths = self.filenames.test or [None]\n lines = utils.read_lines(paths, binary=self.binary)\n\n if max_test_size:\n lines = itertools.islice(lines, max_test_size)\n\n for line_id, lines in enumerate(lines):\n token_ids = [\n sentence if vocab is None else\n utils.sentence_to_token_ids(sentence, vocab.vocab, character_level=self.character_level.get(ext))\n for ext, vocab, sentence in zip(self.extensions, self.vocabs, lines)\n ]\n\n _, weights = self.seq2seq_model.step(data=[token_ids], align=True, update_model=False)\n\n trg_vocab = self.trg_vocab[0]\n trg_token_ids = token_ids[len(self.src_ext)]\n trg_tokens = [trg_vocab.reverse[i] if i < len(trg_vocab.reverse) else utils._UNK for i in trg_token_ids]\n\n weights = weights[0] # can contain a list of forward and backward attention (cf. reconstruction decoders)\n weights = weights.squeeze()\n max_len = weights.shape[1]\n\n if binary:\n src_tokens = None\n else:\n src_tokens = lines[align_encoder_id].split()[:max_len - 1] + [utils._EOS]\n trg_tokens = trg_tokens[:weights.shape[0] - 1] + [utils._EOS]\n\n output_file = output and '{}.{}.pdf'.format(output, line_id + 1)\n\n utils.heatmap(src_tokens, trg_tokens, weights, output_file=output_file, reverse=reverse)\n\n\n def decode(self, output=None, remove_unk=False, raw_output=False, max_test_size=None, unk_replace=False,\n align=False, reverse=False, execute_edit=False, **kwargs):\n utils.log('starting decoding')\n\n # empty `test` means that we read from standard input, which is not possible with multiple encoders\n # assert len(self.src_ext) == 1 or self.filenames.test\n # check that there is the right number of files for decoding\n # assert not self.filenames.test or len(self.filenames.test) == len(self.src_ext)\n\n output_file = None\n try:\n output_file = sys.stdout if output is None else open(output, 'w')\n paths = self.filenames.test or [None]\n lines = utils.read_lines(paths, binary=self.binary)\n\n if max_test_size:\n lines = itertools.islice(lines, max_test_size)\n\n if not self.filenames.test: # interactive mode\n batch_size = 1\n else:\n batch_size = self.batch_size\n lines = list(lines)\n\n hypothesis_iter = self.decode_batch(lines, batch_size, remove_unk=remove_unk, unk_replace=unk_replace,\n align=align, reverse=reverse, output=output, execute_edit=execute_edit)\n\n for hypothesis, raw in hypothesis_iter:\n if raw_output:\n hypothesis = raw\n\n output_file.write(hypothesis + '\\n')\n output_file.flush()\n finally:\n if output_file is not None:\n output_file.close()\n\n def evaluate(self, score_functions, on_dev=True, output=None, remove_unk=False, max_dev_size=None,\n raw_output=False, fix_edits=True, max_test_size=None, post_process_script=None,\n unk_replace=False, **kwargs):\n \"\"\"\n Decode a dev or test set, and perform evaluation with respect to gold standard, using the provided\n scoring function. If `output` is defined, also save the decoding output to this file.\n When evaluating development data (`on_dev` to True), several dev sets can be specified (`dev_prefix` parameter\n in configuration files), and a score is computed for each of them.\n\n :param score_function: name of the scoring function used to score and rank models (typically 'bleu_score')\n :param on_dev: if True, evaluate the dev corpus, otherwise evaluate the test corpus\n :param output: save the hypotheses to this file\n :param remove_unk: remove the UNK symbols from the output\n :param max_dev_size: maximum number of lines to read from dev files\n :param max_test_size: maximum number of lines to read from test files\n :param raw_output: save raw decoder output (don't do post-processing like UNK deletion or subword\n concatenation). The evaluation is still done with the post-processed output.\n :param fix_edits: when predicting edit operations, pad shorter hypotheses with KEEP symbols.\n :return: scores of each corpus to evaluate\n \"\"\"\n utils.log('starting evaluation')\n\n if on_dev:\n filenames = self.filenames.dev\n else:\n filenames = [self.filenames.test]\n\n # convert `output` into a list, for zip\n if isinstance(output, str):\n output = [output]\n elif output is None:\n output = [None] * len(filenames)\n\n scores = []\n\n # evaluation on multiple corpora\n for dev_id, (filenames_, output_, prefix) in enumerate(zip(filenames, output, self.dev_prefix)):\n if self.ref_ext is not None:\n filenames_ = filenames_[:len(self.src_ext)] + filenames_[-1:]\n\n if self.dev_batches:\n dev_batches = self.dev_batches[dev_id]\n dev_loss = sum(self.seq2seq_model.step(batch, update_model=False).loss * len(batch)\n for batch in dev_batches)\n dev_loss /= sum(map(len, dev_batches))\n else: # TODO\n dev_loss = 0\n\n src_lines = list(utils.read_lines(filenames_[:len(self.src_ext)], binary=self.binary[:len(self.src_ext)]))\n trg_lines = list(utils.read_lines([filenames_[len(self.src_ext)]]))\n\n assert len(trg_lines) % len(src_lines) == 0\n\n references = []\n ref_count = len(trg_lines) // len(src_lines)\n for i in range(len(src_lines)):\n ref = trg_lines[i * ref_count:(i + 1) * ref_count]\n ref = [ref_[0].strip().replace('@@ ', '').replace('@@', '') for ref_ in ref]\n references.append(ref)\n\n if on_dev and max_dev_size:\n max_size = max_dev_size\n elif not on_dev and max_test_size:\n max_size = max_test_size\n else:\n max_size = len(src_lines)\n\n src_lines = src_lines[:max_size]\n references = references[:max_size]\n\n hypotheses = []\n output_file = None\n try:\n if output_ is not None:\n output_file = open(output_, 'w')\n\n hypothesis_iter = self.decode_batch(src_lines, self.batch_size, remove_unk=remove_unk,\n fix_edits=fix_edits, unk_replace=unk_replace)\n\n for i, hypothesis in enumerate(hypothesis_iter):\n hypothesis, raw = hypothesis\n hypotheses.append(hypothesis)\n if output_file is not None:\n if raw_output:\n hypothesis = raw\n output_file.write(hypothesis + '\\n')\n output_file.flush()\n finally:\n if output_file is not None:\n output_file.close()\n\n if post_process_script is not None:\n data = '\\n'.join(hypotheses).encode()\n data = Popen([post_process_script], stdout=PIPE, stdin=PIPE).communicate(input=data)[0].decode()\n hypotheses = data.splitlines()\n\n scores_ = []\n summary = None\n\n for score_function in score_functions:\n try:\n if score_function != 'bleu':\n references_ = [ref[0] for ref in references]\n else:\n references_ = references\n\n if score_function == 'loss':\n score = dev_loss\n reversed_ = True\n else:\n fun = getattr(evaluation, 'corpus_' + score_function)\n try:\n reversed_ = fun.reversed\n except AttributeError:\n reversed_ = False\n score, score_summary = fun(hypotheses, references_)\n summary = summary or score_summary\n\n scores_.append((score_function, score, reversed_))\n self.summary_logger.log_scalar(score_function, score, self.global_step.eval())\n except:\n pass\n\n score_info = ['{}={:.2f}'.format(key, value) for key, value, _ in scores_]\n score_info.insert(0, prefix)\n if summary:\n score_info.append(summary)\n\n if self.name is not None:\n score_info.insert(0, self.name)\n\n utils.log(' '.join(map(str, score_info)))\n\n # main score\n _, score, reversed_ = scores_[0]\n scores.append(-score if reversed_ else score)\n\n return scores\n\n def train(self, baseline_steps=0, loss_function='xent', use_baseline=True, **kwargs):\n self.init_training(**kwargs)\n\n if (loss_function == 'reinforce' and use_baseline and baseline_steps > 0 and\n self.baseline_step.eval() < baseline_steps):\n utils.log('pre-training reinforce baseline')\n for i in range(baseline_steps - self.baseline_step.eval()):\n self.seq2seq_model.reinforce_step(next(self.batch_iterator), update_model=False,\n use_sgd=False, update_baseline=True)\n\n utils.log('starting training')\n while True:\n try:\n self.train_step(loss_function=loss_function, use_baseline=use_baseline, **kwargs)\n sys.stdout.flush()\n except (utils.FinishedTrainingException, KeyboardInterrupt):\n utils.log('exiting...')\n self.save()\n return\n except utils.EvalException:\n self.save()\n step, score = self.training.scores[-1]\n self.manage_best_checkpoints(step, score)\n except utils.CheckpointException:\n self.save()\n\n def init_training(self, sgd_after_n_epoch=None, **kwargs):\n self.read_data(**kwargs)\n self.epoch = self.batch_size * self.global_step // self.train_size\n\n global_step = self.global_step.eval()\n epoch = self.epoch.eval()\n if sgd_after_n_epoch is not None and epoch >= sgd_after_n_epoch: # already switched to SGD\n self.training.use_sgd = True\n else:\n self.training.use_sgd = False\n\n if kwargs.get('batch_mode') != 'random' and not kwargs.get('shuffle'):\n # read all the data up to this step (only if the batch iteration method is deterministic)\n for _ in range(global_step):\n next(self.batch_iterator)\n\n # those parameters are used to track the progress of training\n self.training.time = 0\n self.training.steps = 0\n self.training.loss = 0\n self.training.baseline_loss = 0\n self.training.losses = []\n self.training.last_decay = global_step\n self.training.scores = []\n\n def train_step(self, steps_per_checkpoint, model_dir, steps_per_eval=None, max_steps=0,\n max_epochs=0, eval_burn_in=0, decay_if_no_progress=None, decay_after_n_epoch=None,\n decay_every_n_epoch=None, sgd_after_n_epoch=None, sgd_learning_rate=None, min_learning_rate=None,\n loss_function='xent', use_baseline=True, **kwargs):\n if min_learning_rate is not None and self.learning_rate.eval() < min_learning_rate:\n utils.debug('learning rate is too small: stopping')\n raise utils.FinishedTrainingException\n if 0 < max_steps <= self.global_step.eval() or 0 < max_epochs <= self.epoch.eval():\n raise utils.FinishedTrainingException\n\n start_time = time.time()\n\n if loss_function == 'reinforce':\n step_function = self.seq2seq_model.reinforce_step\n else:\n step_function = self.seq2seq_model.step\n\n res = step_function(next(self.batch_iterator), update_model=True, use_sgd=self.training.use_sgd,\n update_baseline=True)\n\n self.training.loss += res.loss\n self.training.baseline_loss += getattr(res, 'baseline_loss', 0)\n\n self.training.time += time.time() - start_time\n self.training.steps += 1\n\n global_step = self.global_step.eval()\n epoch = self.epoch.eval()\n\n if global_step % 10 == 0:\n loss = self.training.loss / self.training.steps\n baseline_loss = self.training.baseline_loss / self.training.steps\n self.summary_logger.log_scalar(\"train_loss\", loss, global_step)\n self.summary_logger.log_scalar(\"baseline_loss\", baseline_loss, global_step)\n\n if decay_after_n_epoch is not None and self.batch_size * global_step >= decay_after_n_epoch * self.train_size:\n if decay_every_n_epoch is not None and (self.batch_size * (global_step - self.training.last_decay)\n >= decay_every_n_epoch * self.train_size):\n self.learning_rate_decay_op.eval()\n utils.debug(' decaying learning rate to: {:.3g}'.format(self.learning_rate.eval()))\n self.training.last_decay = global_step\n\n if sgd_after_n_epoch is not None and epoch >= sgd_after_n_epoch:\n if not self.training.use_sgd:\n utils.debug('epoch {}, starting to use SGD'.format(epoch + 1))\n self.training.use_sgd = True\n if sgd_learning_rate is not None:\n self.learning_rate.assign(sgd_learning_rate).eval()\n self.training.last_decay = global_step # reset learning rate decay\n\n if steps_per_checkpoint and global_step % steps_per_checkpoint == 0:\n loss = self.training.loss / self.training.steps\n baseline_loss = self.training.baseline_loss / self.training.steps\n step_time = self.training.time / self.training.steps\n\n summary = 'step {} epoch {} learning rate {:.3g} step-time {:.3f} loss {:.3f}'.format(\n global_step, epoch + 1, self.learning_rate.eval(), step_time, loss)\n\n if self.name is not None:\n summary = '{} {}'.format(self.name, summary)\n if use_baseline and loss_function == 'reinforce':\n summary = '{} baseline-loss {:.4f}'.format(summary, baseline_loss)\n\n utils.log(summary)\n\n if decay_if_no_progress and len(self.training.losses) >= decay_if_no_progress:\n if loss >= max(self.training.losses[:decay_if_no_progress]):\n self.learning_rate_decay_op.eval()\n\n self.training.losses.append(loss)\n self.training.loss, self.training.time, self.training.steps, self.training.baseline_loss = 0, 0, 0, 0\n\n if steps_per_eval and global_step % steps_per_eval == 0 and 0 <= eval_burn_in <= global_step:\n\n eval_dir = 'eval' if self.name is None else 'eval_{}'.format(self.name)\n eval_output = os.path.join(model_dir, eval_dir)\n\n os.makedirs(eval_output, exist_ok=True)\n\n # if there are several dev files, we define several output files\n output = [\n os.path.join(eval_output, '{}.{}.out'.format(prefix, global_step))\n for prefix in self.dev_prefix\n ]\n\n kwargs_ = dict(kwargs)\n kwargs_['output'] = output\n score, *_ = self.evaluate(on_dev=True, **kwargs_)\n self.training.scores.append((global_step, score))\n\n if steps_per_eval and global_step % steps_per_eval == 0:\n raise utils.EvalException\n elif steps_per_checkpoint and global_step % steps_per_checkpoint == 0:\n raise utils.CheckpointException\n\n def manage_best_checkpoints(self, step, score):\n score_filename = os.path.join(self.checkpoint_dir, 'scores.txt')\n # try loading previous scores\n try:\n with open(score_filename) as f:\n # list of pairs (score, step)\n scores = [(float(line.split()[0]), int(line.split()[1])) for line in f]\n except IOError:\n scores = []\n\n if any(step_ >= step for _, step_ in scores):\n utils.warn('inconsistent scores.txt file')\n\n best_scores = sorted(scores, reverse=True)[:self.keep_best]\n\n def full_path(filename):\n return os.path.join(self.checkpoint_dir, filename)\n\n if any(score_ < score for score_, _ in best_scores) or not best_scores:\n # if this checkpoint is in the top, save it under a special name\n\n prefix = 'translate-{}.'.format(step)\n dest_prefix = 'best-{}.'.format(step)\n\n absolute_best = all(score_ < score for score_, _ in best_scores)\n if absolute_best:\n utils.log('new best model')\n\n for filename in os.listdir(self.checkpoint_dir):\n if filename.startswith(prefix):\n dest_filename = filename.replace(prefix, dest_prefix)\n shutil.copy(full_path(filename), full_path(dest_filename))\n\n # also copy to `best` if this checkpoint is the absolute best\n if absolute_best:\n dest_filename = filename.replace(prefix, 'best.')\n shutil.copy(full_path(filename), full_path(dest_filename))\n\n best_scores = sorted(best_scores + [(score, step)], reverse=True)\n\n for _, step_ in best_scores[self.keep_best:]:\n # remove checkpoints that are not in the top anymore\n prefix = 'best-{}'.format(step_)\n for filename in os.listdir(self.checkpoint_dir):\n if filename.startswith(prefix):\n os.remove(full_path(filename))\n\n # save scores\n scores.append((score, step))\n\n with open(score_filename, 'w') as f:\n for score_, step_ in scores:\n f.write('{:.2f} {}\\n'.format(score_, step_))\n\n def initialize(self, checkpoints=None, reset=False, reset_learning_rate=False, max_to_keep=1,\n keep_every_n_hours=0, sess=None, whitelist=None, blacklist=None,rnn_lm_model_dir=None,\n rnn_mt_model_dir=None, origin_model_ckpt=None, **kwargs):\n \"\"\"\n :param checkpoints: list of checkpoints to load (instead of latest checkpoint)\n :param reset: don't load latest checkpoint, reset learning rate and global step\n :param reset_learning_rate: reset the learning rate to its initial value\n :param max_to_keep: keep this many latest checkpoints at all times\n :param keep_every_n_hours: and keep checkpoints every n hours\n \"\"\"\n sess = sess or tf.get_default_session()\n\n if keep_every_n_hours <= 0 or keep_every_n_hours is None:\n keep_every_n_hours = float('inf')\n\n self.saver = tf.train.Saver(max_to_keep=max_to_keep, keep_checkpoint_every_n_hours=keep_every_n_hours,\n sharded=False)\n\n sess.run(tf.global_variables_initializer())\n\n # load pre-trained embeddings\n for encoder_or_decoder, vocab in zip(self.encoders + self.decoders, self.vocabs):\n if encoder_or_decoder.embedding_file:\n utils.log('loading embeddings from: {}'.format(encoder_or_decoder.embedding_file))\n embeddings = {}\n with open(encoder_or_decoder.embedding_file) as embedding_file:\n for line in embedding_file:\n word, vector = line.split(' ', 1)\n if word in vocab.vocab:\n embeddings[word] = np.array(list(map(float, vector.split())))\n # standardize (mean of 0, std of 0.01)\n mean = sum(embeddings.values()) / len(embeddings)\n std = np.sqrt(sum((value - mean)**2 for value in embeddings.values())) / (len(embeddings) - 1)\n for key in embeddings:\n embeddings[key] = 0.01 * (embeddings[key] - mean) / std\n\n # change TensorFlow variable's value\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n embedding_var = tf.get_variable('embedding_' + encoder_or_decoder.name)\n embedding_value = embedding_var.eval()\n for word, i in vocab.vocab.items():\n if word in embeddings:\n embedding_value[i] = embeddings[word]\n sess.run(embedding_var.assign(embedding_value))\n\n # load pre-trained RNN LM\n if not(rnn_lm_model_dir is None):\n utils.log('load rnn_lm model from {}'.format(rnn_lm_model_dir))\n rnn_lm_graph = ImportGraph(rnn_lm_model_dir)\n cell_name = kwargs['rnn_lm_cell_name']\n kernel_values = rnn_lm_graph.get_variable_value(cell_name + '/kernel:0')\n bias_values = rnn_lm_graph.get_variable_value(cell_name+'/bias:0')\n\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n rnn_lm_kernel_var = [v for v in tf.trainable_variables()\n if v.name == 'decoder_edits/rnn_lm/basic_lstm_cell/kernel:0'][0]\n rnn_lm_bias_var = [v for v in tf.trainable_variables()\n if v.name == 'decoder_edits/rnn_lm/basic_lstm_cell/bias:0'][0]\n sess.run(rnn_lm_kernel_var.assign(kernel_values))\n sess.run(rnn_lm_bias_var.assign(bias_values))\n\n # load pre-trained RNN MT\n if not(rnn_mt_model_dir is None):\n utils.log('load rnn_mt model from {}'.format(rnn_mt_model_dir))\n load_checkpoint(sess, rnn_mt_model_dir, filename=\"best\", prefix=\"decoder_mt\")\n load_checkpoint(sess, rnn_mt_model_dir, filename=\"best\", prefix=\"encoder_src\")\n\n if whitelist:\n with open(whitelist) as f:\n whitelist = list(line.strip() for line in f)\n if blacklist:\n with open(blacklist) as f:\n blacklist = list(line.strip() for line in f)\n else:\n blacklist = []\n\n blacklist.append('dropout_keep_prob')\n\n if reset_learning_rate or reset:\n blacklist.append('learning_rate')\n if reset:\n blacklist.append('global_step')\n\n params = {k: kwargs.get(k) for k in ('variable_mapping', 'reverse_mapping')}\n\n if origin_model_ckpt is not None:\n utils.log(\"Load origin model\")\n blacklist.append('decoder_edits/basic_lstm_cell/kernel:0')\n load_checkpoint(sess, origin_model_ckpt, blacklist=blacklist, whitelist=whitelist, **params)\n\n if checkpoints and len(self.models) > 1:\n assert len(self.models) == len(checkpoints)\n for i, checkpoint in enumerate(checkpoints, 1):\n load_checkpoint(sess, None, checkpoint, blacklist=blacklist, whitelist=whitelist,\n prefix='model_{}'.format(i), **params)\n elif checkpoints: # load partial checkpoints\n for checkpoint in checkpoints: # checkpoint files to load\n load_checkpoint(sess, None, checkpoint, blacklist=blacklist, whitelist=whitelist, **params)\n elif not reset:\n load_checkpoint(sess, self.checkpoint_dir, blacklist=blacklist, whitelist=whitelist, **params)\n\n utils.debug('global step: {}'.format(self.global_step.eval()))\n utils.debug('baseline step: {}'.format(self.baseline_step.eval()))\n\n def save(self):\n save_checkpoint(tf.get_default_session(), self.saver, self.checkpoint_dir, self.global_step)\n\n def save_embedding(self, output_dir):\n os.makedirs(output_dir, exist_ok=True)\n for encoder_or_decoder, vocab in zip(self.encoders + self.decoders, self.vocabs):\n utils.log('saving embeddings for: {}'.format(encoder_or_decoder.name))\n if not (encoder_or_decoder.name == \"edits\"):\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n embedding_var = tf.get_variable('embedding_' + encoder_or_decoder.name)\n embedding_value = embedding_var.eval()\n with open(output_dir + \"/\" + embedding_var.name + \".txt\", 'w') as file_:\n for word, i in vocab.vocab.items():\n file_.write('%s %s\\n' % (word, ' '.join(map(str, embedding_value[i]))))\n\n\n\n# hard-coded variables which can also be defined in config file (variable_mapping and reverse_mapping)\nglobal_variable_mapping = [] # map old names to new names\nglobal_reverse_mapping = [ # map new names to old names\n (r'decoder_(.*?)/.*/initial_state_projection/', r'decoder_\\1/initial_state_projection/'),\n]\n\n\ndef load_checkpoint(sess, checkpoint_dir, filename=None, blacklist=(), prefix=None, variable_mapping=None,\n whitelist=None, reverse_mapping=None):\n \"\"\"\n if `filename` is None, we load last checkpoint, otherwise\n we ignore `checkpoint_dir` and load the given checkpoint file.\n \"\"\"\n variable_mapping = variable_mapping or []\n reverse_mapping = reverse_mapping or []\n\n variable_mapping = list(variable_mapping) + global_variable_mapping\n reverse_mapping = list(reverse_mapping) + global_reverse_mapping\n\n if filename is None:\n # load last checkpoint\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt is not None:\n filename = ckpt.model_checkpoint_path\n else:\n checkpoint_dir = os.path.dirname(filename)\n\n vars_ = []\n var_names = []\n for var in tf.global_variables():\n if prefix is None or var.name.startswith(prefix):\n name = var.name if prefix is None else var.name[len(prefix) + 1:]\n vars_.append(var)\n var_names.append(name)\n\n var_file = os.path.join(checkpoint_dir, 'vars.pkl')\n if os.path.exists(var_file):\n with open(var_file, 'rb') as f:\n old_names = pickle.load(f)\n else:\n old_names = list(var_names)\n\n name_mapping = {}\n for name in old_names:\n name_ = name\n for key, value in variable_mapping:\n name_ = re.sub(key, value, name_)\n name_mapping[name] = name_\n\n var_names_ = []\n for name in var_names:\n name_ = name\n for key, value in reverse_mapping:\n name_ = re.sub(key, value, name_)\n if name_ in list(name_mapping.values()):\n name = name_\n var_names_.append(name)\n vars_ = dict(zip(var_names_, vars_))\n\n variables = {old_name[:-2]: vars_[new_name] for old_name, new_name in name_mapping.items()\n if new_name in vars_ and not any(prefix in new_name for prefix in blacklist) and\n (whitelist is None or new_name in whitelist)}\n\n if filename is not None:\n utils.log('reading model parameters from {}'.format(filename))\n tf.train.Saver(variables).restore(sess, filename)\n\n utils.debug('retrieved parameters ({})'.format(len(variables)))\n for var in sorted(variables.values(), key=lambda var: var.name):\n utils.debug(' {} {}'.format(var.name, var.get_shape()))\n\n\ndef save_checkpoint(sess, saver, checkpoint_dir, step=None, name=None):\n var_file = os.path.join(checkpoint_dir, 'vars.pkl')\n name = name or 'translate'\n os.makedirs(checkpoint_dir, exist_ok=True)\n\n with open(var_file, 'wb') as f:\n var_names = [var.name for var in tf.global_variables()]\n pickle.dump(var_names, f)\n\n utils.log('saving model to {}'.format(checkpoint_dir))\n checkpoint_path = os.path.join(checkpoint_dir, name)\n saver.save(sess, checkpoint_path, step, write_meta_graph=False)\n\n utils.log('finished saving model')\n"
] |
[
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.get_default_session",
"tensorflow.device",
"tensorflow.get_variable",
"tensorflow.Variable",
"tensorflow.global_variables",
"tensorflow.trainable_variables",
"tensorflow.global_variables_initializer",
"tensorflow.train.Saver",
"tensorflow.get_variable_scope"
]
] |
Mohamed-hanafy30/Disasters-pipeline-project-
|
[
"83787c04063f05404eab8f72c0710980588fb3c5"
] |
[
"data/process_data.py"
] |
[
"import sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ndef load_data(messages_filepath, categories_filepath):\n \"\"\"Load dataframe from filepaths\n\n INPUT\n messages_filepath -- str, link to file\n categories_filepath -- str, link to file\n\n OUTPUT\n df - pandas DataFrame\n \"\"\"\n messages = pd.read_csv(messages_filepath)\n categories = pd.read_csv(categories_filepath)\n df = messages.merge(categories, on='id')\n return df\n\ndef clean_data(df):\n \"\"\"Clean data included in the DataFrame and transform categories part\n\n INPUT\n df -- type pandas DataFrame\n\n OUTPUT\n df -- cleaned pandas DataFrame\n \"\"\"\n categories = df['categories'].str.split(pat=';', expand=True)\n row = categories.loc[0]\n colnames = []\n for entry in row:\n colnames.append(entry[:-2])\n category_colnames = colnames\n print('Column names:', category_colnames)\n categories.columns = category_colnames\n for column in categories:\n categories[column] = categories[column].str[-1:]\n categories[column] = categories[column].astype(int)\n df.drop('categories', axis=1, inplace=True)\n df = pd.concat([df, categories], axis=1)\n df.drop_duplicates(inplace=True)\n # Removing entry that is non-binary\n df = df[df['related'] != 2]\n print('Duplicates remaining:', df.duplicated().sum())\n return df\n \ndef save_data(df, database_filename):\n \"\"\"Saves DataFrame (df) to database path\"\"\"\n name = 'sqlite:///' + database_filename\n engine = create_engine(name)\n df.to_sql('Disasters', engine, index=False)\n\n\ndef main():\n \"\"\"Runs main functions: Loads the data, cleans it and saves it in a database\"\"\"\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_csv"
]
] |
swarajthakur/deep-q-learning
|
[
"7856f2f003455c6c4935c902d722fe435bded863"
] |
[
"dqn.py"
] |
[
"# -*- coding: utf-8 -*-\nimport random\nimport gym\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\nEPISODES = 1000\n\nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=2000)\n self.gamma = 0.95 # discount rate\n self.epsilon = 1.0 # exploration rate\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.learning_rate = 0.001\n self.model = self._build_model()\n\n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n model.add(Dense(24, input_dim=self.state_size, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse',\n optimizer=Adam(lr=self.learning_rate))\n return model\n\n def memorize(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def act(self, state):\n if np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n act_values = self.model.predict(state)\n return np.argmax(act_values[0]) # returns action\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in minibatch:\n target = reward\n if not done:\n target = (reward + self.gamma *\n np.amax(self.model.predict(next_state)[0]))\n target_f = self.model.predict(state)\n target_f[0][action] = target\n self.model.fit(state, target_f, epochs=1, verbose=0)\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nif __name__ == \"__main__\":\n env = gym.make('CartPole-v1')\n state_size = env.observation_space.shape[0]\n action_size = env.action_space.n\n agent = DQNAgent(state_size, action_size)\n # agent.load(\"./save/cartpole-dqn.h5\")\n done = False\n batch_size = 32\n\n for e in range(EPISODES):\n state = env.reset()\n state = np.reshape(state, [1, state_size])\n for time in range(500):\n # env.render()\n action = agent.act(state)\n next_state, reward, done, _ = env.step(action)\n reward = reward if not done else -10\n next_state = np.reshape(next_state, [1, state_size])\n agent.memorize(state, action, reward, next_state, done)\n state = next_state\n if done:\n print(\"episode: {}/{}, score: {}, e: {:.2}\"\n .format(e, EPISODES, time, agent.epsilon))\n break\n if len(agent.memory) > batch_size:\n agent.replay(batch_size)\n # if e % 10 == 0:\n # agent.save(\"./save/cartpole-dqn.h5\")"
] |
[
[
"numpy.reshape",
"numpy.argmax",
"numpy.random.rand"
]
] |
leoorshansky/DeepCTR-Torch-MLET
|
[
"54e8f947ac677b5c0afe7967a224fb8d9cceb516"
] |
[
"deepctr_torch/inputs.py"
] |
[
"# -*- coding:utf-8 -*-\n\"\"\"\nAuthor:\n Weichen Shen,wcshen1994@163.com\n\"\"\"\n\nfrom collections import OrderedDict, namedtuple, defaultdict\nfrom itertools import chain\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom .layers.sequence import SequencePoolingLayer\nfrom .layers.utils import concat_fun\n\nDEFAULT_GROUP_NAME = \"default_group\"\n\n\nclass SparseFeat(namedtuple('SparseFeat',\n ['name', 'vocabulary_size', 'embedding_dim', 'use_hash', 'dtype', 'embedding_name',\n 'group_name'])):\n __slots__ = ()\n\n def __new__(cls, name, vocabulary_size, embedding_dim=4, use_hash=False, dtype=\"int32\", embedding_name=None,\n group_name=DEFAULT_GROUP_NAME):\n if embedding_name is None:\n embedding_name = name\n if embedding_dim == \"auto\":\n embedding_dim = 6 * int(pow(vocabulary_size, 0.25))\n if use_hash:\n print(\n \"Notice! Feature Hashing on the fly currently is not supported in torch version,you can use tensorflow version!\")\n return super(SparseFeat, cls).__new__(cls, name, vocabulary_size, embedding_dim, use_hash, dtype,\n embedding_name, group_name)\n\n def __hash__(self):\n return self.name.__hash__()\n\n\nclass VarLenSparseFeat(namedtuple('VarLenSparseFeat',\n ['sparsefeat', 'maxlen', 'combiner', 'length_name'])):\n __slots__ = ()\n\n def __new__(cls, sparsefeat, maxlen, combiner=\"mean\", length_name=None):\n return super(VarLenSparseFeat, cls).__new__(cls, sparsefeat, maxlen, combiner, length_name)\n\n @property\n def name(self):\n return self.sparsefeat.name\n\n @property\n def vocabulary_size(self):\n return self.sparsefeat.vocabulary_size\n\n @property\n def embedding_dim(self):\n return self.sparsefeat.embedding_dim\n\n @property\n def dtype(self):\n return self.sparsefeat.dtype\n\n @property\n def embedding_name(self):\n return self.sparsefeat.embedding_name\n\n @property\n def group_name(self):\n return self.sparsefeat.group_name\n\n def __hash__(self):\n return self.name.__hash__()\n\n\nclass DenseFeat(namedtuple('DenseFeat', ['name', 'dimension', 'dtype'])):\n __slots__ = ()\n\n def __new__(cls, name, dimension=1, dtype=\"float32\"):\n return super(DenseFeat, cls).__new__(cls, name, dimension, dtype)\n\n def __hash__(self):\n return self.name.__hash__()\n\n\ndef get_feature_names(feature_columns):\n features = build_input_features(feature_columns)\n return list(features.keys())\n\n\n# def get_inputs_list(inputs):\n# return list(chain(*list(map(lambda x: x.values(), filter(lambda x: x is not None, inputs)))))\n\n\ndef build_input_features(feature_columns):\n # Return OrderedDict: {feature_name:(start, start+dimension)}\n\n features = OrderedDict()\n\n start = 0\n for feat in feature_columns:\n feat_name = feat.name\n if feat_name in features:\n continue\n if isinstance(feat, SparseFeat):\n features[feat_name] = (start, start + 1)\n start += 1\n elif isinstance(feat, DenseFeat):\n features[feat_name] = (start, start + feat.dimension)\n start += feat.dimension\n elif isinstance(feat, VarLenSparseFeat):\n features[feat_name] = (start, start + feat.maxlen)\n start += feat.maxlen\n if feat.length_name is not None and feat.length_name not in features:\n features[feat.length_name] = (start, start + 1)\n start += 1\n else:\n raise TypeError(\"Invalid feature column type,got\", type(feat))\n return features\n\n\ndef combined_dnn_input(sparse_embedding_list, dense_value_list):\n if len(sparse_embedding_list) > 0 and len(dense_value_list) > 0:\n sparse_dnn_input = torch.flatten(\n torch.cat(sparse_embedding_list, dim=-1), start_dim=1)\n dense_dnn_input = torch.flatten(\n torch.cat(dense_value_list, dim=-1), start_dim=1)\n return concat_fun([sparse_dnn_input, dense_dnn_input])\n elif len(sparse_embedding_list) > 0:\n return torch.flatten(torch.cat(sparse_embedding_list, dim=-1), start_dim=1)\n elif len(dense_value_list) > 0:\n return torch.flatten(torch.cat(dense_value_list, dim=-1), start_dim=1)\n else:\n raise NotImplementedError\n\n\ndef get_varlen_pooling_list(embedding_dict, features, feature_index, varlen_sparse_feature_columns, device):\n varlen_sparse_embedding_list = []\n\n for feat in varlen_sparse_feature_columns:\n seq_emb = embedding_dict[feat.embedding_name](\n features[:, feature_index[feat.name][0]:feature_index[feat.name][1]].long())\n if feat.length_name is None:\n seq_mask = features[:, feature_index[feat.name][0]:feature_index[feat.name][1]].long() != 0\n\n emb = SequencePoolingLayer(mode=feat.combiner, supports_masking=True, device=device)(\n [seq_emb, seq_mask])\n else:\n seq_length = features[:,\n feature_index[feat.length_name][0]:feature_index[feat.length_name][1]].long()\n emb = SequencePoolingLayer(mode=feat.combiner, supports_masking=False, device=device)(\n [seq_emb, seq_length])\n varlen_sparse_embedding_list.append(emb)\n return varlen_sparse_embedding_list\n\n\ndef create_embedding_matrix(feature_columns, init_std=0.0001, linear=False, sparse=False, device='cpu'):\n # Return nn.ModuleDict: for sparse features, {embedding_name: nn.Embedding}\n # for varlen sparse features, {embedding_name: nn.EmbeddingBag}\n sparse_feature_columns = list(\n filter(lambda x: isinstance(x, SparseFeat), feature_columns)) if len(feature_columns) else []\n\n varlen_sparse_feature_columns = list(\n filter(lambda x: isinstance(x, VarLenSparseFeat), feature_columns)) if len(feature_columns) else []\n\n embedding_dict = nn.ModuleDict(\n {feat.embedding_name: nn.Embedding(feat.vocabulary_size, feat.embedding_dim if not linear else 1, sparse=sparse)\n for feat in\n sparse_feature_columns + varlen_sparse_feature_columns}\n )\n\n # for feat in varlen_sparse_feature_columns:\n # embedding_dict[feat.embedding_name] = nn.EmbeddingBag(\n # feat.dimension, embedding_size, sparse=sparse, mode=feat.combiner)\n\n for tensor in embedding_dict.values():\n nn.init.normal_(tensor.weight, mean=0, std=init_std)\n\n return embedding_dict.to(device)\n\nclass MLET_Embedding(nn.Embedding):\n def __init__(self, mlet_dim, num_embeddings, embedding_dim, padding_idx=None,\n max_norm=None, norm_type=2., scale_grad_by_freq=False,\n sparse=False, _weight=None):\n super(nn.Embedding, self).__init__()\n self.mlet_dim = mlet_dim\n self.num_embeddings = num_embeddings\n self.embedding_dim = embedding_dim\n if padding_idx is not None:\n if padding_idx > 0:\n assert padding_idx < self.num_embeddings, 'Padding_idx must be within num_embeddings'\n elif padding_idx < 0:\n assert padding_idx >= -self.num_embeddings, 'Padding_idx must be within num_embeddings'\n padding_idx = self.num_embeddings + padding_idx\n self.padding_idx = padding_idx\n self.max_norm = max_norm\n self.norm_type = norm_type\n self.scale_grad_by_freq = scale_grad_by_freq\n\n shape = [num_embeddings, embedding_dim]\n shape[1:1] = list(mlet_dim) # [num_embeddings, d1, d2, ... , embedding_dim]\n if _weight is None:\n self.weight = [nn.Parameter(torch.Tensor(*tup)) for tup in zip(shape, shape[1:])]\n self.reset_parameters()\n else:\n assert [mat.shape for mat in _weight] == zip(shape, shape[1:]), \\\n 'Shape of weight does not match num_embeddings, mlet_dim, and embedding_dim'\n self.weight = [nn.Parameter(mat) for mat in _weight]\n self.sparse = sparse\n\n def forward(self, input):\n out = torch.nn.functional.embedding(\n input, self.weight[0], self.padding_idx, self.max_norm,\n self.norm_type, self.scale_grad_by_freq, self.sparse)\n for mat in self.weight[1:]:\n out = torch.matmul(out, mat)\n return out\n\n def reset_parameters(self, mean=0, init_std=0.0001):\n for mat in self.weight:\n nn.init.normal_(mat)\n if self.padding_idx is not None:\n with torch.no_grad():\n for mat in self.weight:\n mat[self.padding_idx].fill_(0)\n\n @classmethod\n def from_pretrained(cls, embeddings, mlet_dim, freeze=True, padding_idx=None,\n max_norm=None, norm_type=2., scale_grad_by_freq=False,\n sparse=False):\n embedding = cls(\n num_embeddings=embeddings[0].shape()[0],\n mlet_dim=mlet_dim,\n embedding_dim=embeddings[-1].shape()[1],\n _weight=embeddings,\n padding_idx=padding_idx,\n max_norm=max_norm,\n norm_type=norm_type,\n scale_grad_by_freq=scale_grad_by_freq,\n sparse=sparse)\n for mat in embedding.weight:\n mat.requires_grad = not freeze\n return embedding\n\ndef create_mlet_embeddings(feature_columns, dim, init_std=0.0001, linear=False, sparse=False, device='cpu'):\n # Return nn.ModuleDict: for sparse features, {embedding_name: nn.Embedding}\n # for varlen sparse features, {embedding_name: nn.EmbeddingBag}\n sparse_feature_columns = list(\n filter(lambda x: isinstance(x, SparseFeat), feature_columns)) if len(feature_columns) else []\n\n varlen_sparse_feature_columns = list(\n filter(lambda x: isinstance(x, VarLenSparseFeat), feature_columns)) if len(feature_columns) else []\n\n embedding_dict = nn.ModuleDict(\n {feat.embedding_name: MLET_Embedding(dim, feat.vocabulary_size, feat.embedding_dim if not linear else 1, sparse=sparse)\n for feat in\n sparse_feature_columns + varlen_sparse_feature_columns}\n )\n\n # for feat in varlen_sparse_feature_columns:\n # embedding_dict[feat.embedding_name] = nn.EmbeddingBag(\n # feat.dimension, embedding_size, sparse=sparse, mode=feat.combiner)\n\n for tensor in embedding_dict.values():\n tensor.reset_parameters(init_std=init_std)\n\n return embedding_dict.to(device)\n\ndef input_from_feature_columns(self, X, feature_columns, embedding_dict, support_dense=True):\n sparse_feature_columns = list(\n filter(lambda x: isinstance(x, SparseFeat), feature_columns)) if len(feature_columns) else []\n dense_feature_columns = list(\n filter(lambda x: isinstance(x, DenseFeat), feature_columns)) if len(feature_columns) else []\n\n varlen_sparse_feature_columns = list(\n filter(lambda x: isinstance(x, VarLenSparseFeat), feature_columns)) if feature_columns else []\n\n if not support_dense and len(dense_feature_columns) > 0:\n raise ValueError(\n \"DenseFeat is not supported in dnn_feature_columns\")\n\n sparse_embedding_list = [embedding_dict[feat.embedding_name](\n X[:, self.feature_index[feat.name][0]:self.feature_index[feat.name][1]].long()) for\n feat in sparse_feature_columns]\n\n varlen_sparse_embedding_list = get_varlen_pooling_list(self.embedding_dict, X, self.feature_index,\n varlen_sparse_feature_columns, self.device)\n\n dense_value_list = [X[:, self.feature_index[feat.name][0]:self.feature_index[feat.name][1]] for feat in\n dense_feature_columns]\n\n return sparse_embedding_list + varlen_sparse_embedding_list, dense_value_list\n\n\n\ndef embedding_lookup(X, sparse_embedding_dict, sparse_input_dict, sparse_feature_columns, return_feat_list=(),\n mask_feat_list=(), to_list=False):\n \"\"\"\n Args:\n X: input Tensor [batch_size x hidden_dim]\n sparse_embedding_dict: nn.ModuleDict, {embedding_name: nn.Embedding}\n sparse_input_dict: OrderedDict, {feature_name:(start, start+dimension)}\n sparse_feature_columns: list, sparse features\n return_feat_list: list, names of feature to be returned, defualt () -> return all features\n mask_feat_list, list, names of feature to be masked in hash transform\n Return:\n group_embedding_dict: defaultdict(list)\n \"\"\"\n group_embedding_dict = defaultdict(list)\n for fc in sparse_feature_columns:\n feature_name = fc.name\n embedding_name = fc.embedding_name\n if (len(return_feat_list) == 0 or feature_name in return_feat_list):\n # TODO: add hash function\n # if fc.use_hash:\n # raise NotImplementedError(\"hash function is not implemented in this version!\")\n lookup_idx = np.array(sparse_input_dict[feature_name])\n input_tensor = X[:, lookup_idx[0]:lookup_idx[1]].long()\n emb = sparse_embedding_dict[embedding_name](input_tensor)\n group_embedding_dict[fc.group_name].append(emb)\n if to_list:\n return list(chain.from_iterable(group_embedding_dict.values()))\n return group_embedding_dict\n\n\ndef varlen_embedding_lookup(X, embedding_dict, sequence_input_dict, varlen_sparse_feature_columns):\n varlen_embedding_vec_dict = {}\n for fc in varlen_sparse_feature_columns:\n feature_name = fc.name\n embedding_name = fc.embedding_name\n if fc.use_hash:\n # lookup_idx = Hash(fc.vocabulary_size, mask_zero=True)(sequence_input_dict[feature_name])\n # TODO: add hash function\n lookup_idx = sequence_input_dict[feature_name]\n else:\n lookup_idx = sequence_input_dict[feature_name]\n varlen_embedding_vec_dict[feature_name] = embedding_dict[embedding_name](\n X[:, lookup_idx[0]:lookup_idx[1]].long()) # (lookup_idx)\n\n return varlen_embedding_vec_dict\n\n\ndef get_dense_input(X, features, feature_columns):\n dense_feature_columns = list(filter(lambda x: isinstance(\n x, DenseFeat), feature_columns)) if feature_columns else []\n dense_input_list = []\n for fc in dense_feature_columns:\n lookup_idx = np.array(features[fc.name])\n input_tensor = X[:, lookup_idx[0]:lookup_idx[1]].float()\n dense_input_list.append(input_tensor)\n return dense_input_list\n\n\ndef maxlen_lookup(X, sparse_input_dict, maxlen_column):\n if maxlen_column is None or len(maxlen_column)==0:\n raise ValueError('please add max length column for VarLenSparseFeat of DIEN input')\n lookup_idx = np.array(sparse_input_dict[maxlen_column[0]])\n return X[:, lookup_idx[0]:lookup_idx[1]].long()\n"
] |
[
[
"torch.nn.functional.embedding",
"torch.nn.Parameter",
"torch.Tensor",
"torch.cat",
"torch.nn.Embedding",
"torch.matmul",
"torch.nn.init.normal_",
"torch.no_grad",
"numpy.array"
]
] |
gmagannaDevelop/TousAntiCovid
|
[
"7174845b0614b6a20e48834d5a76579cfbf80bd6"
] |
[
"metrics/probability_analysis.py"
] |
[
"#!/usr/bin/env python3\n\nimport sys\nimport pandas as pd\n\nif __name__ == \"__main__\":\n x = pd.read_csv(sys.argv[1] , header=None)\n x.columns = [\"lambda\", \"doctor\", \"virus\"]\n print(x.describe())\n"
] |
[
[
"pandas.read_csv"
]
] |
alexlyttle/cpnest
|
[
"ae620b5f214a7a2a52e16ef5f2fe7354992aff88"
] |
[
"tests/test_half_gaussian.py"
] |
[
"import sys\nimport unittest\nimport numpy as np\nfrom scipy import integrate,stats\nimport cpnest\nimport cpnest.model\nimport matplotlib as mpl\nmpl.use('Agg')\nfrom matplotlib import pyplot as plt\n\nclass HalfGaussianModel(cpnest.model.Model):\n \"\"\"\n A simple gaussian model with parameters mean and sigma\n \"\"\"\n def __init__(self,xmax=10.0):\n self.distr = stats.norm(loc=0,scale=1.0)\n self.bounds=[[0,xmax]]\n self.names=['x']\n self.analytic_log_Z = np.log(self.distr.cdf(self.bounds[0][1]) - self.distr.cdf(self.bounds[0][0])) \\\n - np.log(self.bounds[0][1]-self.bounds[0][0])\n\n def log_likelihood(self,p):\n return self.distr.logpdf(p['x'])\n\n def force(self,x):\n return np.zeros(1, dtype = {'names':x.names, 'formats':['f8' for _ in x.names]})\n\nclass HalfGaussianTestCase(unittest.TestCase):\n \"\"\"\n Test the gaussian model\n \"\"\"\n def setUp(self,xmax=20):\n self.model=HalfGaussianModel(xmax=xmax)\n self.work=cpnest.CPNest(self.model,verbose=1,nlive=500,nthreads=1)\n self.work.run()\n\n def test_evidence(self):\n # 2 sigma tolerance\n tolerance = 2.0*np.sqrt(self.work.NS.state.info/self.work.NS.Nlive)\n print('2-sigma statistic error in logZ: {0:0.3f}'.format(tolerance))\n print('Analytic logZ {0}'.format(self.model.analytic_log_Z))\n print('Estimated logZ {0}'.format(self.work.NS.logZ))\n pos=self.work.posterior_samples['x']\n #t,pval=stats.kstest(pos,self.model.distr.cdf)\n pos=self.work.posterior_samples['x']\n #t,pval=stats.kstest(pos,self.model.distr.cdf)\n plt.figure()\n plt.hist(pos.ravel(),density=True)\n x=np.linspace(self.model.bounds[0][0],self.model.bounds[0][1],100)\n plt.plot(x,2*self.model.distr.pdf(x))\n plt.savefig('posterior.png')\n plt.figure()\n plt.plot(pos.ravel(),',')\n plt.title('chain')\n plt.savefig('chain.png')\n self.assertTrue(np.abs(self.work.NS.logZ - self.model.analytic_log_Z)<tolerance, 'Incorrect evidence for normalised distribution: {0:.3f} instead of {1:.3f}'.format(self.work.NS.logZ,self.model.analytic_log_Z ))\n\n\ndef test_all():\n unittest.main(verbosity=2)\n\nif __name__=='__main__':\n unittest.main()\n\n"
] |
[
[
"numpy.log",
"numpy.sqrt",
"numpy.linspace",
"matplotlib.pyplot.title",
"numpy.abs",
"matplotlib.use",
"matplotlib.pyplot.savefig",
"scipy.stats.norm",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
trungvdhp/mpsnet
|
[
"e76979e2f8ecd9ea50a0d864533494af2afbb2d4"
] |
[
"Keras_Code/model/nets.py"
] |
[
"from model.adacos import AdaCos\nfrom model.blocks import NetBlock\nfrom tensorflow.keras.layers import Input, Reshape, Conv2D, Activation, Flatten, Dropout, add\nfrom tensorflow.keras.models import Model\nimport tensorflow.keras.backend as K\n\nclass Net:\n \n def __init__(self, config):\n self.model_name = config.model_name\n self.start_fine_tune_layer_id = config.start_fine_tune_layer_id\n self.end_fine_tune_layer_id = config.end_fine_tune_layer_id\n self.embedding_dim = config.embedding_dim\n self.embedding_layer_name = config.embedding_layer_name\n self.dropout = config.dropout\n self.net_blocks = NetBlock(config)\n\n def build_mpsnet_backbone(self, input_shape):\n \n c = [32, 32, 64, 64, 128]\n t = [1, 2, 2, 3, 2]\n s = [2, 2, 2, 2, 1]\n n = [1, 2, 2, 3, 2]\n \n activation='relu'\n I = Input(shape = input_shape)\n \n M0 = self.net_blocks.conv_block(I, c[0], 3, s[0], activation=activation)\n M1 = self.net_blocks.inverted_residual_block(M0, c=c[1], ks=3, t=t[1], s=s[1], n=n[1], activation=activation)\n M0 = self.net_blocks.separable_conv_block(M0, c[1], 3, s[1], activation=None)\n A1 = add([M0, M1])\n \n M2 = self.net_blocks.inverted_residual_block(A1, c=c[2], ks=3, t=t[2], s=s[2], n=n[2], activation=activation)\n A1 = self.net_blocks.separable_conv_block(A1, c[2], 3, s[2], activation=None)\n A2 = add([A1, M2])\n \n M3 = self.net_blocks.inverted_residual_block(A2, c=c[3], ks=3, t=t[3], s=s[3], n=n[3], activation=activation)\n A2 = self.net_blocks.separable_conv_block(A2, c[3], 3, s[3], activation=None)\n A3 = add([A2, M3])\n \n M4 = self.net_blocks.inverted_residual_block(A3, c=c[4], ks=3, t=t[4], s=s[4], n=n[4], activation=activation)\n A3 = self.net_blocks.separable_conv_block(A3, c[4], 3, s[4], activation=None)\n A4 = add([A3, M4])\n \n M = self.net_blocks.spp_block(A4, pool_list=[1, 2, 4])\n \n self.backbone = Model(inputs=I, outputs=M, name=self.model_name)\n \n def build_mobilenet_v1_backbone(self, input_shape, alpha=1.0):\n \n I = Input(shape = input_shape)\n activation = 'relu'\n c = int(32 * alpha)\n\n x = self.net_blocks.conv_block(I, 32, 3, 2, activation=activation)\n\n x = self.net_blocks.bottleneck_v1(x, 64 , 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 128, 3, s=2, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 128, 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 256, 3, s=2, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 256, 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 512, 3, s=2, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 512, 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 512, 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 512, 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 512, 3, s=1, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 512, 3, s=1, alpha=alpha, activation=activation)\n\n x = self.net_blocks.bottleneck_v1(x, 1024, 3, s=2, alpha=alpha, activation=activation)\n x = self.net_blocks.bottleneck_v1(x, 1024, 3, s=1, alpha=alpha, activation=activation)\n\n x = GlobalAveragePooling2D()(x)\n\n self.backbone = Model(inputs=I, outputs=x, name=self.model_name)\n \n def build_mobilenet_v2_backbone(self, input_shape, alpha=1.0):\n \n c = [32, 16, 24, 32, 64, 96, 160, 320, 1280]\n t = [1, 1, 6, 6, 6, 6, 6, 6, 1]\n s = [2, 1, 2, 2, 2, 1, 2, 1, 1]\n n = [1, 1, 2, 3, 4, 3, 3, 1, 1]\n\n activation = 'relu6'\n I = Input(shape = input_shape)\n n_filters = self.net_blocks.make_divisible(c[0] * alpha, 8)\n\n x = self.net_blocks.conv_block(I, n_filters, 3, s[0], activation=activation) # (64, 64, 32) \n\n x = self.net_blocks.inverted_residual_block(x, c=c[1], ks=3, t=t[1], s=s[1], n=n[1], alpha=alpha, activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[2], ks=3, t=t[2], s=s[2], n=n[2], alpha=alpha, activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[3], ks=3, t=t[3], s=s[3], n=n[3], alpha=alpha, activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[4], ks=3, t=t[4], s=s[4], n=n[4], alpha=alpha, activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[5], ks=3, t=t[5], s=s[5], n=n[5], alpha=alpha, activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[6], ks=3, t=t[6], s=s[6], n=n[6], alpha=alpha, activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[7], ks=3, t=t[7], s=s[7], n=n[7], alpha=alpha, activation=activation)\n\n if alpha > 1.0:\n last_filters = self.net_blocks.make_divisible(c[8] * alpha, 8)\n else:\n last_filters = c[8]\n x = self.net_blocks.conv_block(x, last_filters, 1, 1, activation=activation)\n\n x = GlobalAveragePooling2D()(x)\n\n self.backbone = Model(inputs=I, outputs=x, name=self.model_name)\n \n def build_mobilenet_v3_backbone(self, input_shape, alpha=1.0):\n \n I = Input(shape = input_shape)\n \n x = self.net_blocks.conv_block(I, 16, 3 , 2, activation='hard_swish')\n \n x = self.net_blocks.bottleneck_v3(x, 16 , 3, e=16 , s=1, alpha=alpha, squeeze=False, activation='relu6')\n\n x = self.net_blocks.bottleneck_v3(x, 24 , 3, e=64 , s=2, alpha=alpha, squeeze=False, activation='relu6')\n x = self.net_blocks.bottleneck_v3(x, 24 , 3, e=72 , s=1, alpha=alpha, squeeze=False, activation='relu6')\n\n x = self.net_blocks.bottleneck_v3(x, 40 , 5, e=72 , s=2, alpha=alpha, squeeze=True, activation='relu6')\n x = self.net_blocks.bottleneck_v3(x, 40 , 5, e=120, s=1, alpha=alpha, squeeze=True, activation='relu6')\n x = self.net_blocks.bottleneck_v3(x, 40 , 5, e=120, s=1, alpha=alpha, squeeze=True, activation='relu6')\n\n x = self.net_blocks.bottleneck_v3(x, 80 , 3, e=240, s=2, alpha=alpha, squeeze=False, activation='hard_swish')\n x = self.net_blocks.bottleneck_v3(x, 80 , 3, e=200, s=1, alpha=alpha, squeeze=False, activation='hard_swish')\n x = self.net_blocks.bottleneck_v3(x, 80 , 3, e=184, s=1, alpha=alpha, squeeze=False, activation='hard_swish')\n x = self.net_blocks.bottleneck_v3(x, 80 , 3, e=184, s=1, alpha=alpha, squeeze=False, activation='hard_swish')\n\n x = self.net_blocks.bottleneck_v3(x, 112, 3, e=480, s=1, alpha=alpha, squeeze=True, activation='hard_swish')\n x = self.net_blocks.bottleneck_v3(x, 112, 3, e=672, s=1, alpha=alpha, squeeze=True, activation='hard_swish')\n\n x = self.net_blocks.bottleneck_v3(x, 160, 5, e=672, s=2, alpha=alpha, squeeze=True, activation='hard_swish')\n x = self.net_blocks.bottleneck_v3(x, 160, 5, e=960, s=1, alpha=alpha, squeeze=True, activation='hard_swish')\n x = self.net_blocks.bottleneck_v3(x, 160, 5, e=960, s=1, alpha=alpha, squeeze=True, activation='hard_swish')\n\n x = self.net_blocks.conv_block(x, 960, 1, 1, activation='hard_swish')\n\n x = GlobalAveragePooling2D()(x)\n \n self.backbone = Model(inputs=I, outputs=x, name=self.model_name)\n \n def build_mobilefacenet_backbone(self, input_shape, alpha=1.0):\n \n c = [64, 64, 64, 128, 128, 128, 128]\n t = [1, 1, 2, 4, 2, 4, 2]\n s = [2, 1, 2, 2, 1, 2, 1]\n n = [1, 1, 5, 1, 6, 1, 2]\n activation='prelu'\n I = Input(shape = input_shape)\n\n x = self.net_blocks.conv_block(I, c[0], 3, s[0], activation=activation) \n x = self.net_blocks.separable_conv_block(M, c[1], 3, s[1], activation=activation)\n\n x = self.net_blocks.inverted_residual_block(x, c=c[2], ks=3, t=t[2], s=s[2], n=n[2], activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[3], ks=3, t=t[3], s=s[3], n=n[3], activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[4], ks=3, t=t[4], s=s[4], n=n[4], activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[5], ks=3, t=t[5], s=s[5], n=n[5], activation=activation)\n x = self.net_blocks.inverted_residual_block(x, c=c[6], ks=3, t=t[6], s=s[6], n=n[6], activation=activation)\n\n x = self.net_blocks.conv_block(x, 512, 1, 1, 'valid', activation=activation)\n ks = K.int_shape(x)[2]\n x = self.net_blocks.depthwise_conv_block(x, ks, 1, padding='valid', activation=None)\n \n self.backbone = Model(inputs=I, outputs=x, name=self.model_name)\n \n def build_softmax_model(self, n_classes):\n \n I=self.backbone.inputs\n x=self.backbone.outputs[0]\n \n if(len(x.shape)==2):\n c = K.int_shape(x)[self.net_blocks.channel_axis]\n x = Reshape((1, 1, c))(x)\n x = self.net_blocks.conv_block(x, self.embedding_dim, 1, 1, 'valid', activation=None) \n \n if(self.dropout>0):\n x = Dropout(rate=dropout)(x)\n \n x = self.net_blocks.conv_block(x, n_classes, 1, 1, activation='softmax', norm=None)\n x = Reshape((n_classes,))(x)\n \n self.softmax_model = Model(inputs=I, outputs=x, name=self.model_name) \n\n def build_adacos_model(self):\n \n label = Input(shape=(1,), name='label_input')\n softmax = self.softmax_model.outputs[0]\n n_classes = K.int_shape(softmax)[-1]\n inputs = self.softmax_model.inputs[0]\n x = self.softmax_model.layers[self.end_fine_tune_layer_id].output\n \n if(self.dropout>0):\n x = Dropout(rate=dropout)(x)\n \n x = Flatten(name=self.embedding_layer_name)(x)\n \n break_point = len(self.softmax_model.layers) + self.start_fine_tune_layer_id\n \n for layer in self.softmax_model.layers[:break_point]:\n layer.trainable=False\n \n outputs = AdaCos(n_classes, initializer=self.net_blocks.kernel_initializer, regularizer=self.net_blocks.kernel_regularizer, name='adacos')([x, label])\n \n self.adacos_model = Model(inputs = (inputs, label), outputs = outputs, name=self.model_name)\n\n"
] |
[
[
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.models.Model",
"tensorflow.keras.backend.int_shape",
"tensorflow.keras.layers.add",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Input"
]
] |
neerajbafila/pytorch-CNN
|
[
"9828166149b73473138ab54ee45bec054eb9e591"
] |
[
"src/utils/evaluation_model.py"
] |
[
"from unittest import result\nimport torch\nimport os\nimport logging\nfrom src.utils.common import read_yaml, create_directories\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom pathlib import Path\nfrom src import stage_01_get_data\n\n\nSTAGE = \"evaluation_model\"\nlogging.basicConfig(filename=os.path.join('logs', 'running_logs.log'),\n format=\"[%(asctime)s: %(levelname)s: %(module)s]: %(message)s\",\n filemode=\"a\"\n)\n\ndef main(config_path):\n content = read_yaml(config_path)\n trained_model_path = Path(content['artifacts']['model'], content['artifacts']['trained_model'])\n trained_model = torch.load(trained_model_path)\n trained_model.eval()\n DEVICE = \"cuda\" if torch.cuda.is_available() else 'cpu'\n train_data_loader, test_data_loader, label_map = stage_01_get_data.main(config_path)\n test_batch = content['evaluation']['no_of_test_batches']\n no_of_test_batches = test_batch ## 1 batch contain batch_size images\n # LOAD DATA FROM DATALOADER\n \n pred = np.array([])\n actual = np.array([])\n with torch.no_grad():\n\n for i in range(no_of_test_batches):\n\n for images, labels in test_data_loader:\n ##put images and labels in cuda\n images = images.to(DEVICE) # it will contain 32 images as default batchsize=32\n # labels = labels.to(DEVICE)\n\n raw_prediction = trained_model(images) # it will predict the class of images \n prediction = torch.argmax(raw_prediction, dim=1) # give the class have max probability\n\n y_pred = prediction.cpu().numpy() # load in cpu and convert it numpy from torch\n\n pred = np.concatenate((pred,y_pred)) # concatenate data to numpy array\n actual = np.concatenate((actual, labels))\n cm = confusion_matrix(actual, pred)\n logging.info(f\"confusion matrix is {cm}\")\n\n # plot confusion matrix\n fig_path = Path(content['artifacts']['model'], content['artifacts']['confusion_matrix_fig'])\n plt.figure(figsize=(12,10))\n sns.heatmap(cm, annot=True,fmt='d', cbar=False, xticklabels=label_map.values(), yticklabels=label_map.values())\n result = fig_path\n plt.savefig(result)\n plt.show()\n logging.info(f\"confusion matrix figure is saved at {result}\")\n \n\nif __name__ == '__main__':\n logging.info(\"\\n**********************\")\n logging.info(f\">>>>>>>>>{STAGE} started<<<<<<<<<\")\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config\", \"-c\", default=\"config/config.yaml\")\n parsed_arg = parser.parse_args()\n try:\n main(parsed_arg.config)\n logging.info(f\"{STAGE} completed successfully\")\n except Exception as e:\n logging.exception(e)\n print(e)\n raise e"
] |
[
[
"torch.load",
"torch.argmax",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.savefig",
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
dougct/predictability
|
[
"9dbc905b75900477637f3f90a5c4da27c3c778d9"
] |
[
"entropy.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport math\nimport numpy as np\n\n\ndef uniform_entropy(sequence):\n \"\"\"\n Computes the \"random entropy\", that is, the entropy of a uniform distribution.\n\n Equation:\n $H_{uniform} = \\log_{2}(n)$, where n is the number of unique symbols in the input sequence.\n\n Args:\n sequence: a list of symbols.\n\n Returns:\n A float representing the random entropy of the input sequence.\n \"\"\"\n n_unique = len(set(sequence))\n if n_unique == 0:\n return 0.0\n return np.log2(n_unique)\n\n\ndef shannon_entropy(sequence):\n \"\"\"\n Computes H(sequence) using Shannon's formula.\n\n Equation:\n $H_{shannon} = - \\sum p(i) \\log_2{p(i)}$, for each symbol i in the input sequence.\n\n Args:\n sequence: the input sequence of symbols.\n\n Returns:\n A float representing the Shannon entropy of the input sequence.\n \"\"\"\n n = len(sequence)\n if n == 0:\n return 0.0\n _, counts = np.unique(sequence, return_counts=True, axis=0)\n probs = counts / n\n return np.sum((-1) * probs * np.log2(probs))\n\n\ndef joint_entropy(X, Y):\n \"\"\"\n Computes H(X, Y), the joint entropy of X and Y.\n \"\"\"\n probs = []\n for xi in set(X):\n for yi in set(Y):\n probs.append(np.mean(np.logical_and(X == xi, Y == yi)))\n return np.sum(-p * np.log2(p) for p in probs if p > 0)\n\n\ndef conditional_entropy(X, Y):\n \"\"\"\n Computes the conditional entropy of X given Y.\n\n Equation:\n $H(X | Y) = H(X, Y) - H(Y)$\n \"\"\"\n return joint_entropy(X, Y) - shannon_entropy(Y)\n\n\ndef entropy_kontoyiannis(sequence):\n \"\"\"\n Estimate the entropy rate of the sequence using Kontoyiannis' algorithm.\n\n Reference:\n Kontoyiannis, I., Algoet, P. H., Suhov, Y. M., & Wyner, A. J. (1998).\n Nonparametric entropy estimation for stationary processes and random\n fields, with applications to English text. IEEE Transactions on Information\n Theory, 44(3), 1319-1327.\n\n Limits of Predictability in Human Mobility. Chaoming Song, Zehui Qu, \n Nicholas Blumm1, Albert-László Barabási. Vol. 327, Issue 5968, pp. 1018-1021.\n DOI: 10.1126/science.1177170\n\n Equation:\n $H_{kontoyiannis} = \\left( \\frac{1}{n} \\sum \\Lambda_{i} \\right)^{-1}\\log_{2}(n)$\n\n Args:\n sequence: the input sequence of symbols.\n\n Returns:\n A float representing an estimate of the entropy rate of the sequence.\n \"\"\"\n n = len(sequence)\n if n == 0:\n return 0.0\n \n # For the pattern matching below, items in the sequence have to be strings\n sequence = [str(item) for item in sequence]\n\n lambdas = 0\n for i in range(n):\n current_sequence = ''.join(sequence[0:i])\n match = True\n k = i\n while match and k < n:\n k += 1\n match = ''.join(sequence[i:k]) in current_sequence\n lambdas += (k - i)\n return (1.0 * n / lambdas) * np.log2(n)\n\n\ndef longest_match_length(s, i):\n sequence = ''.join(s[0:i])\n k = i\n while k < len(s) and ''.join(s[i:k]) in sequence:\n k += 1\n return k - i\n\n\ndef entropy_kontoyiannis_longest_match(sequence):\n \"\"\"\n Estimate the entropy rate of the sequence using Kontoyiannis' estimator.\n\n Reference:\n Kontoyiannis, I., Algoet, P. H., Suhov, Y. M., & Wyner, A. J. (1998).\n Nonparametric entropy estimation for stationary processes and random\n fields, with applications to English text. IEEE Transactions on Information\n Theory, 44(3), 1319-1327.\n\n Equation:\n $S_{real} = \\left( \\frac{1}{n} \\sum \\Lambda_{i} \\right)^{-1}\\log_{2}(n)$\n\n Args:\n sequence: the input sequence of symbols.\n\n Returns:\n A float representing an estimate of the entropy rate of the sequence.\n \"\"\"\n n = len(sequence)\n if n == 0:\n return 0.0\n\n # For the pattern matching below, items in the sequence have to be strings\n sequence = [str(item) for item in sequence]\n\n lambdas = 0\n for i in range(n):\n match_length = longest_match_length(sequence, i)\n lambdas += (match_length + 1)\n return (1.0 * n / lambdas) * np.log2(n)\n\n\ndef baseline_entropy_kontoyiannis(sequence):\n \"\"\"\"\n Computes the baseline entropy of the input sequence by creating a baseline\n sequence and running Kontoyiannis et al.'s entropy estimator on it.\n\n Reference: \n https://epjdatascience.springeropen.com/articles/10.1140/epjds/s13688-021-00304-8\n\n Args:\n sequence: the input sequence of symbols.\n\n Returns:\n A float indicating an estimate of the baseline entropy of the sequence.\n \"\"\"\n if not sequence:\n return 0.0\n\n n = len(sequence)\n unique_symbols = set(sequence)\n n_unique = len(unique_symbols)\n baseline_sequence = [sequence[0]] * (n - n_unique) + list(unique_symbols)\n return entropy_kontoyiannis(baseline_sequence)\n\n\ndef baseline_entropy(sequence):\n \"\"\"\"\n Computes the baseline entropy of the input sequence using a closed-formula. \n The baseline entropy is the entropy of a sequence with the same size as the\n original sequence, the same number of symbols in the novelty component, and \n a completely predictable routine component. \n\n Notice that for sequences of size less than 100, the estimates are not very\n reliable. For longer sequences, this closed formula should give a very good\n approximation for the baseline entropy, without having to build the \n sequence and then run Kontoyiannis et al.'s entropy estimator on it.\n\n Reference: \n https://epjdatascience.springeropen.com/articles/10.1140/epjds/s13688-021-00304-8\n\n Args:\n sequence: the input sequence of symbols.\n\n Returns:\n A float indicating an estimate of the baseline entropy of the sequence.\n \"\"\"\n n = len(sequence)\n m = len(set(sequence))\n k = n - m + 1\n baseline_routine_size = math.ceil((k * k) / 4 + k / 2)\n baseline_novelty_size = m\n return (n * np.log2(n)) / (baseline_routine_size + baseline_novelty_size)\n\n\n# The three functions below are wrappers to the functions previously defined.\n# The sole purpuse of these functions below is to follow the naming conventions\n# defined in Song et al.'s paper (Limits of Predictability in Human Mobility).\n# In the paper, they define three types of entropy: s_rand, s_unc, and s_real.\n\ndef s_rand(sequence):\n return uniform_entropy(sequence)\n\ndef s_unc(sequence):\n return shannon_entropy(sequence)\n\ndef s_real(sequence):\n return entropy_kontoyiannis(sequence)\n\n"
] |
[
[
"numpy.log2",
"numpy.logical_and",
"numpy.unique"
]
] |
goesslfabian/unify-eval
|
[
"ced486e44ca57ed31b552fd20b53cae61015e486"
] |
[
"unify_eval/utils/load_data.py"
] |
[
"import abc\nimport sys\nfrom abc import ABC\nfrom typing import List, Iterator, Dict, Callable\n\nimport numpy as np\nfrom tqdm import tqdm\n\n\nclass DataLoader(ABC):\n @abc.abstractmethod\n def next_minibatch(self, minibatch_size: int = 16):\n pass\n\n @abc.abstractmethod\n def is_exhausted(self) -> bool:\n pass\n\n def yield_minibatches(self, minibatch_size: int = 16):\n while not self.is_exhausted():\n yield self.next_minibatch(minibatch_size=minibatch_size)\n\n @abc.abstractmethod\n def reset(self) -> \"DataLoader\":\n pass\n\n @abc.abstractmethod\n def is_lazy(self) -> bool:\n pass\n\n\nclass EagerDataLoader(DataLoader):\n\n def is_lazy(self) -> bool:\n return False\n\n @abc.abstractmethod\n def n_datapoints(self) -> int:\n pass\n\n def n_minibatches(self, minibatch_size: int) -> int:\n return int(np.ceil(self.n_datapoints() / minibatch_size))\n\n def yield_minibatches(self, minibatch_size: int = 16, progress_bar: bool = True):\n raw_yield = super().yield_minibatches(minibatch_size)\n return tqdm(iterable=raw_yield,\n total=self.n_minibatches(minibatch_size=minibatch_size),\n file=sys.stdout) if progress_bar else raw_yield\n\n\nclass LazyDataLoader(DataLoader):\n\n def is_lazy(self) -> bool:\n return True\n\n\nclass RandomIndicesLoader(EagerDataLoader):\n \"\"\"\n samples random indices given a batch size and max index\n \"\"\"\n\n def __init__(self, max_index: int):\n self.max_index = max_index\n self.n_minibatches = 0\n\n def is_exhausted(self):\n return False\n\n def next_minibatch(self, minibatch_size: int = 16) -> np.ndarray:\n minibatch_size = np.min([self.max_index, minibatch_size])\n return np.random.choice(self.max_index, minibatch_size, replace=False)\n\n def reset(self) -> \"DataLoader\":\n return self\n\n def n_datapoints(self) -> int:\n return self.max_index\n\n\nclass IndicesLoader(EagerDataLoader):\n \"\"\"\n loads indices given max index and batch size. If exhausted, it can be reset\n \"\"\"\n\n def __init__(self, max_index: int):\n self.max_index = max_index\n self.current_start_index = 0\n\n def next_minibatch(self, minibatch_size: int = 16) -> np.ndarray:\n upper_bound = np.min([self.current_start_index + minibatch_size, self.max_index])\n indices = np.arange(self.current_start_index, upper_bound)\n self.current_start_index = upper_bound\n return indices\n\n def is_exhausted(self) -> bool:\n return self.max_index == self.current_start_index\n\n def reset(self) -> \"DataLoader\":\n self.current_start_index = 0\n return self\n\n def n_datapoints(self) -> int:\n return self.max_index\n\n\nclass BatchLoader(EagerDataLoader):\n \"\"\"\n loads samples from n different sources, given a batch size. If exhausted, it can be reset\n \"\"\"\n\n def __init__(self, *data: np.ndarray):\n self.data = data\n self._indices_loader = IndicesLoader(data[0].shape[0])\n\n def next_minibatch(self, minibatch_size: int = 16) -> List[np.ndarray]:\n indices = self._indices_loader.next_minibatch(minibatch_size=minibatch_size)\n return [d[indices] for d in self.data]\n\n def reset(self) -> DataLoader:\n self._indices_loader.reset()\n return self\n\n def is_exhausted(self) -> bool:\n return self._indices_loader.is_exhausted()\n\n def n_datapoints(self) -> int:\n return self._indices_loader.max_index\n\n\nclass KeyedBatchLoader(EagerDataLoader):\n \"\"\"\n loads samples from n different sources, given a batch size. If exhausted, it can be reset\n \"\"\"\n\n def __init__(self, **data: np.ndarray):\n self.data = data\n self._indices_loader = IndicesLoader(data[list(data.keys())[0]].shape[0])\n\n def next_minibatch(self, minibatch_size: int = 16) -> Dict[str, np.ndarray]:\n indices = self._indices_loader.next_minibatch(minibatch_size=minibatch_size)\n return dict((k, d[indices]) for k, d in self.data.items())\n\n def reset(self) -> DataLoader:\n self._indices_loader.reset()\n return self\n\n def is_exhausted(self) -> bool:\n return self._indices_loader.is_exhausted()\n\n def n_datapoints(self) -> int:\n return self._indices_loader.max_index\n\n\nclass KeyedSubsampledBatchLoader(EagerDataLoader):\n \"\"\"\n same as KeyedCorpusBatchLoader, but yielded full batch only consists of subset of actual full batch\n \"\"\"\n\n def __init__(self, n_subsampled: int, **data: np.ndarray):\n self.data = data\n data_length = data[list(data.keys())[0]].shape[0]\n self.n_subsampled = np.min([n_subsampled, data_length])\n self.current_subsampled_indices = np.random.choice(data_length, n_subsampled, replace=False)\n self._current_data = dict((k, v[self.current_subsampled_indices]) for k, v in self.data.items())\n self._indices_loader = IndicesLoader(self.current_subsampled_indices.shape[0])\n\n def next_minibatch(self, minibatch_size: int = 16) -> Dict[str, np.ndarray]:\n indices = self.current_subsampled_indices[self._indices_loader.next_minibatch(minibatch_size=minibatch_size)]\n return dict((k, d[indices]) for k, d in self.data.items())\n\n def reset(self) -> DataLoader:\n self.current_subsampled_indices = np.random.choice(self.data[list(self.data.keys())[0]].shape[0],\n self.n_subsampled,\n replace=False)\n self._current_data = dict((k, v[self.current_subsampled_indices]) for k, v in self.data.items())\n self._indices_loader = IndicesLoader(self.current_subsampled_indices.shape[0])\n return self\n\n def is_exhausted(self) -> bool:\n return self._indices_loader.is_exhausted()\n\n def n_datapoints(self) -> int:\n return self._indices_loader.max_index\n\n\nclass KeyedLazyDataLoader(LazyDataLoader):\n \"\"\"\n lazily loads data from some iterators. Iterators might be cyclic / infinitely long\n \"\"\"\n\n def __init__(self, **data_iterators: object) -> object:\n self.data_iterators = data_iterators\n\n def next_minibatch(self, minibatch_size: int = 16) -> Dict[str, np.ndarray]:\n data = dict((key, []) for key in self.data_iterators)\n for i in range(minibatch_size):\n try:\n for key, data_iterator in self.data_iterators.items():\n data[key].append(next(data_iterator))\n except:\n break\n\n return dict((key, np.array(d)) for key, d in data.items())\n\n def is_exhausted(self) -> bool:\n return False\n\n def reset(self) -> \"KeyedLazyDataLoader\":\n return self\n\n\nclass FiniteKeyedLazyDataLoader(KeyedLazyDataLoader):\n \"\"\"\n same as KeyedLazyDataLoader, but expects data iterators to be finite.\n Useful for instance for finite but big data sets to be loaded lazily\n \"\"\"\n\n def __init__(self, n_datapoints: int, **data_iterator_factories: Callable[[], Iterator]):\n super().__init__(**dict((k, v()) for k, v in data_iterator_factories.items()))\n self.data_iterator_factories = data_iterator_factories\n self.n_datapoints = n_datapoints\n self._is_exhausted = False\n\n def n_minibatches(self, minibatch_size: int) -> int:\n return int(np.ceil(self.n_datapoints / minibatch_size))\n\n def next_minibatch(self, minibatch_size: int = 16) -> Dict[str, np.ndarray]:\n\n data = dict((key, []) for key in self.data_iterators)\n for i in range(minibatch_size):\n try:\n for key, data_iterator in self.data_iterators.items():\n data[key].append(next(data_iterator))\n self._is_exhausted = False\n except:\n self._is_exhausted = True\n break\n return dict((key, np.array(d)) for key, d in data.items())\n\n def is_exhausted(self) -> bool:\n return self._is_exhausted\n\n def reset(self) -> \"FiniteKeyedLazyDataLoader\":\n self.data_iterators = dict((k, v()) for k, v in self.data_iterator_factories.items())\n self._is_exhausted = False\n return self\n\n def yield_minibatches(self, minibatch_size: int = 16, progress_bar: bool = True):\n raw_yield = super().yield_minibatches(minibatch_size)\n if progress_bar:\n return tqdm(iterable=raw_yield,\n total=self.n_minibatches(minibatch_size=minibatch_size),\n file=sys.stdout)\n return raw_yield\n\n\nclass CyclicIterator(Iterator):\n def __init__(self, iterator_factory):\n self.iterator_factory = iterator_factory\n self.iterator = self.iterator_factory()\n\n def __next__(self):\n try:\n return next(self.iterator)\n except:\n self.iterator = self.iterator_factory()\n return next(self.iterator)\n\n def __iter__(self) -> Iterator:\n return self\n"
] |
[
[
"numpy.random.choice",
"numpy.min",
"numpy.arange",
"numpy.ceil",
"numpy.array"
]
] |
dennis-j-lee/AirNet-SNL
|
[
"c35b84b50b7f1351a450a5970b19d8a8b83053d1"
] |
[
"airnetSNL/model/train_loop.py"
] |
[
"import errno\nimport numpy as np\nimport os\nimport torch\nfrom torch.nn import functional as F\n\n\ndef train_model(model: torch.nn.Module,\n optimizer: torch.optim.Adam,\n train_loader: torch.utils.data.DataLoader,\n nEpochs: int,\n saveModel: bool = False,\n resumeFrom: int = 0,\n saveFilePath: str = '',\n loadFilePath: str = ''):\n \"\"\"Train a model.\n\n Args:\n * model (Module): Model to be trained.\n * optimizer (Adam): Optimization parameters, e.g. learning rate.\n * train_loader (DataLoader): Dataset parameters, e.g. batch size.\n * nEpochs (int): Number of epochs for training.\n * saveModel (bool): Save model if loss improves.\n * resumeFrom (int): Resume training from epoch number.\n * saveFilePath (str): Where to save the model.\n * loadFilePath (str): Which model to load.\n\n Example:\n .. code-block:: python\n :linenos:\n\n import airnetSNL.model.train_loop as tl\n import airnetSNL.model.airnet_snl as snl\n import airnetSNL.dataset.dataset_utils as du\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n from torch import optim\n\n angles = du.decimateAngles(nAnglesFull=451,\n downsample=8)\n imgSize = 336\n batchSize = 10\n model = snl.AirNetSNL(angles=angles,\n n_iterations=12,\n n_cnn=10,\n imgSize=imgSize,\n batchSize=batchSize,\n includeSkipConnection=False)\n\n optimizer = optim.Adam(model.parameters(), lr=1e-5)\n\n trainSinograms = torch.zeros(100, 1, len(angles), imgSize)\n trainImages = torch.zeros(100, 1, imgSize, imgSize)\n trainSet = TensorDataset(trainSinograms, trainImages)\n trainLoader = DataLoader(trainSet, batch_size=batchSize)\n\n tl.train_model(model=model,\n optimizer=optimizer,\n train_loader=trainLoader,\n nEpochs=1,\n saveModel=False,\n resumeFrom=0,\n saveFilePath='./testModel.pth')\n\n \"\"\"\n\n def train_one_batch(x_sinogram, y_img_gt):\n y_img_pred = model(x_sinogram)\n loss = F.mse_loss(y_img_pred, y_img_gt)\n\n optimizer.zero_grad() # Clears Gradient\n loss.backward() # Calculate Gradients\n optimizer.step() # Update Weights\n\n loss = loss.item()\n return loss\n\n def train_epoch():\n total_loss = 0\n\n for x_sinogram, y_img in train_loader:\n x_sinogram = x_sinogram.to('cuda')\n y_img = y_img.to('cuda')\n batch_loss = train_one_batch(x_sinogram, y_img)\n total_loss += batch_loss\n\n return total_loss\n\n def save_model(epoch_num):\n state = {\n 'epoch': epoch_num,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss_per_epoch': loss_per_epoch,\n }\n torch.save(state, saveFilePath)\n\n model.cuda()\n if not saveFilePath:\n raise ValueError(\"Need to specify saveFilePath to save model.\")\n\n saved_epoch = 0\n loss_per_epoch = -1 * torch.ones(nEpochs)\n loss_per_epoch = loss_per_epoch.type(torch.cuda.FloatTensor).cuda()\n\n if resumeFrom > 0:\n if not os.path.isfile(loadFilePath):\n raise FileNotFoundError(errno.ENOENT,\n os.stderror(errno.ENOENT),\n loadFilePath)\n checkpoint = torch.load(loadFilePath)\n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n saved_epoch = checkpoint['epoch']\n saved_loss = checkpoint['loss_per_epoch']\n\n # Initialize loss_per_epoch with saved_loss\n if len(saved_loss) < nEpochs:\n loss_per_epoch = -1 * np.ones(nEpochs)\n loss_per_epoch[:len(saved_loss)] = saved_loss\n print('Loaded model!')\n\n print(f'saved_epoch = {saved_epoch}, nEpochs = {nEpochs}')\n\n save_interval = 1\n minLoss = torch.tensor(1e9).type(torch.cuda.FloatTensor).cuda()\n for e in range(saved_epoch, nEpochs):\n total_loss = train_epoch()\n loss_per_epoch[e] = total_loss\n\n # Save model if loss decreases\n if e % save_interval == 0 and saveModel and total_loss < minLoss:\n minLoss = total_loss\n save_model(e)\n print(f'epoch = {e}, loss = {total_loss}, saved!')\n else:\n print(f'epoch = {e}, loss = {total_loss}')\n\n # Save if checkpoint before nEpochs\n if saved_epoch < nEpochs and saveModel:\n epoch = nEpochs - 1\n save_model(epoch)\n print('Saved model!')\n\n\ndef run_inference(testLoader, model, filepath, isFileDict=True):\n \"\"\"Run the AirNet-SNL model by passing it in the argument.\n\n Args:\n * testLoader (DataLoader): Dataset for running inference.\n * model (nn.Module): Use this model for inference.\n * filepath (str): Saved model weights.\n * isFileDict (bool): True if filepath is a dictionary\n\n Returns:\n Predictions: Tensor of size [nSamples, 1, imgSize, imgSize].\n\n Example:\n .. code-block:: python\n :linenos:\n\n import airnetSNL.model.airnet_snl as snl\n import airnetSNL.dataset.dataset_utils as du\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n angles = du.decimateAngles(nAnglesFull=451,\n downsample=8)\n imgSize = 336\n batchSize = 10\n totalSamples = 100\n\n model = snl.AirNetSNL(angles=angles,\n n_iterations=12,\n n_cnn=10,\n imgSize=imgSize,\n batchSize=batchSize,\n includeSkipConnection=False)\n model = model.cuda()\n filepath = './model.pth'\n testSinograms = torch.zeros(totalSamples, 1, len(angles), imgSize)\n testImages = torch.zeros(totalSamples, 1, imgSize, imgSize)\n testSet = TensorDataset(testSinograms.cpu(), testImages.cpu())\n testLoader = DataLoader(testSet, batch_size=batchSize)\n y_img_pred = run_inference(testLoader, model, filepath)\n\n \"\"\"\n\n if not filepath:\n raise ValueError(\"Need to specify filepath to load model.\")\n if isFileDict:\n checkpoint = torch.load(filepath)\n model.load_state_dict(checkpoint['model_state_dict'])\n else:\n model.load_state_dict(torch.load(filepath))\n\n model.eval().cuda()\n totalLoss = 0\n for i, (xSino, yImg) in enumerate(testLoader):\n xSino_gpu = xSino.to('cuda')\n\n pred = model(xSino_gpu).data.cpu()\n loss = F.mse_loss(pred, yImg)\n loss += loss.item()\n totalLoss += loss\n print(f'totalLoss = {totalLoss}')\n\n if i == 0:\n preds = pred\n else:\n preds = torch.cat((preds, pred), dim=0)\n\n return preds\n"
] |
[
[
"torch.ones",
"torch.cat",
"torch.load",
"numpy.ones",
"torch.tensor",
"torch.nn.functional.mse_loss",
"torch.save"
]
] |
jayunit100/katib
|
[
"d6ea2d5b3ce5a2ca454b079e18e0dc0d4f7dfeed"
] |
[
"pkg/suggestion/bayesianoptimization/src/algorithm_manager.py"
] |
[
"\"\"\" module for algorithm manager \"\"\"\n\nimport numpy as np\n\nfrom pkg.api.python import api_pb2\nimport logging\nfrom logging import getLogger, StreamHandler, INFO, DEBUG\n\ndef deal_with_discrete(feasible_values, current_value):\n \"\"\" function to embed the current values to the feasible discrete space\"\"\"\n diff = np.subtract(feasible_values, current_value)\n diff = np.absolute(diff)\n return feasible_values[np.argmin(diff)]\n\ndef deal_with_categorical(feasible_values, one_hot_values):\n \"\"\" function to do the one hot encoding of the categorical values \"\"\"\n #index = np.argmax(one_hot_values)\n index = one_hot_values.argmax()\n return feasible_values[int(index)]\n\nclass AlgorithmManager:\n \"\"\" class for the algorithm manager\n provide some helper functions\n \"\"\"\n def __init__(self, study_id, study_config, X_train, y_train, logger=None):\n if logger == None:\n self.logger = getLogger(__name__)\n FORMAT = '%(asctime)-15s StudyID %(studyid)s %(message)s'\n logging.basicConfig(format=FORMAT)\n handler = StreamHandler()\n handler.setLevel(DEBUG)\n self.logger.setLevel(DEBUG)\n self.logger.addHandler(handler)\n self.logger.propagate = False\n else:\n self.logger = logger\n self._study_id = study_id\n self._study_config = study_config\n self._goal = self._study_config.optimization_type\n self._dim = 0\n self._lowerbound = []\n self._upperbound = []\n self._types = []\n self._names = []\n # record all the feasible values of discrete type variables\n self._discrete_info = []\n self._categorical_info = []\n self._name_id = {}\n\n self._parse_config()\n\n self._X_train = self._mapping_params(X_train)\n self.parse_X()\n\n self._y_train = y_train\n self._parse_metric()\n\n @property\n def study_id(self):\n \"\"\" return the study id \"\"\"\n return self._study_id\n\n @property\n def study_config(self):\n \"\"\" return the study configuration \"\"\"\n return self._study_config\n\n @property\n def goal(self):\n \"\"\" return the optimization goal\"\"\"\n return self._goal\n\n @property\n def dim(self):\n \"\"\" return the dimension \"\"\"\n return self._dim\n\n @property\n def lower_bound(self):\n \"\"\" return the lower bound of all the parameters \"\"\"\n return self._lowerbound\n\n @property\n def upper_bound(self):\n \"\"\" return the ipper bound of all the parameters \"\"\"\n return self._upperbound\n\n @property\n def types(self):\n \"\"\" return the types of all the parameters \"\"\"\n return self._types\n\n @property\n def names(self):\n \"\"\" return the names of all the parameters \"\"\"\n return self._names\n\n @property\n def discrete_info(self):\n \"\"\" return the info of all the discrete parameters \"\"\"\n return self._discrete_info\n\n @property\n def categorical_info(self):\n \"\"\" return the info of all the categorical parameters \"\"\"\n return self._categorical_info\n\n @property\n def X_train(self):\n \"\"\" return the training data \"\"\"\n return self._X_train\n\n @property\n def y_train(self):\n \"\"\" return the target of the training data\"\"\"\n return self._y_train\n\n def _parse_config(self):\n \"\"\" extract info from the study configuration \"\"\"\n for i, param in enumerate(self._study_config.parameter_configs.configs):\n self._name_id[param.name]=i\n self._types.append(param.parameter_type)\n self._names.append(param.name)\n if param.parameter_type == api_pb2.DOUBLE or param.parameter_type == api_pb2.INT:\n self._dim = self._dim + 1\n self._lowerbound.append(float(param.feasible.min))\n self._upperbound.append(float(param.feasible.max))\n elif param.parameter_type == api_pb2.DISCRETE:\n self._dim = self._dim + 1\n discrete_values = [int(x) for x in param.feasible.list]\n min_value = min(discrete_values)\n max_value = max(discrete_values)\n self._lowerbound.append(min_value)\n self._upperbound.append(max_value)\n self._discrete_info.append(dict({\n \"name\": param.name,\n \"values\": discrete_values,\n }))\n # one hot encoding for categorical type\n elif param.parameter_type == api_pb2.CATEGORICAL:\n num_feasible = len(param.feasible.list)\n for i in range(num_feasible):\n self._lowerbound.append(0)\n self._upperbound.append(1)\n self._categorical_info.append(dict({\n \"name\": param.name,\n \"values\": param.feasible.list,\n \"number\": num_feasible,\n }))\n self._dim += num_feasible\n\n def _mapping_params(self, parameters_list):\n if len(parameters_list) == 0:\n return None\n ret = []\n for parameters in parameters_list:\n maplist = [np.zeros(1)]*len(self._names)\n for p in parameters:\n self.logger.debug(\"mapping: %r\", p, extra={\"StudyID\": self._study_id})\n map_id = self._name_id[p.name]\n if self._types[map_id] == api_pb2.DOUBLE or self._types[map_id] == api_pb2.INT or self._types[map_id] == api_pb2.DISCRETE:\n maplist[map_id] = float(p.value)\n elif self._types[map_id] == api_pb2.CATEGORICAL:\n for ci in self._categorical_info:\n if ci[\"name\"] == p.name:\n maplist[map_id] = np.zeros(ci[\"number\"])\n for i, v in enumerate(ci[\"values\"]):\n if v == p.value:\n maplist[map_id][i]=1\n break\n self.logger.debug(\"mapped: %r\", maplist, extra={\"StudyID\": self._study_id})\n ret.append(np.hstack(maplist))\n return ret\n\n def _parse_metric(self):\n \"\"\" parse the metric to the dictionary \"\"\"\n if not self._y_train:\n self._y_train = None\n return\n y = []\n for metric in self._y_train:\n if self._goal == api_pb2.MAXIMIZE:\n y.append(float(metric))\n else:\n y.append(-float(metric))\n self.logger.debug(\"Ytrain: %r\", y, extra={\"StudyID\": self._study_id})\n self._y_train = np.array(y)\n\n def parse_X(self):\n if not self._X_train:\n self._X_train = None\n return\n self.logger.debug(\"Xtrain: %r\", self._X_train, extra={\"StudyID\": self._study_id})\n self._X_train = np.array(self._X_train)\n\n def parse_x_next(self, x_next):\n \"\"\" parse the next suggestion to the proper format \"\"\"\n counter = 0\n result = []\n for i in range(len(self._types)):\n if self._types[i] == api_pb2.INT:\n result.append(int(round(x_next[counter], 0)))\n counter = counter + 1\n elif self._types[i] == api_pb2.DISCRETE:\n for param in self._discrete_info:\n if param[\"name\"] == self._names[i]:\n result.append(\n deal_with_discrete(param[\"values\"], x_next[counter])\n )\n counter = counter + 1\n break\n elif self._types[i] == api_pb2.CATEGORICAL:\n for param in self._categorical_info:\n if param[\"name\"] == self._names[i]:\n result.append(deal_with_categorical(\n feasible_values=param[\"values\"],\n one_hot_values=x_next[counter:counter + param[\"number\"]],\n ))\n counter = counter + param[\"number\"]\n break\n elif self._types[i] == api_pb2.DOUBLE:\n result.append(x_next[counter])\n counter = counter + 1\n return result\n\n def convert_to_dict(self, x_next):\n \"\"\" convert the next suggestion to the dictionary \"\"\"\n result = []\n for i in range(len(x_next)):\n tmp = dict({\n \"name\": self._names[i],\n \"value\": x_next[i],\n \"type\": self._types[i],\n })\n result.append(tmp)\n return result\n\n"
] |
[
[
"numpy.hstack",
"numpy.absolute",
"numpy.subtract",
"numpy.argmin",
"numpy.array",
"numpy.zeros"
]
] |
maryamhgf/Heterogeneous-Multiscale-
|
[
"dd41532a98603d7b75a035b14d28586dd4133baa"
] |
[
"examples/Toy_Example_HMM.py"
] |
[
"#run export PYTHONPATH=\"${PYTHONPATH}:/home/mhaghifam/Documents/Research/Neural-ODE/Code/torchdiffeq/torchdiffeq\" to be able to import torchdiffeq\n\nimport os\nimport argparse\nimport time\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\n\nimport os\nimport psutil\nimport tracemalloc\n\n# inner psutil function\ndef process_memory():\n process = psutil.Process(os.getpid())\n mem_info = process.memory_info()\n return mem_info.rss\n \n# decorator function\ndef profile(func):\n def wrapper(*args, **kwargs):\n \n mem_before = process_memory()\n result = func(*args, **kwargs)\n mem_after = process_memory()\n print(\"{}:consumed memory: {:,}\".format(\n func.__name__,\n mem_before, mem_after, mem_after - mem_before))\n \n return result\n return wrapper\n\ntorch.pi = torch.acos(torch.zeros(1)).item() * 2\n\nparser = argparse.ArgumentParser('ODE demo')\nparser.add_argument('--method', type=str, choices=['dopri5', 'adams'], default='dopri5')\nparser.add_argument('--data_size', type=int, default=500)\nparser.add_argument('--batch_time', type=int, default=100)\nparser.add_argument('--fast_batch_time', type=int, default=100)\nparser.add_argument('--batch_size', type=int, default=64)\nparser.add_argument('--niters', type=int, default=1000)\nparser.add_argument('--test_freq', type=int, default=40)\nparser.add_argument('--fast_step', type=int, default=10)\nparser.add_argument('--viz', action='store_true')\nparser.add_argument('--gpu', type=int, default=0)\nparser.add_argument('--adjoint', action='store_true')\nargs = parser.parse_args()\nprint(args.adjoint)\nif args.adjoint:\n from torchdiffeq import odeint_adjoint as odeint\nelse:\n from torchdiffeq import odeint\n\n\ndevice = torch.device('cuda:' + str(args.gpu) if torch.cuda.is_available() else 'cpu')\n\n\ndef generate_stellar_orbits(a=2, b=3, epslion=0.009):\n ts = torch.linspace(0., 0.03, args.data_size).to(device)\n data = []\n t_prev = ts[0]\n A = torch.tensor([[0., a, 0., 0.], [-a, 0., 0., 0.], [0., 0., 0., b], [0., 0., -b, 0.]])\n y_0 = torch.tensor([[1., 0., 1., 0]])\n y = y_0\n for t in ts:\n dt = t - t_prev\n f = torch.tensor([[0., y[0][1]**2/a, 0., (2*y[0][0]*y[0][1])/b]])\n y = y + dt * ((1/epslion) * A@y.T + f.T).T\n t_prev = t\n data.append(y)\n return data, ts\n\ndef extract_modes(data, index_slow, index_fast):\n slow = [item[0][index_slow] for item in data]\n fast = [item[0][index_fast] for item in data]\n return slow, fast\n\ndef time_series_sampling(slow, fast, data_t, slow_step_size=None, fast_step_size=None, fast_size=args.fast_step):\n dt = data_t[1] - data_t[0]\n if(slow_step_size == None):\n slow_step_size = dt * 12\n if(fast_step_size == None):\n fast_step_size = dt/3\n slow_step = int(slow_step_size/dt)\n fast_step = int(fast_step_size/dt)\n if(slow_step == 0):\n slow_step = 1\n if(fast_step == 0):\n fast_step = 1\n t_slow = [data_t[i * slow_step] for i in range(int(len(data_t)/slow_step))]\n t_fast = [[data_t[data_t.index(sample_t) + i*fast_step] for i in range(min(fast_size, int(len(data_t) - data_t.index(sample_t)/fast_step)))] for sample_t in t_slow]\n data_slow = [slow[i * slow_step] for i in range(int(len(slow)/slow_step))]\n data_fast = [[fast[data_t.index(sample_t) + i*fast_step] for i in range(min(fast_size, int(len(fast) - data_t.index(sample_t)/fast_step)))] for sample_t in t_slow]\n print(len(t_slow))\n for i in range(len(data_fast)):\n if(len(data_fast[i]) != fast_size):\n for j in range(fast_size - len(data_fast[i])):\n data_fast[i].append(data_fast[i][-1])\n t_fast[i].append(t_fast[i][-1])\n return t_slow, t_fast, torch.tensor(data_slow), torch.tensor(data_fast)\n\ndef convert_to_float(lst):\n output = []\n for element in lst:\n output.append(float(element))\n return output\n\ntrue_y_0 = [torch.tensor([[1., 0., 1., 0]])]\ntrue_y0_slow, true_y0_fast = extract_modes(true_y_0, 0, 3)\ndata, ts = generate_stellar_orbits()\ndata_slow, data_fast = extract_modes(data, 0, 2)\nt_slow, t_fast, slow, fast = time_series_sampling(data_slow, data_fast, convert_to_float(ts))\n\ndef plot_data(fast, slow, t_slow, t_fast, title=None, xlabel=None, ylabel=None):\n plt.figure()\n slow_int = convert_to_float(slow)\n if(len(fast.shape) == 2):\n fast_one_dim = fast[:, :1]\n fast_one_dim.reshape([len(fast)])\n fast = fast_one_dim\n fast_int = convert_to_float(fast)\n plt.plot(t_slow, slow_int, '--go', label=\"slow\")\n plt.plot(t_slow, fast_int, '--bo', label=\"fast\")\n plt.legend(loc=\"upper left\")\n if(title != None):\n plt.title(title)\n if(xlabel != None):\n plt.xlabel(xlabel)\n if(ylabel != None):\n plt.ylabel(ylabel)\n plt.savefig(title+\".png\")\n\nplot_data(fast, slow, t_slow, t_fast, title=\"input\")\ndef get_batch(true_y_slow, true_y_fast, ts, ts_fast):\n s = torch.from_numpy(np.random.choice(np.arange(len(ts) - args.batch_time, dtype=np.int64), args.batch_size, replace=False))\n print(\"true y_fast\", true_y_fast.shape, s.shape)\n batch_y0_slow = true_y_slow[s] # (M, D)\n batch_y0_fast = true_y_fast[s] # (M, D)\n batch_t = ts[:args.batch_time] # (T)\n batch_t_fast = ts_fast[:args.batch_time]\n batch_y_slow = torch.stack([true_y_slow[s + i] for i in range(args.batch_time)], dim=0) # (T, M, D)\n batch_y_fast = torch.stack([true_y_fast[s + i] for i in range(args.fast_batch_time)], dim=0) # (T, M, D)\n return batch_y0_slow.to(device), batch_y_slow.to(device), batch_y0_fast.to(device), batch_y_fast.to(device), torch.tensor(batch_t).to(device), torch.tensor(batch_t_fast).to(device)\n\ndef makedirs(dirname):\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n\nif args.viz:\n makedirs('png')\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize=(12, 4), facecolor='white')\n ax_traj = fig.add_subplot(131, frameon=False)\n ax_phase = fig.add_subplot(132, frameon=False)\n ax_vecfield = fig.add_subplot(133, frameon=False)\n plt.show(block=False)\n\n\n#f_theta (slow ODE)\nclass ODEFunc_fast(nn.Module):\n\n def __init__(self, dim_in=3, dim_out=1):\n super(ODEFunc_fast, self).__init__()\n\n self.net = nn.Sequential(\n nn.Linear(dim_in, 50),\n nn.Tanh(),\n nn.Linear(50, dim_out),\n )\n self.nfe = 0\n for m in self.net.modules():\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0, std=0.1)\n nn.init.constant_(m.bias, val=0)\n\n def forward(self, t, y, y_other_dim):\n if(y.shape == torch.Size([])):\n dim0 = 1\n else:\n dim0 = len(y)\n y = y.reshape([dim0, 1])\n y_other_dim = y_other_dim.reshape([len(y_other_dim), 1])\n input = torch.concat([y, y_other_dim, torch.full(y.shape, t)], 1)\n self.nfe += 1\n return self.net(torch.sin(input))\n\n#f_theta (slow ODE)\nclass ODEFunc_slow(nn.Module):\n\n def __init__(self, dim_in=3, dim_out=1):\n super(ODEFunc_slow, self).__init__()\n\n self.net = nn.Sequential(\n nn.Linear(dim_in, 50),\n nn.Tanh(),\n nn.Linear(50, dim_out),\n )\n\n for m in self.net.modules():\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0, std=0.1)\n nn.init.constant_(m.bias, val=0)\n self.nfe = 0\n def forward(self, t, y, y_other_dim):\n y = y.reshape([len(y), 1])\n y_other_dim = y_other_dim.reshape([len(y_other_dim), 1])\n input = torch.concat([y, y_other_dim, torch.full(y.shape, t)], 1)\n self.nfe += 1\n return self.net(torch.sin(input))\n \n\nclass RunningAverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self, momentum=0.99):\n self.momentum = momentum\n self.reset()\n\n def reset(self):\n self.val = None\n self.avg = 0\n\n def update(self, val):\n if self.val is None:\n self.avg = val\n else:\n self.avg = self.avg * self.momentum + val * (1 - self.momentum)\n self.val = val\n\n\nif __name__ == '__main__':\n\n ii = 0\n _dt_fast = 0.01\n func = ODEFunc_slow().to(device)\n func_fast = ODEFunc_fast().to(device)\n \n optimizer = optim.Adam(func.parameters(), lr=1e-1)\n optimizer_fast = optim.Adam(func_fast.parameters(), lr=1e-2)\n \n \n end = time.time()\n\n time_meter = RunningAverageMeter(0.97)\n \n #loss_meter = RunningAverageMeter(0.97)\n #loss_meter_fast = RunningAverageMeter(0.97)\n losses_fast = []\n losses_slow = []\n times = []\n slow_intg_time = []\n fast_intg_time = []\n nfes = []\n nfes_fast = []\n for itr in range(1, args.niters + 1):\n print(\"----\", itr)\n func.nfe = 0\n func_fast.nfe = 0\n start = time.time()\n optimizer.zero_grad()\n optimizer_fast.zero_grad()\n batch_y0_slow, batch_y_slow, batch_y0_fast, batch_y_fast, batch_t, batch_t_fast = get_batch(slow, fast, t_slow, t_fast)\n tracemalloc.start()\n \n pred_y, pred_y_fast, timing, fast_timing = odeint(func, batch_y0_slow, batch_t, batch_t_fast, func_fast=func_fast, y0_fast=batch_y0_fast, dt_fast=_dt_fast)\n current, peak = tracemalloc.get_traced_memory()\n print(f\"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB\")\n tracemalloc.stop()\n slow_intg_time.append(timing)\n fast_intg_time.append(fast_timing)\n loss = torch.nn.functional.binary_cross_entropy_with_logits(pred_y, batch_y_slow)\n loss_fast = torch.nn.functional.binary_cross_entropy_with_logits(pred_y_fast, batch_y_fast)\n \n loss.backward(retain_graph=True)\n loss_fast.backward(retain_graph=True)\n \n optimizer.step()\n optimizer_fast.step()\n\n #loss_meter.update(loss.item())\n #loss_meter_fast.update(loss_fast.item())\n print(\"loss (slow): \", float(loss), \"loss (fast): \", float(loss_fast))\n if(float(loss_fast) >= 2):\n print(\"outlier\")\n if(len(losses_fast) == 0):\n losses_fast.append(0)\n else:\n losses_fast.append(losses_fast[len(losses_fast) - 1])\n else:\n losses_fast.append(float(loss_fast))\n losses_slow.append(float(loss))\n print(\"NFE: \", func.nfe, func_fast.nfe)\n nfes.append(func.nfe)\n nfes_fast.append(func_fast.nfe)\n\n \n if itr % args.test_freq == 0:\n print(\"----------------------------------------\")\n with torch.no_grad():\n if(len(true_y0_fast) == 1):\n true_y0_fast_lst = args.fast_step * [true_y0_fast]\n true_y0_fast = true_y0_fast_lst\n pred_y, pred_y_fast, timing, fast_timing = odeint(func, torch.tensor([true_y0_slow]), torch.tensor(t_slow), torch.tensor(t_fast), func_fast=func_fast, y0_fast=torch.tensor(true_y0_fast).T, dt_fast=_dt_fast)\n plt.figure()\n plt.plot(pred_y.reshape(len(pred_y), 1), label = \"predicted\")\n plt.plot(slow, label = \"true value\")\n plt.legend(\"upper right\")\n plt.title(\"prediction\" + str(itr))\n plt.savefig(\"prediction\" + str(itr))\n loss = torch.nn.functional.binary_cross_entropy_with_logits(pred_y.reshape(len(pred_y)), slow)\n loss_fast = torch.nn.functional.binary_cross_entropy_with_logits(pred_y_fast.reshape(fast.shape), fast)\n print('[slow] Iter {:04d} | Total Loss {:.6f}'.format(itr, loss.item()))\n print('[fast] Iter {:04d} | Total Loss {:.6f}'.format(itr, loss_fast.item()))\n ii += 1\n \n times.append(time.time() - end)\n end = time.time()\n \n\n \n plot_data(torch.tensor(losses_fast), torch.tensor(losses_slow), t_slow, t_fast, xlabel=\"interation\", ylabel=\"loss\", title=\"loss\")\n #plot_data(torch.tensor(nfes_fast), torch.tensor(nfes), xlabel=\"iteration\", ylabel=\"nfe\")\n\n print(\"timing avg: \", sum(times)/len(times))\n print(\"slow intg abg time: \", sum(slow_intg_time)/len(slow_intg_time))\n print(\"fast intg abg time: \", sum(fast_intg_time)/len(fast_intg_time))\n print(\"NFE for fast ode: \", func.nfe)\n print(\"NFE for slow ode: \", func_fast.nfe)\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"torch.sin",
"torch.zeros",
"matplotlib.pyplot.plot",
"torch.no_grad",
"torch.cuda.is_available",
"torch.Size",
"torch.tensor",
"matplotlib.pyplot.figure",
"torch.linspace",
"matplotlib.pyplot.title",
"torch.full",
"torch.nn.init.constant_",
"torch.nn.functional.binary_cross_entropy_with_logits",
"matplotlib.pyplot.savefig",
"torch.nn.Linear",
"torch.nn.init.normal_",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"torch.nn.Tanh",
"matplotlib.pyplot.xlabel"
]
] |
DonovanZhu/minimalRL
|
[
"333d22e226a168e7af327913cd07f6cc4637acb0"
] |
[
"a2c.py"
] |
[
"import gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import Categorical\nimport torch.multiprocessing as mp\nimport time\nimport numpy as np\n\n# Hyperparameters\nn_train_processes = 3\nlearning_rate = 0.0002\nupdate_interval = 5\ngamma = 0.98\nmax_train_steps = 60000\nPRINT_INTERVAL = update_interval * 100\n\nclass ActorCritic(nn.Module):\n def __init__(self):\n super(ActorCritic, self).__init__()\n self.fc1 = nn.Linear(4, 256)\n self.fc_pi = nn.Linear(256, 2)\n self.fc_v = nn.Linear(256, 1)\n\n def pi(self, x, softmax_dim=1):\n x = F.relu(self.fc1(x))\n x = self.fc_pi(x)\n prob = F.softmax(x, dim=softmax_dim)\n return prob\n\n def v(self, x):\n x = F.relu(self.fc1(x))\n v = self.fc_v(x)\n return v\n\ndef worker(worker_id, master_end, worker_end):\n master_end.close() # Forbid worker to use the master end for messaging\n env = gym.make('CartPole-v1')\n env.seed(worker_id)\n\n while True:\n cmd, data = worker_end.recv()\n if cmd == 'step':\n ob, reward, done, info = env.step(data)\n if done:\n ob = env.reset()\n worker_end.send((ob, reward, done, info))\n elif cmd == 'reset':\n ob = env.reset()\n worker_end.send(ob)\n elif cmd == 'reset_task':\n ob = env.reset_task()\n worker_end.send(ob)\n elif cmd == 'close':\n worker_end.close()\n break\n elif cmd == 'get_spaces':\n worker_end.send((env.observation_space, env.action_space))\n else:\n raise NotImplementedError\n\nclass ParallelEnv:\n def __init__(self, n_train_processes):\n self.nenvs = n_train_processes\n self.waiting = False\n self.closed = False\n self.workers = list()\n\n master_ends, worker_ends = zip(*[mp.Pipe() for _ in range(self.nenvs)])\n self.master_ends, self.worker_ends = master_ends, worker_ends\n\n for worker_id, (master_end, worker_end) in enumerate(zip(master_ends, worker_ends)):\n p = mp.Process(target=worker,\n args=(worker_id, master_end, worker_end))\n p.daemon = True\n p.start()\n self.workers.append(p)\n\n # Forbid master to use the worker end for messaging\n for worker_end in worker_ends:\n worker_end.close()\n\n def step_async(self, actions):\n for master_end, action in zip(self.master_ends, actions):\n master_end.send(('step', action))\n self.waiting = True\n\n def step_wait(self):\n results = [master_end.recv() for master_end in self.master_ends]\n self.waiting = False\n obs, rews, dones, infos = zip(*results)\n return np.stack(obs), np.stack(rews), np.stack(dones), infos\n\n def reset(self):\n for master_end in self.master_ends:\n master_end.send(('reset', None))\n return np.stack([master_end.recv() for master_end in self.master_ends])\n\n def step(self, actions):\n self.step_async(actions)\n return self.step_wait()\n\n def close(self): # For clean up resources\n if self.closed:\n return\n if self.waiting:\n [master_end.recv() for master_end in self.master_ends]\n for master_end in self.master_ends:\n master_end.send(('close', None))\n for worker in self.workers:\n worker.join()\n self.closed = True\n\ndef test(step_idx, model):\n env = gym.make('CartPole-v1')\n score = 0.0\n done = False\n num_test = 10\n\n for _ in range(num_test):\n s = env.reset()\n while not done:\n prob = model.pi(torch.from_numpy(s).float(), softmax_dim=0)\n a = Categorical(prob).sample().numpy()\n s_prime, r, done, info = env.step(a)\n s = s_prime\n score += r\n done = False\n print(f\"Step # :{step_idx}, avg score : {score/num_test:.1f}\")\n\n env.close()\n\ndef compute_target(v_final, r_lst, mask_lst):\n G = v_final.reshape(-1)\n td_target = list()\n\n for r, mask in zip(r_lst[::-1], mask_lst[::-1]):\n G = r + gamma * G * mask\n td_target.append(G)\n\n return torch.tensor(td_target[::-1]).float()\n\nif __name__ == '__main__':\n envs = ParallelEnv(n_train_processes)\n\n model = ActorCritic()\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\n step_idx = 0\n s = envs.reset()\n while step_idx < max_train_steps:\n s_lst, a_lst, r_lst, mask_lst = list(), list(), list(), list()\n for _ in range(update_interval):\n prob = model.pi(torch.from_numpy(s).float())\n a = Categorical(prob).sample().numpy()\n s_prime, r, done, info = envs.step(a)\n\n s_lst.append(s)\n a_lst.append(a)\n r_lst.append(r/100.0)\n mask_lst.append(1 - done)\n\n s = s_prime\n step_idx += 1\n\n s_final = torch.from_numpy(s_prime).float()\n v_final = model.v(s_final).detach().clone().numpy()\n td_target = compute_target(v_final, r_lst, mask_lst)\n\n td_target_vec = td_target.reshape(-1)\n s_vec = torch.tensor(s_lst).float().reshape(-1, 4) # 4 == Dimension of state\n a_vec = torch.tensor(a_lst).reshape(-1).unsqueeze(1)\n advantage = td_target_vec - model.v(s_vec).reshape(-1)\n\n pi = model.pi(s_vec, softmax_dim=1)\n pi_a = pi.gather(1, a_vec).reshape(-1)\n loss = -(torch.log(pi_a) * advantage.detach()).mean() +\\\n F.smooth_l1_loss(model.v(s_vec).reshape(-1), td_target_vec)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if step_idx % PRINT_INTERVAL == 0:\n test(step_idx, model)\n\n envs.close()\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.from_numpy",
"numpy.stack",
"torch.tensor",
"torch.nn.Linear",
"torch.distributions.Categorical",
"torch.log",
"torch.multiprocessing.Pipe",
"torch.multiprocessing.Process"
]
] |
MrRubyRed/DLS
|
[
"9dd92e83c8ce1a7ec9b3954b7c4640f2fb8dd1dd"
] |
[
"DeepLS.py"
] |
[
"import reachable_computation as Utils\nimport baselines.common.tf_util as U\nimport numpy as np\nimport tensorflow as tf\nimport pickle\nimport cvxpy\nimport os\n\n#Define a new TF session\nsess = U.single_threaded_session()\nsess.__enter__()\n\n#Experiment Directory\ndirectory = \"/home/vrubies/Documents/Research/baselines/baselines/trpo_mpi/experiments/\"\nenviron = \"LinearSystem-v0\"\n\n#Name of the pickle file\npicklefile_names = os.listdir(path=directory)\npicklefile_names = [directory+name for name in picklefile_names if environ+\"_2018-01-12 15:35\" in name]\npicklefile2 = '/home/vrubies/Research/DLS/saved_net.pkl'\n\n#Load pre-trained policy and get environment\npolicies,env = Utils.load_policy_and_env_from_pickle(sess,environ,picklefile_names)\n\n# PARAMETERS for learning the dynamics\narchitecture = {\"hid_size\":5,\"num_hid_layers\":2,\"activation\":tf.nn.relu}\noptimizer = tf.train.MomentumOptimizer\nloss_func = tf.losses.mean_squared_error\ntotal_grad_steps=3000\ntraj_len=20\nepisodes=40\nbatch_size=10\nl_rate=0.01\nmomentum=0.95\n\n#Learn dynamics model of autonomous system\ndynamics,list_W,list_b = Utils.learn_dynamics_model(sess,env,policies,architecture,optimizer,loss_func,total_grad_steps,\n traj_len,episodes,batch_size,l_rate,False,momentum)\nA = np.array([[1,0],[-1,0],[0,1],[0,-1]])\nb = -np.array([-3.5,3.0,-.5,-.5])\nfor k in range(20):\n initial_set = (A,b)\n A,b = Utils.compute_supporting_planes(list_W,list_b,initial_set,num_planes=20,draw=True)\nlist_W_ = [W/np.linalg.norm(W,axis=1,keepdims=True) for W in list_W]\nlist_b_ = [b/np.linalg.norm(W,axis=1) for W,b in zip(list_W,list_b)]\n#active_list,Lg,Ll = Utils.get_active_inactive(-np.ones((2,1)),0.05,list_W,list_b,list_W_,list_b_)\n#dynamics = Utils.load_dynamics_model(picklefile2,sess,env,policies,architecture,optimizer,loss_func,total_grad_steps,\n# traj_len,episodes,batch_size,l_rate,False,momentum)\n\nUtils.show_tube(dynamics,-np.ones((2,1)),0.05,5,list_W,list_b,list_W_,list_b_)\nscaling = 1.0\n#Get all weights and biases\nWb = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='dyn')\nlist_W = []\nlist_b = []\nfor i in range(len(Wb)):\n if i % 2 == 0:\n list_W.append(sess.run(Wb[i]).T/scaling)\n else:\n list_b.append(sess.run(Wb[i]).T/scaling)\n\n#TODO: Compare regions identified at random vs by following trajectories!\n#stats,_,_ = Utils.collect_traj(env,policy,30,30)\n\n#print(\"Start #1\")\n#C_list,b_list = Utils.random_sampling_regions(list_W,list_b,num_points=10000)\n#print(\"Start #2\")\n#C_list_,b_list_ = Utils.traj_sampling_regions(list_W,list_b,env,policy,episodes=500,traj_len=20)\n\nbounds = [(-3.0,3.0),(-3.0,3.0),(-3.0,3.0),(-3.0,3.0)]\nC = []\nb = []\nfor i in range(len(bounds)):\n v = np.zeros((len(bounds),))\n v[i] = 1.0\n C.append(v/scaling)\n C.append(-v/scaling)\n low,high = bounds[i]\n b.append(low/scaling)\n b.append(-high/scaling)\nC = np.array(C)\nb = np.array(b)\n#import pickle\n#C,b,W_y,B_y = pickle.load(open(\"Traitors.pkl\",\"rb\"))\nRegionTree = Utils.Region(C,b,np.zeros((4,1)),0,3,dataW=list_W,datab=list_b)\n#RegionTree.hyperP_Pre_filter(W_y,B_y)\n#(self,C,b,interior_point,depth,max_depth,parent=None,dataW=None,datab=None):\n#W = np.random.uniform(-3.0,3.0,(10,4))\n#b = np.random.uniform(-3.0,3.0,(10,))\n#tmp = (b <= 0)\n#diag = np.diag(np.array([int(i) for i in tmp])*2 - 1)\n#W = np.matmul(diag,W)\n#b = np.matmul(diag,b)\n#W_,B_ = RegionTree.reorient_hyper_planes(list_W[0],list_b[0],RegionTree.interior_point,False)\n#RegionTree.find_children(W_,B_)\nRegionTree = pickle.load(open(\"saved_Tree.pkl\",\"rb\"))[0] #.find_family()\ntmp_ = dynamics.step(np.array([0.0,0.0,0.0,0.0]))\nfor k in range(10000):\n tmp_ = dynamics.step(tmp_[0][0])\nprint(tmp_)\n#A_eq = dynamics.get_Jacobian(tmp_[0][0])[0][0].T\n#b_eq = dynamics.step(tmp_[0][0])[0].T - np.matmul(A_eq,tmp_[0].T)\n#shift = -np.matmul(np.linalg.inv((A_eq - np.eye(len(A_eq)))/env.env.dt),b_eq/env.env.dt)\nshift = tmp_[0].T\navore = RegionTree.return_regions(tmp_[0].T,3); avore = avore[1]; avore = avore[1]; avore = avore[1];\nRegionTree.shift_regions(shift)\nmax_r = [0]\nRegionTree.find_maxr(max_r)\nconstraints = []\nT = cvxpy.Variable(1,max_r[0]+4)\nRegionTree.find_HEFAB(env,dynamics,shift,constraints,T,max_r[0])\n#obj = cvxpy.Minimize(0)\n#Prob = cvxpy.Problem(obj,constraints)\n#Prob.solve()\n\n#for i in range(100):\n# gf = np.random.randint(0,len(RegionTree.children))\n# dd = np.random.randint(0,len(RegionTree.children[gf].children))\n# ch = np.random.randint(0,len(RegionTree.children[gf].children[dd].children))\n# x = RegionTree.children[gf].children[dd].children[ch].interior_point_shifted\n# x_ = np.concatenate((x,np.ones((1,1))),axis=0)\n# tmp = np.matmul(np.array(RegionTree.children[gf].children[dd].children[ch].u.value),\n# RegionTree.children[gf].children[dd].children[ch].E)\n# dec = np.matmul(tmp,x_)\n\n# print(str(dec))\n# \n#t = np.array(T.value).T\n#x = np.random.uniform(-3,3,size=(4,1))\n#for i in range(100):\n# rid = RegionTree.region_id(x,3).split(\"-\")\n# gf = int(rid[0]); dd = int(rid[1]); ch = int(rid[2]);\n# F = RegionTree.children[gf].children[dd].children[ch].F\n# x_ = np.concatenate((x,np.ones((1,1))),axis=0)\n# val = np.matmul(np.matmul(F.T,t).T,x_)\n# print(val)\n# x = dynamics.step(x.T[0])[0].T\n \n \n#colors = []\n#points = []\n#for i in range(10000):\n#\n# point = np.random.uniform(-2.0,2.0,(4,1))\n# #point[2:] = 0\n# j = 0\n# for C_,b_ in zip(C_list,b_list):\n# chk = ((np.matmul(C_,point) + b_) < 0)\n# if chk.all():\n# points.append(point.T)\n# colors.append(j)\n# break\n# j += 1\n\n \n \n"
] |
[
[
"tensorflow.get_collection",
"numpy.linalg.norm",
"numpy.ones",
"numpy.array",
"numpy.zeros"
]
] |
FlyBrainLab/Neuroballad
|
[
"dc8f3aef60e89183e4d5644a226aaf76addcacd1"
] |
[
"neuroballad/neuroballad.py"
] |
[
"#!/usr/bin/env python\n\"\"\"\nNeuroballad circuit class and components for simplifying Neurokernel/Neurodriver\nworkflow.\n\"\"\"\nfrom __future__ import absolute_import\nimport os\nimport copy\nimport json\nimport h5py\nimport time\nimport random\nimport pickle\nimport inspect\nimport argparse\nimport itertools\nimport subprocess\nimport numpy as np\nimport networkx as nx\nimport matplotlib as mpl\nimport networkx as nx\nfrom networkx.drawing.nx_agraph import graphviz_layout\nfrom shutil import copyfile\n\n\nmpl.use('agg')\n\nclass NeuroballadExecutor(object):\n def __init__(self, config=None):\n if config is None:\n config = {}\n self.path = 'neuroballad_execute.py'\n\ndef get_neuroballad_path():\n return os.path.dirname(\n os.path.abspath(inspect.getsourcefile(NeuroballadExecutor)))\n\ndef NeuroballadModelGenerator(model_name, arg_names):\n def __init__(self, **kwargs):\n BaseNeuroballadModel.__init__(self, model_name)\n self.arg_names = arg_names + ['reverse']\n for key, value in kwargs.items():\n if key in arg_names:\n pass\n else:\n print(\"Warning: {} is not in the default parameters for {}: {}\".format(\n key, model_name, ', '.join(arg_names)))\n setattr(self, key, value)\n\n def nadd(self, G, i):\n name = 'uid' + str(i)\n node_name = self.__class__.__name__\n dict_struct = {'class': node_name}\n for key in self.arg_names:\n try:\n dict_struct[key] = getattr(self, key)\n except Exception as e:\n pass\n # Fill in better error handling here\n # print('Required parameter',key,'not found in the definition.')\n G.add_node(name, **dict_struct)\n return G\n return type(model_name, (BaseNeuroballadModel,),\n {\"__init__\": __init__, \"nadd\": nadd})\n\nclass BaseNeuroballadModel(object):\n def __init__(self, my_type):\n self._type = my_type\n\ndef populate_models():\n import os\n import inspect\n from importlib import import_module\n import neurokernel\n nk_path = inspect.getfile(neurokernel)\n ndcomponents_path = os.path.join(os.path.join(os.path.dirname(nk_path),\n 'LPU'),\n 'NDComponents')\n comp_types = [f.path for f in os.scandir(ndcomponents_path) if \\\n f.is_dir() and 'Models' in os.path.basename(f.path)]\n for i in comp_types:\n models_path_py = '.'.join(i.split('/')[-4:])\n model_paths = [f.path for f in os.scandir(i) if \\\n not f.is_dir() and 'Base' not in os.path.basename(f.path) \\\n and '__init__' not in os.path.basename(f.path) \\\n and '.py' in os.path.basename(f.path)]\n for p in model_paths:\n model_name = os.path.basename(p).split('.')[0]\n from_path = models_path_py + '.' + model_name\n mod = import_module(from_path)\n model_class = getattr(mod, model_name)\n if hasattr(model_class, 'params'):\n params = model_class.params\n else:\n params = []\n if model_name not in globals():\n globals()[model_name] = NeuroballadModelGenerator(model_name, params)\n else:\n print(model_name, 'has been already defined in workspace.')\n"
] |
[
[
"matplotlib.use"
]
] |
593903762/center
|
[
"1093f4519422d417b44d5caa4aea12fa7141ba55"
] |
[
"src/cocoeval.py"
] |
[
"__author__ = 'tsungyi'\n\nimport numpy as np\nimport datetime\nimport time\nfrom collections import defaultdict\nfrom . import mask as maskUtils\nimport copy\n\nclass COCOeval:\n # Interface for evaluating detection on the Microsoft COCO dataset.\n #\n # The usage for CocoEval is as follows:\n # cocoGt=..., cocoDt=... # load dataset and results\n # E = CocoEval(cocoGt,cocoDt); # initialize CocoEval object\n # E.params.recThrs = ...; # set parameters as desired\n # E.evaluate(); # run per image evaluation\n # E.accumulate(); # accumulate per image results\n # E.summarize(); # display summary metrics of results\n # For example usage see evalDemo.m and http://mscoco.org/.\n #\n # The evaluation parameters are as follows (defaults in brackets):\n # imgIds - [all] N img ids to use for evaluation\n # catIds - [all] K cat ids to use for evaluation\n # iouThrs - [.5:.05:.95] T=10 IoU thresholds for evaluation\n # recThrs - [0:.01:1] R=101 recall thresholds for evaluation\n # areaRng - [...] A=4 object area ranges for evaluation\n # maxDets - [1 10 100] M=3 thresholds on max detections per image\n # iouType - ['segm'] set iouType to 'segm', 'bbox' or 'keypoints'\n # iouType replaced the now DEPRECATED useSegm parameter.\n # useCats - [1] if true use category labels for evaluation\n # Note: if useCats=0 category labels are ignored as in proposal scoring.\n # Note: multiple areaRngs [Ax2] and maxDets [Mx1] can be specified.\n #\n # evaluate(): evaluates detections on every image and every category and\n # concats the results into the \"evalImgs\" with fields:\n # dtIds - [1xD] id for each of the D detections (dt)\n # gtIds - [1xG] id for each of the G ground truths (gt)\n # dtMatches - [TxD] matching gt id at each IoU or 0\n # gtMatches - [TxG] matching dt id at each IoU or 0\n # dtScores - [1xD] confidence of each dt\n # gtIgnore - [1xG] ignore flag for each gt\n # dtIgnore - [TxD] ignore flag for each dt at each IoU\n #\n # accumulate(): accumulates the per-image, per-category evaluation\n # results in \"evalImgs\" into the dictionary \"eval\" with fields:\n # params - parameters used for evaluation\n # date - date evaluation was performed\n # counts - [T,R,K,A,M] parameter dimensions (see above)\n # precision - [TxRxKxAxM] precision for every evaluation setting\n # recall - [TxKxAxM] max recall for every evaluation setting\n # Note: precision and recall==-1 for settings with no gt objects.\n #\n # See also coco, mask, pycocoDemo, pycocoEvalDemo\n #\n # Microsoft COCO Toolbox. version 2.0\n # Data, paper, and tutorials available at: http://mscoco.org/\n # Code written by Piotr Dollar and Tsung-Yi Lin, 2015.\n # Licensed under the Simplified BSD License [see coco/license.txt]\n def __init__(self, cocoGt=None, cocoDt=None, iouType='segm'):\n '''\n Initialize CocoEval using coco APIs for gt and dt\n :param cocoGt: coco object with ground truth annotations\n :param cocoDt: coco object with detection results\n :return: None\n '''\n if not iouType:\n print('iouType not specified. use default iouType segm')\n self.cocoGt = cocoGt # ground truth COCO API\n self.cocoDt = cocoDt # detections COCO API\n self.evalImgs = defaultdict(list) # per-image per-category evaluation results [KxAxI] elements\n self.eval = {} # accumulated evaluation results\n self._gts = defaultdict(list) # gt for evaluation\n self._dts = defaultdict(list) # dt for evaluation\n self.params = Params(iouType=iouType) # parameters\n self._paramsEval = {} # parameters for evaluation\n self.stats = [] # result summarization\n self.ious = {} # ious between all gts and dts\n if not cocoGt is None:\n self.params.imgIds = sorted(cocoGt.getImgIds())\n self.params.catIds = sorted(cocoGt.getCatIds())\n\n\n def _prepare(self):\n '''\n Prepare ._gts and ._dts for evaluation based on params\n :return: None\n '''\n def _toMask(anns, coco):\n # modify ann['segmentation'] by reference\n for ann in anns:\n rle = coco.annToRLE(ann)\n ann['segmentation'] = rle\n p = self.params\n if p.useCats:\n gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds))\n dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds))\n else:\n gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))\n dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))\n\n # convert ground truth to mask if iouType == 'segm'\n if p.iouType == 'segm':\n _toMask(gts, self.cocoGt)\n _toMask(dts, self.cocoDt)\n # set ignore flag\n for gt in gts:\n gt['ignore'] = gt['ignore'] if 'ignore' in gt else 0\n gt['ignore'] = 'iscrowd' in gt and gt['iscrowd']\n if p.iouType == 'keypoints':\n gt['ignore'] = (gt['num_keypoints'] == 0) or gt['ignore']\n self._gts = defaultdict(list) # gt for evaluation\n self._dts = defaultdict(list) # dt for evaluation\n for gt in gts:\n self._gts[gt['image_id'], gt['category_id']].append(gt)\n for dt in dts:\n self._dts[dt['image_id'], dt['category_id']].append(dt)\n self.evalImgs = defaultdict(list) # per-image per-category evaluation results\n self.eval = {} # accumulated evaluation results\n\n def evaluate(self):\n '''\n Run per image evaluation on given images and store results (a list of dict) in self.evalImgs\n :return: None\n '''\n tic = time.time()\n print('Running per image evaluation...')\n p = self.params\n # add backward compatibility if useSegm is specified in params\n if not p.useSegm is None:\n p.iouType = 'segm' if p.useSegm == 1 else 'bbox'\n print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType))\n print('Evaluate annotation type *{}*'.format(p.iouType))\n p.imgIds = list(np.unique(p.imgIds))\n if p.useCats:\n p.catIds = list(np.unique(p.catIds))\n p.maxDets = sorted(p.maxDets)\n self.params=p\n\n self._prepare()\n # loop through images, area range, max detection number\n catIds = p.catIds if p.useCats else [-1]\n\n if p.iouType == 'segm' or p.iouType == 'bbox':\n computeIoU = self.computeIoU\n elif p.iouType == 'keypoints':\n computeIoU = self.computeOks\n self.ious = {(imgId, catId): computeIoU(imgId, catId) \\\n for imgId in p.imgIds\n for catId in catIds}\n\n evaluateImg = self.evaluateImg\n maxDet = p.maxDets[-1]\n self.evalImgs = [evaluateImg(imgId, catId, areaRng, maxDet)\n for catId in catIds\n for areaRng in p.areaRng\n for imgId in p.imgIds\n ]\n self._paramsEval = copy.deepcopy(self.params)\n toc = time.time()\n print('DONE (t={:0.2f}s).'.format(toc-tic))\n\n def computeIoU(self, imgId, catId):\n p = self.params\n if p.useCats:\n gt = self._gts[imgId,catId]\n dt = self._dts[imgId,catId]\n else:\n gt = [_ for cId in p.catIds for _ in self._gts[imgId,cId]]\n dt = [_ for cId in p.catIds for _ in self._dts[imgId,cId]]\n if len(gt) == 0 and len(dt) ==0:\n return []\n inds = np.argsort([-d['score'] for d in dt], kind='mergesort')\n dt = [dt[i] for i in inds]\n if len(dt) > p.maxDets[-1]:\n dt=dt[0:p.maxDets[-1]]\n\n if p.iouType == 'segm':\n g = [g['segmentation'] for g in gt]\n d = [d['segmentation'] for d in dt]\n elif p.iouType == 'bbox':\n g = [g['bbox'] for g in gt]\n d = [d['bbox'] for d in dt]\n else:\n raise Exception('unknown iouType for iou computation')\n\n # compute iou between each dt and gt region\n iscrowd = [int(o['iscrowd']) for o in gt]\n ious = maskUtils.iou(d,g,iscrowd)\n return ious\n\n def computeOks(self, imgId, catId):\n p = self.params\n # dimention here should be Nxm\n gts = self._gts[imgId, catId]\n dts = self._dts[imgId, catId]\n inds = np.argsort([-d['score'] for d in dts], kind='mergesort')\n dts = [dts[i] for i in inds]\n if len(dts) > p.maxDets[-1]:\n dts = dts[0:p.maxDets[-1]]\n # if len(gts) == 0 and len(dts) == 0:\n if len(gts) == 0 or len(dts) == 0:\n return []\n ious = np.zeros((len(dts), len(gts)))\n sigmas = p.kpt_oks_sigmas\n vars = (sigmas * 2)**2\n k = len(sigmas)\n # compute oks between each detection and ground truth object\n for j, gt in enumerate(gts):\n # create bounds for ignore regions(double the gt bbox)\n g = np.array(gt['keypoints'])\n xg = g[0::3]; yg = g[1::3]; vg = g[2::3]\n k1 = np.count_nonzero(vg > 0)\n bb = gt['bbox']\n x0 = bb[0] - bb[2]; x1 = bb[0] + bb[2] * 2\n y0 = bb[1] - bb[3]; y1 = bb[1] + bb[3] * 2\n for i, dt in enumerate(dts):\n d = np.array(dt['keypoints'])\n xd = d[0::3]; yd = d[1::3]\n if k1>0:\n # measure the per-keypoint distance if keypoints visible\n dx = xd - xg\n dy = yd - yg\n else:\n # measure minimum distance to keypoints in (x0,y0) & (x1,y1)\n z = np.zeros((k))\n dx = np.max((z, x0-xd),axis=0)+np.max((z, xd-x1),axis=0)\n dy = np.max((z, y0-yd),axis=0)+np.max((z, yd-y1),axis=0)\n e = (dx**2 + dy**2) / vars / (gt['area']+np.spacing(1)) / 2\n if k1 > 0:\n e=e[vg > 0]\n ious[i, j] = np.sum(np.exp(-e)) / e.shape[0]\n return ious\n\n def evaluateImg(self, imgId, catId, aRng, maxDet):\n '''\n perform evaluation for single category and image\n :return: dict (single image results)\n '''\n p = self.params\n if p.useCats:\n gt = self._gts[imgId,catId]\n dt = self._dts[imgId,catId]\n else:\n gt = [_ for cId in p.catIds for _ in self._gts[imgId,cId]]\n dt = [_ for cId in p.catIds for _ in self._dts[imgId,cId]]\n if len(gt) == 0 and len(dt) ==0:\n return None\n\n for g in gt:\n if g['ignore'] or (g['area']<aRng[0] or g['area']>aRng[1]):\n g['_ignore'] = 1\n else:\n g['_ignore'] = 0\n\n # sort dt highest score first, sort gt ignore last\n gtind = np.argsort([g['_ignore'] for g in gt], kind='mergesort') # 使用归并排序\n gt = [gt[i] for i in gtind]\n dtind = np.argsort([-d['score'] for d in dt], kind='mergesort')\n dt = [dt[i] for i in dtind[0:maxDet]]\n iscrowd = [int(o['iscrowd']) for o in gt]\n # load computed ious\n ious = self.ious[imgId, catId][:, gtind] if len(self.ious[imgId, catId]) > 0 else self.ious[imgId, catId]\n\n T = len(p.iouThrs)\n G = len(gt)\n D = len(dt)\n gtm = np.zeros((T,G))\n dtm = np.zeros((T,D))\n gtIg = np.array([g['_ignore'] for g in gt])\n dtIg = np.zeros((T,D))\n if not len(ious)==0:\n for tind, t in enumerate(p.iouThrs):\n for dind, d in enumerate(dt):\n # information about best match so far (m=-1 -> unmatched)\n iou = min([t,1-1e-10])\n m = -1\n for gind, g in enumerate(gt):\n # if this gt already matched, and not a crowd, continue\n if gtm[tind,gind]>0 and not iscrowd[gind]:\n continue\n # if dt matched to reg gt, and on ignore gt, stop\n if m>-1 and gtIg[m]==0 and gtIg[gind]==1:\n break\n # continue to next gt unless better match made\n if ious[dind,gind] < iou:\n continue\n # if match successful and best so far, store appropriately\n iou=ious[dind,gind]\n m=gind\n # if match made store id of match for both dt and gt\n if m ==-1:\n continue\n dtIg[tind,dind] = gtIg[m]\n dtm[tind,dind] = gt[m]['id']\n gtm[tind,m] = d['id']\n # set unmatched detections outside of area range to ignore\n a = np.array([d['area']<aRng[0] or d['area']>aRng[1] for d in dt]).reshape((1, len(dt)))\n dtIg = np.logical_or(dtIg, np.logical_and(dtm==0, np.repeat(a,T,0)))\n # store results for given image and category\n return {\n 'image_id': imgId,\n 'category_id': catId,\n 'aRng': aRng,\n 'maxDet': maxDet,\n 'dtIds': [d['id'] for d in dt],\n 'gtIds': [g['id'] for g in gt],\n 'dtMatches': dtm,\n 'gtMatches': gtm,\n 'dtScores': [d['score'] for d in dt],\n 'gtIgnore': gtIg,\n 'dtIgnore': dtIg,\n }\n\n def accumulate(self, p = None):\n '''\n Accumulate per image evaluation results and store the result in self.eval\n :param p: input params for evaluation\n :return: None\n '''\n print('Accumulating evaluation results...')\n tic = time.time()\n if not self.evalImgs:\n print('Please run evaluate() first')\n # allows input customized parameters\n if p is None:\n p = self.params\n p.catIds = p.catIds if p.useCats == 1 else [-1]\n T = len(p.iouThrs)\n R = len(p.recThrs)\n K = len(p.catIds) if p.useCats else 1\n A = len(p.areaRng)\n M = len(p.maxDets)\n precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories\n recall = -np.ones((T,K,A,M))\n scores = -np.ones((T,R,K,A,M))\n\n # create dictionary for future indexing\n _pe = self._paramsEval\n catIds = _pe.catIds if _pe.useCats else [-1]\n setK = set(catIds)\n setA = set(map(tuple, _pe.areaRng))\n setM = set(_pe.maxDets)\n setI = set(_pe.imgIds)\n # get inds to evaluate\n k_list = [n for n, k in enumerate(p.catIds) if k in setK]\n m_list = [m for n, m in enumerate(p.maxDets) if m in setM]\n a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA]\n i_list = [n for n, i in enumerate(p.imgIds) if i in setI]\n I0 = len(_pe.imgIds)\n A0 = len(_pe.areaRng)\n # retrieve E at each category, area range, and max number of detections\n for k, k0 in enumerate(k_list):\n Nk = k0*A0*I0\n for a, a0 in enumerate(a_list):\n Na = a0*I0\n for m, maxDet in enumerate(m_list):\n E = [self.evalImgs[Nk + Na + i] for i in i_list]\n E = [e for e in E if not e is None]\n if len(E) == 0:\n continue\n dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E])\n\n # different sorting method generates slightly different results.\n # mergesort is used to be consistent as Matlab implementation.\n inds = np.argsort(-dtScores, kind='mergesort')\n dtScoresSorted = dtScores[inds]\n\n dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds]\n dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds]\n gtIg = np.concatenate([e['gtIgnore'] for e in E])\n npig = np.count_nonzero(gtIg==0 )\n if npig == 0:\n continue\n tps = np.logical_and( dtm, np.logical_not(dtIg) )\n fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) )\n\n tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)\n fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)\n for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)):\n tp = np.array(tp)\n fp = np.array(fp)\n nd = len(tp)\n rc = tp / npig\n pr = tp / (fp+tp+np.spacing(1))\n q = np.zeros((R,))\n ss = np.zeros((R,))\n\n if nd:\n recall[t,k,a,m] = rc[-1]\n else:\n recall[t,k,a,m] = 0\n\n # numpy is slow without cython optimization for accessing elements\n # use python array gets significant speed improvement\n pr = pr.tolist(); q = q.tolist()\n\n for i in range(nd-1, 0, -1):\n if pr[i] > pr[i-1]:\n pr[i-1] = pr[i]\n\n inds = np.searchsorted(rc, p.recThrs, side='left')\n try:\n for ri, pi in enumerate(inds):\n q[ri] = pr[pi]\n ss[ri] = dtScoresSorted[pi]\n except:\n pass\n precision[t,:,k,a,m] = np.array(q)\n scores[t,:,k,a,m] = np.array(ss)\n self.eval = {\n 'params': p,\n 'counts': [T, R, K, A, M],\n 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n 'precision': precision,\n 'recall': recall,\n 'scores': scores,\n }\n toc = time.time()\n print('DONE (t={:0.2f}s).'.format( toc-tic))\n\n def summarize(self):\n '''\n Compute and display summary metrics for evaluation results.\n Note this functin can *only* be applied on the default parameter setting\n '''\n def _summarize( ap=1, iouThr=None, areaRng='all', maxDets=100 ):\n p = self.params\n iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}'\n titleStr = 'Average Precision' if ap == 1 else 'Average Recall'\n typeStr = '(AP)' if ap==1 else '(AR)'\n iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \\\n if iouThr is None else '{:0.2f}'.format(iouThr)\n\n aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]\n mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]\n if ap == 1:\n # dimension of precision: [TxRxKxAxM]\n s = self.eval['precision']\n # IoU\n if iouThr is not None:\n t = np.where(iouThr == p.iouThrs)[0]\n s = s[t]\n s = s[:,:,:,aind,mind]\n else:\n # dimension of recall: [TxKxAxM]\n s = self.eval['recall']\n if iouThr is not None:\n t = np.where(iouThr == p.iouThrs)[0]\n s = s[t]\n s = s[:,:,aind,mind]\n if len(s[s>-1])==0:\n mean_s = -1\n else:\n mean_s = np.mean(s[s>-1])\n print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))\n return mean_s\n def _summarizeDets():\n stats = np.zeros((12,))\n stats[0] = _summarize(1)\n stats[1] = _summarize(1, iouThr=.5, maxDets=self.params.maxDets[2])\n stats[2] = _summarize(1, iouThr=.75, maxDets=self.params.maxDets[2])\n stats[3] = _summarize(1, areaRng='small', maxDets=self.params.maxDets[2])\n stats[4] = _summarize(1, areaRng='medium', maxDets=self.params.maxDets[2])\n stats[5] = _summarize(1, areaRng='large', maxDets=self.params.maxDets[2])\n stats[6] = _summarize(0, maxDets=self.params.maxDets[0])\n stats[7] = _summarize(0, maxDets=self.params.maxDets[1])\n stats[8] = _summarize(0, maxDets=self.params.maxDets[2])\n stats[9] = _summarize(0, areaRng='small', maxDets=self.params.maxDets[2])\n stats[10] = _summarize(0, areaRng='medium', maxDets=self.params.maxDets[2])\n stats[11] = _summarize(0, areaRng='large', maxDets=self.params.maxDets[2])\n return stats\n def _summarizeKps():\n stats = np.zeros((10,))\n stats[0] = _summarize(1, maxDets=20)\n stats[1] = _summarize(1, maxDets=20, iouThr=.5)\n stats[2] = _summarize(1, maxDets=20, iouThr=.75)\n stats[3] = _summarize(1, maxDets=20, areaRng='medium')\n stats[4] = _summarize(1, maxDets=20, areaRng='large')\n stats[5] = _summarize(0, maxDets=20)\n stats[6] = _summarize(0, maxDets=20, iouThr=.5)\n stats[7] = _summarize(0, maxDets=20, iouThr=.75)\n stats[8] = _summarize(0, maxDets=20, areaRng='medium')\n stats[9] = _summarize(0, maxDets=20, areaRng='large')\n return stats\n if not self.eval:\n raise Exception('Please run accumulate() first')\n iouType = self.params.iouType\n if iouType == 'segm' or iouType == 'bbox':\n summarize = _summarizeDets\n elif iouType == 'keypoints':\n summarize = _summarizeKps\n self.stats = summarize()\n\n def __str__(self):\n self.summarize()\n\nclass Params:\n '''\n Params for coco evaluation api\n '''\n def setDetParams(self):\n self.imgIds = []\n self.catIds = []\n # np.arange causes trouble. the data point on arange is slightly larger than the true value\n self.iouThrs = np.linspace(.5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)\n self.recThrs = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1, endpoint=True)\n self.maxDets = [1, 10, 100]\n self.areaRng = [[0 ** 2, 1e5 ** 2], [0 ** 2, 32 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]\n self.areaRngLbl = ['all', 'small', 'medium', 'large']\n self.useCats = 1\n\n def setKpParams(self):\n self.imgIds = []\n self.catIds = []\n # np.arange causes trouble. the data point on arange is slightly larger than the true value\n self.iouThrs = np.linspace(.5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)\n self.recThrs = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1, endpoint=True)\n self.maxDets = [20]\n self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]\n self.areaRngLbl = ['all', 'medium', 'large']\n self.useCats = 1\n self.kpt_oks_sigmas = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62,.62, 1.07, 1.07, .87, .87, .89, .89])/10.0\n\n def __init__(self, iouType='segm'):\n if iouType == 'segm' or iouType == 'bbox':\n self.setDetParams()\n elif iouType == 'keypoints':\n self.setKpParams()\n else:\n raise Exception('iouType not supported')\n self.iouType = iouType\n # useSegm is deprecated\n self.useSegm = None\n"
] |
[
[
"numpy.logical_not",
"numpy.spacing",
"numpy.unique",
"numpy.cumsum",
"numpy.ones",
"numpy.concatenate",
"numpy.round",
"numpy.max",
"numpy.mean",
"numpy.count_nonzero",
"numpy.searchsorted",
"numpy.exp",
"numpy.argsort",
"numpy.repeat",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] |
IPUdk/iputemplates
|
[
"f182305ffbdd95a75cc55ba8a6a570aca6f78c54"
] |
[
"tex/latex/ipu/ipucolours.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division, absolute_import\nimport matplotlib as mpl\nimport matplotlib.cm as mplcm\nfrom cycler import cycler \nimport numpy as np\nfrom matplotlib.colors import LinearSegmentedColormap\n#import brewer2mpl\nfrom itertools import cycle\nimport platform\n\ndef _get_color_map():\n \"\"\"A function to create and register the custom colour map objects \n in a way matplotlib can digest. The cubehelix (including Kindl et al., \n the Brewer3 colour maps (YlOrRd, PuBuGn, YlGnBu) all provide proper \n desaturation in grey-scale.\n \n \"\"\"\n specs = {}\n # We start out with the custom cubehelix maps\n #========= =======================================================\n #Keyword Description\n #========= =======================================================\n #gamma gamma factor to emphasise either low intensity values\n # (gamma < 1), or high intensity values (gamma > 1);\n # defaults to 1.0.\n #s the start color; defaults to 0.5 (i.e. purple).\n #r the number of r,g,b rotations in color that are made\n # from the start to the end of the color scheme; defaults\n # to -1.5 (i.e. -> B -> G -> R -> B).\n #h the hue parameter which controls how saturated the\n # colors are. If this parameter is zero then the color\n # scheme is purely a greyscale; defaults to 1.0.\n #========= =======================================================\n # 0 = blue, 1 = red, 2 = green\n specs['cubehelix_alt'] = mpl._cm.cubehelix(h=1.5) # standard colours but more intensity\n specs['cubehelix_blue'] = mpl._cm.cubehelix(s=0.3,r=-0.5,h=1.5) # blue colours and higher intensity\n specs['cubehelix_red'] = mpl._cm.cubehelix(s=1.3,r=-0.5,h=1.5) # blue colours and higher intensity\n specs['cubehelix_green'] = mpl._cm.cubehelix(s=2.3,r=-0.5,h=1.5) # blue colours and higher intensity\n specs['cubehelix_kindl'] = mpl._cm.cubehelix(gamma=1.4,s=0.4,r=-0.8,h=2.0) # blue colours and higher intensity\n \n for name in specs:\n mplcm.register_cmap(name=name, data=specs[name])\n mplcm.register_cmap(name=name+\"_r\", data=mplcm._reverse_cmap_spec(specs[name]))\n # #self._color_maps[name] = self.get_color_map(name)\n # #self._color_maps[name+\"_r\"] = self.get_color_map(name+\"_r\")\n return mplcm.get_cmap('cubehelix_kindl')\n\n\ndef _get_color_list(length=None):\n if length is None: length = 4\n cmap = _get_color_map()\n clist = [cmap(i) for i in np.linspace(0.25, 0.75, length)]\n return clist\n\nif __name__ == \"__main__\":\n clist = _get_color_list()\n print(clist)\n #for i in dic:\n # line_fig,map_fig,sur_fig = dic[i]()._show_info()\n # line_fig.savefig(i+\"_lines.pdf\")\n # map_fig.savefig(i+\"_maps.pdf\")\n # sur_fig.savefig(i+\"_surf.pdf\")\n"
] |
[
[
"numpy.linspace",
"matplotlib.cm._reverse_cmap_spec",
"matplotlib.cm.get_cmap",
"matplotlib._cm.cubehelix",
"matplotlib.cm.register_cmap"
]
] |
mmjazzar/-python-snippets
|
[
"fa53a6bc5c2f60b8a19677ae8dc848fdb6197589"
] |
[
"open cv_example 1.py"
] |
[
"import cv2\r\nimport numpy as np\r\n\r\nimg = cv2.imread('C:\\\\Users\\\\mmjaz\\\\Desktop\\\\OneDrive_3_7-3-2017\\\\Button\\\\images_190.jpeg')\r\n\r\nimg = cv2.imread('C:\\\\Users\\\\mmjaz\\\\Desktop\\\\OneDrive_3_7-3-2017\\\\OneDrive_4_7-3-2017\\\\pop up.jpg')\r\n\r\ngray= cv2.imread('C:\\\\Users\\\\mmjaz\\\\Desktop\\\\OneDrive_3_7-3-2017\\\\OneDrive_4_7-3-2017\\\\pop up.jpg',0)\r\n\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\ngray = np.float32(gray)\r\ndst = cv2.cornerHarris(gray,2,3,0.04)\r\n\r\n#result is dilated for marking the corners, not important\r\ndst = cv2.dilate(dst,None)\r\n\r\n# Threshold for an optimal value, it may vary depending on the image.\r\nimg[dst>0.01*dst.max()]=[0,0,255]\r\n\r\ncv2.imshow('dst',img)\r\nif cv2.waitKey(0) & 0xff == 27:\r\n cv2.destroyAllWindows()\r\n\r\n\r\n\r\n"
] |
[
[
"numpy.float32"
]
] |
ltthinhtb/image_bit
|
[
"4f4118355b44d5b2d6e4537334065ebdc8312ad1"
] |
[
"main.py"
] |
[
"import argparse\nimport logging\nimport random\nimport numpy as np\nimport cv2\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef convert_image_to_bit_planes(img, bit_size):\n \"\"\"\n Convert a color image to separate rgb bit planes\n\n Parameters:\n img: OpenCV image\n bit_size: \n\n Returns\n b_bits: Blue channel bit planes\n g_bits: Green channel bit planes\n r_bits: Red channel bit planes\n \n \"\"\"\n\n # split channels in a color (3-channel) image\n \n b, g, r = cv2.split(img)\n \n # convert image integers to bits assuming 8 bit image for each color channel\n b_bits = np.unpackbits(b).reshape(bit_size)\n g_bits = np.unpackbits(g).reshape(bit_size)\n r_bits = np.unpackbits(r).reshape(bit_size)\n\n return b_bits, g_bits, r_bits\n\n\ndef convert_bit_planes_to_image(b_bits, g_bits, r_bits, img_size):\n \"\"\"\n Convert RGB bit planes back into a color image\n\n Parameters\n b_bits: Blue channel bit planes\n g_bits: Green channel bit planes\n r_bits: Red channel bit planes\n\n Returns\n img: OpenCV image\n\n \"\"\"\n\n # convert back to 8-bit integer in the original shape\n b_aug = np.packbits(b_bits).reshape(img_size)\n g_aug = np.packbits(g_bits).reshape(img_size)\n r_aug = np.packbits(r_bits).reshape(img_size)\n\n # combine the channels back into a color image\n return cv2.merge((b_aug, g_aug, r_aug))\n\n\ndef bit_plane_slice(b_bits, g_bits, r_bits, bit_plane_list):\n \"\"\"\n Zeroize the bit planes in the list for all the rgb bit plane images\n\n Parameters\n b_bits: Blue channel bit planes\n g_bits: Green channel bit planes\n r_bits: Red channel bit planes\n bit_plane_list: list of channels to zeroize\n\n \"\"\"\n\n if bit_plane_list is not None:\n for bit_plane in bit_plane_list:\n logging.debug('Zeroizing {} bit_plane'.format(int(bit_plane)))\n # zeroize the bit plane in each RGB channel\n b_bits[:,:,int(bit_plane)] = 0\n g_bits[:,:,int(bit_plane)] = 0\n r_bits[:,:,int(bit_plane)] = 0\n \n\ndef process_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input', help=\"Input image path\")\n parser.add_argument('-o', '--output', help=\"Output image path\")\n parser.add_argument('-p', '--plane', nargs='+', help=\"Space separated list of bit planes to zeroize\")\n return parser.parse_args()\n\n\ndef main():\n\n args = process_arguments()\n logging.debug(args)\n\n logging.debug(\"Reading image from {}\".format(args.input))\n img = cv2.imread(args.input)\n\n if img is not None and len(img.shape) == 3 and img.shape[2] == 3:\n\n height, width, channels = img.shape\n img_size = (height, width)\n bit_size = img_size + (8,)\n logging.debug(\"Image size: {}\".format(img_size + (channels,)))\n logging.debug(\"Bit size: {}\".format(bit_size))\n\n b_bits, g_bits, r_bits = convert_image_to_bit_planes(img, bit_size)\n bit_plane_slice(b_bits, g_bits, r_bits, args.plane)\n img = convert_bit_planes_to_image(b_bits, g_bits, r_bits, img_size)\n\n logging.debug(\"Saving image to {}\".format(args.output))\n cv2.imwrite(args.output, img)\n else:\n logging.error(\"Image was either not read in correctly or is not color.\")\n\nif __name__ == '__main__':\n main()\n\n\n"
] |
[
[
"numpy.packbits",
"numpy.unpackbits"
]
] |
rahul263-stack/TIGRE
|
[
"073b9c6d42f71f42451c4cd2db68ba8d67363e4c"
] |
[
"Python/tigre/algorithms/krylov_subspace_algorithms.py"
] |
[
"from __future__ import division\r\n\r\nimport time\r\n\r\nimport numpy as np\r\nimport tigre\r\nfrom tigre.algorithms.iterative_recon_alg import IterativeReconAlg\r\nfrom tigre.algorithms.iterative_recon_alg import decorator\r\nfrom tigre.utilities.Atb import Atb\r\nfrom tigre.utilities.Ax import Ax\r\n\r\n\r\nif hasattr(time, \"perf_counter\"):\r\n default_timer = time.perf_counter\r\nelse:\r\n default_timer = time.clock\r\n\r\n\r\nclass CGLS(IterativeReconAlg): # noqa: D101\r\n __doc__ = (\r\n \" CGLS_CBCT solves the CBCT problem using the conjugate gradient least\\n\"\r\n \" squares\\n\"\r\n \" \\n\"\r\n \" CGLS_CBCT(PROJ,GEO,ANGLES,NITER) solves the reconstruction problem\\n\"\r\n \" using the projection data PROJ taken over ALPHA angles, corresponding\\n\"\r\n \" to the geometry descrived in GEO, using NITER iterations.\"\r\n ) + IterativeReconAlg.__doc__\r\n\r\n def __init__(self, proj, geo, angles, niter, **kwargs):\r\n # Don't precompute V and W.\r\n kwargs.update(dict(W=None, V=None))\r\n kwargs.update(dict(blocksize=angles.shape[0]))\r\n self.log_parameters = False\r\n self.re_init_at_iteration = 0\r\n IterativeReconAlg.__init__(self, proj, geo, angles, niter, **kwargs)\r\n\r\n if self.log_parameters:\r\n parameter_history = {}\r\n iterations = self.niter\r\n parameter_history[\"alpha\"] = np.zeros([iterations], dtype=np.float32)\r\n parameter_history[\"beta\"] = np.zeros([iterations], dtype=np.float32)\r\n parameter_history[\"gamma\"] = np.zeros([iterations], dtype=np.float32)\r\n parameter_history[\"q_norm\"] = np.zeros([iterations], dtype=np.float32)\r\n parameter_history[\"s_norm\"] = np.zeros([iterations], dtype=np.float32)\r\n self.parameter_history = parameter_history\r\n\r\n self.__r__ = self.proj - Ax(self.res, self.geo, self.angles, \"Siddon\", gpuids=self.gpuids)\r\n self.__p__ = Atb(self.__r__, self.geo, self.angles, gpuids=self.gpuids)\r\n p_norm = np.linalg.norm(self.__p__.ravel(), 2)\r\n self.__gamma__ = p_norm * p_norm\r\n\r\n def reinitialise_cgls(self):\r\n self.__r__ = self.proj - Ax(self.res, self.geo, self.angles, \"Siddon\", gpuids=self.gpuids)\r\n self.__p__ = Atb(self.__r__, self.geo, self.angles, gpuids=self.gpuids)\r\n p_norm = np.linalg.norm(self.__p__.ravel(), 2)\r\n self.__gamma__ = p_norm * p_norm\r\n\r\n # Overide\r\n def run_main_iter(self):\r\n self.l2l = np.zeros((1, self.niter), dtype=np.float32)\r\n avgtime = []\r\n for i in range(self.niter):\r\n if i == 0:\r\n if self.verbose:\r\n print(\"CGLS Algorithm in progress.\")\r\n toc = default_timer()\r\n if i == 1:\r\n tic = default_timer()\r\n if self.verbose:\r\n print(\r\n \"Esitmated time until completetion (s): \"\r\n + str((self.niter - 1) * (tic - toc))\r\n )\r\n avgtic = default_timer()\r\n q = tigre.Ax(self.__p__, self.geo, self.angles, \"Siddon\", gpuids=self.gpuids)\r\n q_norm = np.linalg.norm(q)\r\n alpha = self.__gamma__ / (q_norm * q_norm)\r\n self.res += alpha * self.__p__\r\n avgtoc = default_timer()\r\n avgtime.append(abs(avgtic - avgtoc))\r\n for item in self.__dict__:\r\n if isinstance(getattr(self, item), np.ndarray):\r\n if np.isnan(getattr(self, item)).any():\r\n raise ValueError(\"nan found for \" + item + \" at iteraton \" + str(i))\r\n\r\n aux = self.proj - tigre.Ax(\r\n self.res, self.geo, self.angles, \"Siddon\", gpuids=self.gpuids\r\n )\r\n self.l2l[0, i] = np.linalg.norm(aux)\r\n if i > 0 and self.l2l[0, i] > self.l2l[0, i - 1]:\r\n if self.verbose:\r\n print(\"re-initilization of CGLS called at iteration:\" + str(i))\r\n if self.re_init_at_iteration + 1 == i:\r\n if self.verbose:\r\n print(\"Algorithm exited with two consecutive reinitializations.\")\r\n return self.res\r\n self.res -= alpha * self.__p__\r\n self.reinitialise_cgls()\r\n self.re_init_at_iteration = i\r\n\r\n self.__r__ -= alpha * q\r\n s = tigre.Atb(self.__r__, self.geo, self.angles, gpuids=self.gpuids)\r\n s_norm = np.linalg.norm(s)\r\n\r\n gamma1 = s_norm * s_norm\r\n beta = gamma1 / self.__gamma__\r\n if self.log_parameters:\r\n self.parameter_history[\"alpha\"][i] = alpha\r\n self.parameter_history[\"beta\"][i] = beta\r\n self.parameter_history[\"gamma\"][i] = self.__gamma__\r\n self.parameter_history[\"q_norm\"][i] = q_norm\r\n self.parameter_history[\"s_norm\"][i] = s_norm\r\n\r\n self.__gamma__ = gamma1\r\n self.__p__ = s + beta * self.__p__\r\n if self.verbose:\r\n print(\r\n \"Average time taken for each iteration for CGLS:\"\r\n + str(sum(avgtime) / len(avgtime))\r\n + \"(s)\"\r\n )\r\n\r\n\r\ncgls = decorator(CGLS, name=\"cgls\")\r\n"
] |
[
[
"numpy.zeros",
"numpy.linalg.norm"
]
] |
vaesl/LFIP
|
[
"eb9d934616c508c9a9032f170baa1d97fa792822"
] |
[
"models/LFIP_VOC_300.py"
] |
[
"import torch\nimport torch.nn as nn\n\n\nclass ConvBlock(nn.Module):\n\n def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):\n super(ConvBlock, self).__init__()\n self.out_channels = out_planes\n self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)\n self.bn = nn.BatchNorm2d(out_planes, eps=1e-5, momentum=0.01, affine=True) if bn else None\n self.relu = nn.ReLU(inplace=False) if relu else None\n\n def forward(self, x):\n x = self.conv(x)\n if self.bn is not None:\n x = self.bn(x)\n if self.relu is not None:\n x = self.relu(x)\n return x\n\n\nclass ExtraBlock(nn.Module):\n\n def __init__(self, in_planes, out_planes, stride=1):\n super(ExtraBlock, self).__init__()\n self.out_channels = out_planes\n inter_planes = in_planes // 4\n self.single_branch = nn.Sequential(\n ConvBlock(in_planes, inter_planes, kernel_size=1),\n ConvBlock(inter_planes, out_planes, kernel_size=(3, 3), stride=stride, padding=1, relu=False)\n )\n\n def forward(self, x):\n out = self.single_branch(x)\n return out\n\n\nclass LFIP(nn.Module):\n\n def __init__(self, in_planes):\n super(LFIP, self).__init__()\n self.iter_ds = Iter_Downsample()\n self.lcb1 = nn.Sequential(\n ConvBlock(in_planes, 128, kernel_size=(3, 3), padding=1), ConvBlock(128, 128, kernel_size=1, stride=1),\n ConvBlock(128, 128, kernel_size=(3, 3), padding=1), ConvBlock(128, 512, kernel_size=1, relu=False))\n self.lcb2 = nn.Sequential(\n ConvBlock(in_planes, 256, kernel_size=(3, 3), padding=1), ConvBlock(256, 256, kernel_size=1),\n ConvBlock(256, 256, kernel_size=(3, 3), padding=1), ConvBlock(256, 256, kernel_size=1, stride=1),\n ConvBlock(256, 256, kernel_size=(3, 3), padding=1), ConvBlock(256, 1024, kernel_size=1, relu=False))\n self.lcb3 = nn.Sequential(\n ConvBlock(in_planes, 128, kernel_size=(3, 3), padding=1), ConvBlock(128, 128, kernel_size=1),\n ConvBlock(128, 128, kernel_size=(3, 3), padding=1), ConvBlock(128, 128, kernel_size=1),\n ConvBlock(128, 128, kernel_size=(3, 3), padding=1), ConvBlock(128, 512, kernel_size=1, relu=False))\n self.lcb4 = nn.Sequential(\n ConvBlock(in_planes, 64, kernel_size=(3, 3), padding=1), ConvBlock(64, 64, kernel_size=1),\n ConvBlock(64, 64, kernel_size=(3, 3), padding=1), ConvBlock(64, 64, kernel_size=1),\n ConvBlock(64, 64, kernel_size=(3, 3), padding=1), ConvBlock(64, 256, kernel_size=1, relu=False))\n\n def forward(self, x):\n img1, img2, img3, img4 = self.iter_ds(x)\n s1 = self.lcb1(img1)\n s2 = self.lcb2(img2)\n s3 = self.lcb3(img3)\n s4 = self.lcb4(img4)\n return s1, s2, s3, s4\n\n\nclass Iter_Downsample(nn.Module):\n\n def __init__(self,):\n super(Iter_Downsample, self).__init__()\n self.init_ds = nn.Sequential(\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0), nn.MaxPool2d(kernel_size=2, stride=2, padding=0))\n self.ds1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=1)\n self.ds2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.ds3 = nn.MaxPool2d(kernel_size=2, stride=2, padding=1)\n self.ds4 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n\n def forward(self, x):\n x = self.init_ds(x)\n x1 = self.ds1(x)\n x2 = self.ds2(x1)\n x3 = self.ds3(x2)\n x4 = self.ds4(x3)\n return x1, x2, x3, x4\n\n\nclass FAM(nn.Module):\n\n def __init__(self, plane1, plane2, bn=True, ds=True, att=True):\n super(FAM, self).__init__()\n self.att = att\n self.bn = nn.BatchNorm2d(plane2, eps=1e-5, momentum=0.01, affine=True) if bn else None\n self.dsc = ConvBlock(plane1, plane2, kernel_size=(3, 3), stride=2, padding=1, relu=False) if ds else None\n self.merge = ConvBlock(plane2, plane2, kernel_size=(3, 3), stride=1, padding=1)\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, o, s, p):\n\n o_bn = self.bn(o) if self.bn is not None else o\n s_bn = s\n if self.att:\n x = o_bn * s_bn + self.dsc(p) if self.dsc is not None else o_bn * s_bn\n else:\n x = o_bn + self.dsc(p) if self.dsc is not None else o_bn\n out = self.merge(self.relu(x))\n\n return out\n\n\nclass LFIPNet(nn.Module):\n \"\"\"LFIP Net for object detection\n The network is based on the SSD architecture.\n Each multibox layer branches into\n 1) conv2d for class conf scores\n 2) conv2d for localization predictions\n 3) associated priorbox layer to produce default bounding\n boxes specific to the layer's feature map size.\n\n Args:\n phase: (string) Can be \"test\" or \"train\"\n base: VGG16 layers for input, size of either 300 or 512\n extras: extra layers that feed to multibox loc and conf layers\n head: \"multibox head\" consists of loc and conf conv layers\n \"\"\"\n\n def __init__(self, phase, size, base, extras, head, num_classes):\n super(LFIPNet, self).__init__()\n self.phase = phase\n self.num_classes = num_classes\n self.size = size\n\n if size == 300:\n self.indicator = 3\n elif size == 512:\n self.indicator = 5\n else:\n print(\"Error: Sorry only SSD300 and SSD512 are supported!\")\n return\n # vgg network\n self.base = nn.ModuleList(base)\n\n self.lfip = LFIP(in_planes=3)\n\n self.fam1 = FAM(plane1=512, plane2=512, bn=True, ds=False, att=True)\n self.fam2 = FAM(plane1=512, plane2=1024, bn=True, ds=True, att=True)\n self.fam3 = FAM(plane1=1024, plane2=512, bn=False, ds=True, att=True)\n self.fam4 = FAM(plane1=512, plane2=256, bn=False, ds=True, att=False)\n\n self.extras = nn.ModuleList(extras)\n self.loc = nn.ModuleList(head[0])\n self.conf = nn.ModuleList(head[1])\n if self.phase == 'test':\n self.softmax = nn.Softmax()\n\n def forward(self, x):\n \"\"\"Applies network layers and ops on input image(s) x.\n\n Args:\n x: input image or batch of images. Shape: [batch,3,300,300].\n\n Return:\n Depending on phase:\n test:\n list of concat outputs from:\n 1: softmax layers, Shape: [batch*num_priors,num_classes]\n 2: localization layers, Shape: [batch,num_priors*4]\n 3: priorbox layers, Shape: [2,num_priors*4]\n\n train:\n list of concat outputs from:\n 1: confidence layers, Shape: [batch*num_priors,num_classes]\n 2: localization layers, Shape: [batch,num_priors*4]\n 3: priorbox layers, Shape: [2,num_priors*4]\n \"\"\"\n sources = list()\n loc = list()\n conf = list()\n\n # generate image pyramid\n s1, s2, s3, s4 = self.lfip(x)\n\n # apply vgg up to conv4_3\n for k in range(22):\n x = self.base[k](x)\n f1 = self.fam1(x, s1, None)\n sources.append(f1)\n\n # apply vgg up to fc7\n for k in range(22, 34):\n x = self.base[k](x)\n f2 = self.fam2(x, s2, f1)\n sources.append(f2)\n\n x = self.base[34](x)\n\n # apply extra layers and cache source layer outputs\n for k, v in enumerate(self.extras):\n x = v(x)\n if k == 0:\n f3 = self.fam3(x, s3, f2)\n sources.append(f3)\n elif k == 2:\n f4 = self.fam4(x, s4, f3)\n sources.append(f4)\n elif k == 5 or k == 7:\n sources.append(x)\n else:\n pass\n\n # apply multibox head to source layers\n for (x, l, c) in zip(sources, self.loc, self.conf):\n loc.append(l(x).permute(0, 2, 3, 1).contiguous())\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n\n if self.phase == \"test\":\n output = (\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(-1, self.num_classes)), # conf preds\n )\n else:\n output = (\n loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n )\n return output\n\n\ndef vgg(cfg, i, batch_norm=False):\n layers = []\n in_channels = i\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif v == 'C':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=False)]\n else:\n layers += [conv2d, nn.ReLU(inplace=False)]\n in_channels = v\n pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)\n conv7 = nn.Conv2d(1024, 1024, kernel_size=1)\n layers += [pool5, conv6,\n nn.ReLU(inplace=False), conv7, nn.ReLU(inplace=False)]\n return layers\n\nbase = {\n '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M',\n 512, 512, 512],\n '512': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M',\n 512, 512, 512],\n}\n\n\ndef add_extras(size, cfg, i):\n # Extra layers added to VGG for feature scaling\n layers = []\n in_channels = i\n for k, v in enumerate(cfg):\n if in_channels != 'S':\n if v == 'S':\n if in_channels == 256 and size == 512:\n layers += [ExtraBlock(in_channels, cfg[k+1], stride=2), nn.ReLU(inplace=False)]\n else:\n layers += [ExtraBlock(in_channels, cfg[k+1], stride=2), nn.ReLU(inplace=False)]\n in_channels = v\n if size == 512:\n layers += [ConvBlock(256, 128, kernel_size=1, stride=1)]\n layers += [ConvBlock(128, 256, kernel_size=4, stride=1, padding=1)]\n elif size == 300:\n layers += [ConvBlock(256, 128, kernel_size=1,stride=1)]\n layers += [ConvBlock(128, 256, kernel_size=3,stride=1)]\n layers += [ConvBlock(256, 128, kernel_size=1,stride=1)]\n layers += [ConvBlock(128, 256, kernel_size=3,stride=1)]\n else:\n print(\"Error: Sorry only LFIPNet300 and LFIPNet512 are supported!\")\n return\n return layers\n\nextras = {\n '300': [1024, 'S', 512, 'S', 256],\n '512': [1024, 'S', 512, 'S', 256, 'S', 256,'S',256],\n}\n\n\ndef multibox(size, vgg, extra_layers, cfg, num_classes):\n loc_layers = []\n conf_layers = []\n vgg_source = [1, -2]\n for k, v in enumerate(vgg_source):\n if k == 0:\n loc_layers += [nn.Conv2d(512, cfg[k] * 4, kernel_size=3, padding=1)]\n conf_layers +=[nn.Conv2d(512, cfg[k] * num_classes, kernel_size=3, padding=1)]\n else:\n loc_layers += [nn.Conv2d(vgg[v].out_channels, cfg[k] * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(vgg[v].out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)]\n i = 2\n if size == 300:\n indicator = 3\n elif size == 512:\n indicator = 5\n else:\n print(\"Error: Sorry only LFIPNet300 and LFIPNet512 are supported!\")\n return\n\n for k, v in enumerate(extra_layers):\n if (k < indicator+1 and k % 2 == 0) or (k > indicator+1 and k % 2 != 0):\n loc_layers += [nn.Conv2d(v.out_channels, cfg[i] * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(v.out_channels, cfg[i] * num_classes, kernel_size=3, padding=1)]\n i += 1\n return vgg, extra_layers, (loc_layers, conf_layers)\n\nmbox = {\n '300': [6, 6, 6, 6, 4, 4], # number of boxes per feature map location\n '512': [6, 6, 6, 6, 6, 4, 4],\n}\n\n\ndef build_net(phase, size=300, num_classes=21):\n if phase != \"test\" and phase != \"train\":\n print(\"Error: Phase not recognized\")\n return\n if size != 300 and size != 512:\n print(\"Error: Sorry only LFIPNet300 and LFIPNet512 are supported!\")\n return\n\n return LFIPNet(phase, size, *multibox(size, vgg(base[str(size)], 3),\n add_extras(size, extras[str(size)], 1024),\n mbox[str(size)], num_classes), num_classes)\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
wakeful-sun/vehicle-detector
|
[
"080eab6acb2fc11dc5ea5a93ee5437347612aab2"
] |
[
"code/classifier/tools.py"
] |
[
"import numpy as np\r\n\r\n\r\ndef insert_separator(items, separator):\r\n row = []\r\n for index, item in enumerate(items):\r\n if index:\r\n row.append(separator)\r\n row.append(item)\r\n return row\r\n\r\n\r\ndef create_composite_image(bgr_images, h_span=5, v_span=5, n_columns=3):\r\n image_shapes = set(map(lambda x: x.shape, bgr_images))\r\n images_have_same_shape = len(image_shapes) == 1\r\n if not images_have_same_shape:\r\n raise NotImplementedError(\"Can't merge images of different shape\")\r\n\r\n h, w, d = image_shapes.pop()\r\n h_separator_shape = h_span, (w + v_span) * n_columns - h_span, d\r\n v_separator_shape = w, v_span, d\r\n\r\n h_separator = np.zeros(h_separator_shape, dtype=np.uint8)\r\n v_separator = np.zeros(v_separator_shape, dtype=np.uint8)\r\n\r\n row_counter = 0\r\n get_row_images = lambda x: bgr_images[(row_counter * n_columns):(row_counter * n_columns + n_columns)]\r\n\r\n row_images = get_row_images(bgr_images)\r\n rows = []\r\n while len(row_images):\r\n diff = n_columns - len(row_images)\r\n if diff > 0:\r\n empty_image = np.zeros((w, h, d), dtype=np.uint8)\r\n [row_images.append(empty_image) for i in range(diff)]\r\n\r\n row = insert_separator(row_images, v_separator)\r\n rows.append(np.hstack(row))\r\n\r\n row_counter = row_counter + 1\r\n row_images = get_row_images(bgr_images)\r\n\r\n image_rows = insert_separator(rows, h_separator)\r\n resulting_image = np.vstack(image_rows)\r\n return resulting_image"
] |
[
[
"numpy.hstack",
"numpy.zeros",
"numpy.vstack"
]
] |
mynameisguy/tensorflow
|
[
"2803742817755846f847ac506bbe20b4d4a14195"
] |
[
"tensorflow/contrib/rnn/python/ops/rnn_cell.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Module for constructing RNN Cells.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport math\n\nfrom tensorflow.contrib.compiler import jit\nfrom tensorflow.contrib.layers.python.layers import layers\nfrom tensorflow.contrib.rnn.python.ops import core_rnn_cell\nfrom tensorflow.contrib.rnn.python.ops import core_rnn_cell_impl\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import op_def_registry\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import rnn_cell_impl\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import nest\n\n\ndef _get_concat_variable(name, shape, dtype, num_shards):\n \"\"\"Get a sharded variable concatenated into one tensor.\"\"\"\n sharded_variable = _get_sharded_variable(name, shape, dtype, num_shards)\n if len(sharded_variable) == 1:\n return sharded_variable[0]\n\n concat_name = name + \"/concat\"\n concat_full_name = vs.get_variable_scope().name + \"/\" + concat_name + \":0\"\n for value in ops.get_collection(ops.GraphKeys.CONCATENATED_VARIABLES):\n if value.name == concat_full_name:\n return value\n\n concat_variable = array_ops.concat(sharded_variable, 0, name=concat_name)\n ops.add_to_collection(ops.GraphKeys.CONCATENATED_VARIABLES,\n concat_variable)\n return concat_variable\n\n\ndef _get_sharded_variable(name, shape, dtype, num_shards):\n \"\"\"Get a list of sharded variables with the given dtype.\"\"\"\n if num_shards > shape[0]:\n raise ValueError(\"Too many shards: shape=%s, num_shards=%d\" %\n (shape, num_shards))\n unit_shard_size = int(math.floor(shape[0] / num_shards))\n remaining_rows = shape[0] - unit_shard_size * num_shards\n\n shards = []\n for i in range(num_shards):\n current_size = unit_shard_size\n if i < remaining_rows:\n current_size += 1\n shards.append(vs.get_variable(name + \"_%d\" % i, [current_size] + shape[1:],\n dtype=dtype))\n return shards\n\n\nclass CoupledInputForgetGateLSTMCell(core_rnn_cell.RNNCell):\n \"\"\"Long short-term memory unit (LSTM) recurrent network cell.\n\n The default non-peephole implementation is based on:\n\n http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf\n\n S. Hochreiter and J. Schmidhuber.\n \"Long Short-Term Memory\". Neural Computation, 9(8):1735-1780, 1997.\n\n The peephole implementation is based on:\n\n https://research.google.com/pubs/archive/43905.pdf\n\n Hasim Sak, Andrew Senior, and Francoise Beaufays.\n \"Long short-term memory recurrent neural network architectures for\n large scale acoustic modeling.\" INTERSPEECH, 2014.\n\n The coupling of input and forget gate is based on:\n\n http://arxiv.org/pdf/1503.04069.pdf\n\n Greff et al. \"LSTM: A Search Space Odyssey\"\n\n The class uses optional peep-hole connections, and an optional projection\n layer.\n \"\"\"\n\n def __init__(self, num_units, use_peepholes=False,\n initializer=None, num_proj=None, proj_clip=None,\n num_unit_shards=1, num_proj_shards=1,\n forget_bias=1.0, state_is_tuple=True,\n activation=math_ops.tanh, reuse=None):\n \"\"\"Initialize the parameters for an LSTM cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell\n use_peepholes: bool, set True to enable diagonal/peephole connections.\n initializer: (optional) The initializer to use for the weight and\n projection matrices.\n num_proj: (optional) int, The output dimensionality for the projection\n matrices. If None, no projection is performed.\n proj_clip: (optional) A float value. If `num_proj > 0` and `proj_clip` is\n provided, then the projected values are clipped elementwise to within\n `[-proj_clip, proj_clip]`.\n num_unit_shards: How to split the weight matrix. If >1, the weight\n matrix is stored across num_unit_shards.\n num_proj_shards: How to split the projection matrix. If >1, the\n projection matrix is stored across num_proj_shards.\n forget_bias: Biases of the forget gate are initialized by default to 1\n in order to reduce the scale of forgetting at the beginning of\n the training.\n state_is_tuple: If True, accepted and returned states are 2-tuples of\n the `c_state` and `m_state`. By default (False), they are concatenated\n along the column axis. This default behavior will soon be deprecated.\n activation: Activation function of the inner states.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(CoupledInputForgetGateLSTMCell, self).__init__(_reuse=reuse)\n if not state_is_tuple:\n logging.warn(\n \"%s: Using a concatenated state is slower and will soon be \"\n \"deprecated. Use state_is_tuple=True.\", self)\n self._num_units = num_units\n self._use_peepholes = use_peepholes\n self._initializer = initializer\n self._num_proj = num_proj\n self._proj_clip = proj_clip\n self._num_unit_shards = num_unit_shards\n self._num_proj_shards = num_proj_shards\n self._forget_bias = forget_bias\n self._state_is_tuple = state_is_tuple\n self._activation = activation\n self._reuse = reuse\n\n if num_proj:\n self._state_size = (\n core_rnn_cell.LSTMStateTuple(num_units, num_proj)\n if state_is_tuple else num_units + num_proj)\n self._output_size = num_proj\n else:\n self._state_size = (\n core_rnn_cell.LSTMStateTuple(num_units, num_units)\n if state_is_tuple else 2 * num_units)\n self._output_size = num_units\n\n @property\n def state_size(self):\n return self._state_size\n\n @property\n def output_size(self):\n return self._output_size\n\n def call(self, inputs, state):\n \"\"\"Run one step of LSTM.\n\n Args:\n inputs: input Tensor, 2D, batch x num_units.\n state: if `state_is_tuple` is False, this must be a state Tensor,\n `2-D, batch x state_size`. If `state_is_tuple` is True, this must be a\n tuple of state Tensors, both `2-D`, with column sizes `c_state` and\n `m_state`.\n\n Returns:\n A tuple containing:\n - A `2-D, [batch x output_dim]`, Tensor representing the output of the\n LSTM after reading `inputs` when previous state was `state`.\n Here output_dim is:\n num_proj if num_proj was set,\n num_units otherwise.\n - Tensor(s) representing the new state of LSTM after reading `inputs` when\n the previous state was `state`. Same type and shape(s) as `state`.\n\n Raises:\n ValueError: If input size cannot be inferred from inputs via\n static shape inference.\n \"\"\"\n sigmoid = math_ops.sigmoid\n\n num_proj = self._num_units if self._num_proj is None else self._num_proj\n\n if self._state_is_tuple:\n (c_prev, m_prev) = state\n else:\n c_prev = array_ops.slice(state, [0, 0], [-1, self._num_units])\n m_prev = array_ops.slice(state, [0, self._num_units], [-1, num_proj])\n\n dtype = inputs.dtype\n input_size = inputs.get_shape().with_rank(2)[1]\n if input_size.value is None:\n raise ValueError(\"Could not infer input size from inputs.get_shape()[-1]\")\n concat_w = _get_concat_variable(\n \"W\", [input_size.value + num_proj, 3 * self._num_units],\n dtype, self._num_unit_shards)\n\n b = vs.get_variable(\n \"B\",\n shape=[3 * self._num_units],\n initializer=init_ops.zeros_initializer(),\n dtype=dtype)\n\n # j = new_input, f = forget_gate, o = output_gate\n cell_inputs = array_ops.concat([inputs, m_prev], 1)\n lstm_matrix = nn_ops.bias_add(math_ops.matmul(cell_inputs, concat_w), b)\n j, f, o = array_ops.split(value=lstm_matrix, num_or_size_splits=3, axis=1)\n\n # Diagonal connections\n if self._use_peepholes:\n w_f_diag = vs.get_variable(\n \"W_F_diag\", shape=[self._num_units], dtype=dtype)\n w_o_diag = vs.get_variable(\n \"W_O_diag\", shape=[self._num_units], dtype=dtype)\n\n if self._use_peepholes:\n f_act = sigmoid(f + self._forget_bias + w_f_diag * c_prev)\n else:\n f_act = sigmoid(f + self._forget_bias)\n c = (f_act * c_prev + (1 - f_act) * self._activation(j))\n\n if self._use_peepholes:\n m = sigmoid(o + w_o_diag * c) * self._activation(c)\n else:\n m = sigmoid(o) * self._activation(c)\n\n if self._num_proj is not None:\n concat_w_proj = _get_concat_variable(\n \"W_P\", [self._num_units, self._num_proj],\n dtype, self._num_proj_shards)\n\n m = math_ops.matmul(m, concat_w_proj)\n if self._proj_clip is not None:\n # pylint: disable=invalid-unary-operand-type\n m = clip_ops.clip_by_value(m, -self._proj_clip, self._proj_clip)\n # pylint: enable=invalid-unary-operand-type\n\n new_state = (core_rnn_cell.LSTMStateTuple(c, m) if self._state_is_tuple else\n array_ops.concat([c, m], 1))\n return m, new_state\n\n\nclass TimeFreqLSTMCell(core_rnn_cell.RNNCell):\n \"\"\"Time-Frequency Long short-term memory unit (LSTM) recurrent network cell.\n\n This implementation is based on:\n\n Tara N. Sainath and Bo Li\n \"Modeling Time-Frequency Patterns with LSTM vs. Convolutional Architectures\n for LVCSR Tasks.\" submitted to INTERSPEECH, 2016.\n\n It uses peep-hole connections and optional cell clipping.\n \"\"\"\n\n def __init__(self, num_units, use_peepholes=False,\n cell_clip=None, initializer=None,\n num_unit_shards=1, forget_bias=1.0,\n feature_size=None, frequency_skip=None,\n reuse=None):\n \"\"\"Initialize the parameters for an LSTM cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell\n use_peepholes: bool, set True to enable diagonal/peephole connections.\n cell_clip: (optional) A float value, if provided the cell state is clipped\n by this value prior to the cell output activation.\n initializer: (optional) The initializer to use for the weight and\n projection matrices.\n num_unit_shards: int, How to split the weight matrix. If >1, the weight\n matrix is stored across num_unit_shards.\n forget_bias: float, Biases of the forget gate are initialized by default\n to 1 in order to reduce the scale of forgetting at the beginning\n of the training.\n feature_size: int, The size of the input feature the LSTM spans over.\n frequency_skip: int, The amount the LSTM filter is shifted by in\n frequency.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(TimeFreqLSTMCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._use_peepholes = use_peepholes\n self._cell_clip = cell_clip\n self._initializer = initializer\n self._num_unit_shards = num_unit_shards\n self._forget_bias = forget_bias\n self._feature_size = feature_size\n self._frequency_skip = frequency_skip\n self._state_size = 2 * num_units\n self._output_size = num_units\n self._reuse = reuse\n\n @property\n def output_size(self):\n return self._output_size\n\n @property\n def state_size(self):\n return self._state_size\n\n def call(self, inputs, state):\n \"\"\"Run one step of LSTM.\n\n Args:\n inputs: input Tensor, 2D, batch x num_units.\n state: state Tensor, 2D, batch x state_size.\n\n Returns:\n A tuple containing:\n - A 2D, batch x output_dim, Tensor representing the output of the LSTM\n after reading \"inputs\" when previous state was \"state\".\n Here output_dim is num_units.\n - A 2D, batch x state_size, Tensor representing the new state of LSTM\n after reading \"inputs\" when previous state was \"state\".\n Raises:\n ValueError: if an input_size was specified and the provided inputs have\n a different dimension.\n \"\"\"\n sigmoid = math_ops.sigmoid\n tanh = math_ops.tanh\n\n freq_inputs = self._make_tf_features(inputs)\n dtype = inputs.dtype\n actual_input_size = freq_inputs[0].get_shape().as_list()[1]\n\n concat_w = _get_concat_variable(\n \"W\", [actual_input_size + 2*self._num_units, 4 * self._num_units],\n dtype, self._num_unit_shards)\n\n b = vs.get_variable(\n \"B\",\n shape=[4 * self._num_units],\n initializer=init_ops.zeros_initializer(),\n dtype=dtype)\n\n # Diagonal connections\n if self._use_peepholes:\n w_f_diag = vs.get_variable(\n \"W_F_diag\", shape=[self._num_units], dtype=dtype)\n w_i_diag = vs.get_variable(\n \"W_I_diag\", shape=[self._num_units], dtype=dtype)\n w_o_diag = vs.get_variable(\n \"W_O_diag\", shape=[self._num_units], dtype=dtype)\n\n # initialize the first freq state to be zero\n m_prev_freq = array_ops.zeros([int(inputs.get_shape()[0]),\n self._num_units], dtype)\n for fq in range(len(freq_inputs)):\n c_prev = array_ops.slice(state, [0, 2*fq*self._num_units],\n [-1, self._num_units])\n m_prev = array_ops.slice(state, [0, (2*fq+1)*self._num_units],\n [-1, self._num_units])\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\n cell_inputs = array_ops.concat([freq_inputs[fq], m_prev, m_prev_freq],\n 1)\n lstm_matrix = nn_ops.bias_add(math_ops.matmul(cell_inputs, concat_w), b)\n i, j, f, o = array_ops.split(\n value=lstm_matrix, num_or_size_splits=4, axis=1)\n\n if self._use_peepholes:\n c = (sigmoid(f + self._forget_bias + w_f_diag * c_prev) * c_prev +\n sigmoid(i + w_i_diag * c_prev) * tanh(j))\n else:\n c = (sigmoid(f + self._forget_bias) * c_prev + sigmoid(i) * tanh(j))\n\n if self._cell_clip is not None:\n # pylint: disable=invalid-unary-operand-type\n c = clip_ops.clip_by_value(c, -self._cell_clip, self._cell_clip)\n # pylint: enable=invalid-unary-operand-type\n\n if self._use_peepholes:\n m = sigmoid(o + w_o_diag * c) * tanh(c)\n else:\n m = sigmoid(o) * tanh(c)\n m_prev_freq = m\n if fq == 0:\n state_out = array_ops.concat([c, m], 1)\n m_out = m\n else:\n state_out = array_ops.concat([state_out, c, m], 1)\n m_out = array_ops.concat([m_out, m], 1)\n return m_out, state_out\n\n def _make_tf_features(self, input_feat):\n \"\"\"Make the frequency features.\n\n Args:\n input_feat: input Tensor, 2D, batch x num_units.\n\n Returns:\n A list of frequency features, with each element containing:\n - A 2D, batch x output_dim, Tensor representing the time-frequency feature\n for that frequency index. Here output_dim is feature_size.\n Raises:\n ValueError: if input_size cannot be inferred from static shape inference.\n \"\"\"\n input_size = input_feat.get_shape().with_rank(2)[-1].value\n if input_size is None:\n raise ValueError(\"Cannot infer input_size from static shape inference.\")\n num_feats = int((input_size - self._feature_size) / (\n self._frequency_skip)) + 1\n freq_inputs = []\n for f in range(num_feats):\n cur_input = array_ops.slice(input_feat, [0, f*self._frequency_skip],\n [-1, self._feature_size])\n freq_inputs.append(cur_input)\n return freq_inputs\n\n\nclass GridLSTMCell(core_rnn_cell.RNNCell):\n \"\"\"Grid Long short-term memory unit (LSTM) recurrent network cell.\n\n The default is based on:\n Nal Kalchbrenner, Ivo Danihelka and Alex Graves\n \"Grid Long Short-Term Memory,\" Proc. ICLR 2016.\n http://arxiv.org/abs/1507.01526\n\n When peephole connections are used, the implementation is based on:\n Tara N. Sainath and Bo Li\n \"Modeling Time-Frequency Patterns with LSTM vs. Convolutional Architectures\n for LVCSR Tasks.\" submitted to INTERSPEECH, 2016.\n\n The code uses optional peephole connections, shared_weights and cell clipping.\n \"\"\"\n\n def __init__(self, num_units, use_peepholes=False,\n share_time_frequency_weights=False,\n cell_clip=None, initializer=None,\n num_unit_shards=1, forget_bias=1.0,\n feature_size=None, frequency_skip=None,\n num_frequency_blocks=None,\n start_freqindex_list=None,\n end_freqindex_list=None,\n couple_input_forget_gates=False,\n state_is_tuple=True,\n reuse=None):\n \"\"\"Initialize the parameters for an LSTM cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell\n use_peepholes: (optional) bool, default False. Set True to enable\n diagonal/peephole connections.\n share_time_frequency_weights: (optional) bool, default False. Set True to\n enable shared cell weights between time and frequency LSTMs.\n cell_clip: (optional) A float value, default None, if provided the cell\n state is clipped by this value prior to the cell output activation.\n initializer: (optional) The initializer to use for the weight and\n projection matrices, default None.\n num_unit_shards: (optional) int, defualt 1, How to split the weight\n matrix. If > 1,the weight matrix is stored across num_unit_shards.\n forget_bias: (optional) float, default 1.0, The initial bias of the\n forget gates, used to reduce the scale of forgetting at the beginning\n of the training.\n feature_size: (optional) int, default None, The size of the input feature\n the LSTM spans over.\n frequency_skip: (optional) int, default None, The amount the LSTM filter\n is shifted by in frequency.\n num_frequency_blocks: [required] A list of frequency blocks needed to\n cover the whole input feature splitting defined by start_freqindex_list\n and end_freqindex_list.\n start_freqindex_list: [optional], list of ints, default None, The\n starting frequency index for each frequency block.\n end_freqindex_list: [optional], list of ints, default None. The ending\n frequency index for each frequency block.\n couple_input_forget_gates: (optional) bool, default False, Whether to\n couple the input and forget gates, i.e. f_gate = 1.0 - i_gate, to reduce\n model parameters and computation cost.\n state_is_tuple: If True, accepted and returned states are 2-tuples of\n the `c_state` and `m_state`. By default (False), they are concatenated\n along the column axis. This default behavior will soon be deprecated.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n Raises:\n ValueError: if the num_frequency_blocks list is not specified\n \"\"\"\n super(GridLSTMCell, self).__init__(_reuse=reuse)\n if not state_is_tuple:\n logging.warn(\"%s: Using a concatenated state is slower and will soon be \"\n \"deprecated. Use state_is_tuple=True.\", self)\n self._num_units = num_units\n self._use_peepholes = use_peepholes\n self._share_time_frequency_weights = share_time_frequency_weights\n self._couple_input_forget_gates = couple_input_forget_gates\n self._state_is_tuple = state_is_tuple\n self._cell_clip = cell_clip\n self._initializer = initializer\n self._num_unit_shards = num_unit_shards\n self._forget_bias = forget_bias\n self._feature_size = feature_size\n self._frequency_skip = frequency_skip\n self._start_freqindex_list = start_freqindex_list\n self._end_freqindex_list = end_freqindex_list\n self._num_frequency_blocks = num_frequency_blocks\n self._total_blocks = 0\n self._reuse = reuse\n if self._num_frequency_blocks is None:\n raise ValueError(\"Must specify num_frequency_blocks\")\n\n for block_index in range(len(self._num_frequency_blocks)):\n self._total_blocks += int(self._num_frequency_blocks[block_index])\n if state_is_tuple:\n state_names = \"\"\n for block_index in range(len(self._num_frequency_blocks)):\n for freq_index in range(self._num_frequency_blocks[block_index]):\n name_prefix = \"state_f%02d_b%02d\" % (freq_index, block_index)\n state_names += (\"%s_c, %s_m,\" % (name_prefix, name_prefix))\n self._state_tuple_type = collections.namedtuple(\n \"GridLSTMStateTuple\", state_names.strip(\",\"))\n self._state_size = self._state_tuple_type(\n *([num_units, num_units] * self._total_blocks))\n else:\n self._state_tuple_type = None\n self._state_size = num_units * self._total_blocks * 2\n self._output_size = num_units * self._total_blocks * 2\n\n @property\n def output_size(self):\n return self._output_size\n\n @property\n def state_size(self):\n return self._state_size\n\n @property\n def state_tuple_type(self):\n return self._state_tuple_type\n\n def call(self, inputs, state):\n \"\"\"Run one step of LSTM.\n\n Args:\n inputs: input Tensor, 2D, [batch, feature_size].\n state: Tensor or tuple of Tensors, 2D, [batch, state_size], depends on the\n flag self._state_is_tuple.\n\n Returns:\n A tuple containing:\n - A 2D, [batch, output_dim], Tensor representing the output of the LSTM\n after reading \"inputs\" when previous state was \"state\".\n Here output_dim is num_units.\n - A 2D, [batch, state_size], Tensor representing the new state of LSTM\n after reading \"inputs\" when previous state was \"state\".\n Raises:\n ValueError: if an input_size was specified and the provided inputs have\n a different dimension.\n \"\"\"\n batch_size = inputs.shape[0].value or array_ops.shape(inputs)[0]\n freq_inputs = self._make_tf_features(inputs)\n m_out_lst = []\n state_out_lst = []\n for block in range(len(freq_inputs)):\n m_out_lst_current, state_out_lst_current = self._compute(\n freq_inputs[block], block, state, batch_size,\n state_is_tuple=self._state_is_tuple)\n m_out_lst.extend(m_out_lst_current)\n state_out_lst.extend(state_out_lst_current)\n if self._state_is_tuple:\n state_out = self._state_tuple_type(*state_out_lst)\n else:\n state_out = array_ops.concat(state_out_lst, 1)\n m_out = array_ops.concat(m_out_lst, 1)\n return m_out, state_out\n\n def _compute(self, freq_inputs, block, state, batch_size,\n state_prefix=\"state\",\n state_is_tuple=True):\n \"\"\"Run the actual computation of one step LSTM.\n\n Args:\n freq_inputs: list of Tensors, 2D, [batch, feature_size].\n block: int, current frequency block index to process.\n state: Tensor or tuple of Tensors, 2D, [batch, state_size], it depends on\n the flag state_is_tuple.\n batch_size: int32, batch size.\n state_prefix: (optional) string, name prefix for states, defaults to\n \"state\".\n state_is_tuple: boolean, indicates whether the state is a tuple or Tensor.\n\n Returns:\n A tuple, containing:\n - A list of [batch, output_dim] Tensors, representing the output of the\n LSTM given the inputs and state.\n - A list of [batch, state_size] Tensors, representing the LSTM state\n values given the inputs and previous state.\n \"\"\"\n sigmoid = math_ops.sigmoid\n tanh = math_ops.tanh\n num_gates = 3 if self._couple_input_forget_gates else 4\n dtype = freq_inputs[0].dtype\n actual_input_size = freq_inputs[0].get_shape().as_list()[1]\n\n concat_w_f = _get_concat_variable(\n \"W_f_%d\" % block, [actual_input_size + 2 * self._num_units,\n num_gates * self._num_units],\n dtype, self._num_unit_shards)\n b_f = vs.get_variable(\n \"B_f_%d\" % block,\n shape=[num_gates * self._num_units],\n initializer=init_ops.zeros_initializer(),\n dtype=dtype)\n if not self._share_time_frequency_weights:\n concat_w_t = _get_concat_variable(\n \"W_t_%d\" % block, [actual_input_size + 2 * self._num_units,\n num_gates * self._num_units],\n dtype, self._num_unit_shards)\n b_t = vs.get_variable(\n \"B_t_%d\" % block,\n shape=[num_gates * self._num_units],\n initializer=init_ops.zeros_initializer(),\n dtype=dtype)\n\n if self._use_peepholes:\n # Diagonal connections\n if not self._couple_input_forget_gates:\n w_f_diag_freqf = vs.get_variable(\n \"W_F_diag_freqf_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_f_diag_freqt = vs.get_variable(\n \"W_F_diag_freqt_%d\"% block, shape=[self._num_units], dtype=dtype)\n w_i_diag_freqf = vs.get_variable(\n \"W_I_diag_freqf_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_i_diag_freqt = vs.get_variable(\n \"W_I_diag_freqt_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_o_diag_freqf = vs.get_variable(\n \"W_O_diag_freqf_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_o_diag_freqt = vs.get_variable(\n \"W_O_diag_freqt_%d\" % block, shape=[self._num_units], dtype=dtype)\n if not self._share_time_frequency_weights:\n if not self._couple_input_forget_gates:\n w_f_diag_timef = vs.get_variable(\n \"W_F_diag_timef_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_f_diag_timet = vs.get_variable(\n \"W_F_diag_timet_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_i_diag_timef = vs.get_variable(\n \"W_I_diag_timef_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_i_diag_timet = vs.get_variable(\n \"W_I_diag_timet_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_o_diag_timef = vs.get_variable(\n \"W_O_diag_timef_%d\" % block, shape=[self._num_units], dtype=dtype)\n w_o_diag_timet = vs.get_variable(\n \"W_O_diag_timet_%d\" % block, shape=[self._num_units], dtype=dtype)\n\n # initialize the first freq state to be zero\n m_prev_freq = array_ops.zeros([batch_size, self._num_units], dtype)\n c_prev_freq = array_ops.zeros([batch_size, self._num_units], dtype)\n for freq_index in range(len(freq_inputs)):\n if state_is_tuple:\n name_prefix = \"%s_f%02d_b%02d\" % (state_prefix, freq_index, block)\n c_prev_time = getattr(state, name_prefix + \"_c\")\n m_prev_time = getattr(state, name_prefix + \"_m\")\n else:\n c_prev_time = array_ops.slice(\n state, [0, 2 * freq_index * self._num_units],\n [-1, self._num_units])\n m_prev_time = array_ops.slice(\n state, [0, (2 * freq_index + 1) * self._num_units],\n [-1, self._num_units])\n\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\n cell_inputs = array_ops.concat(\n [freq_inputs[freq_index], m_prev_time, m_prev_freq], 1)\n\n # F-LSTM\n lstm_matrix_freq = nn_ops.bias_add(math_ops.matmul(cell_inputs,\n concat_w_f), b_f)\n if self._couple_input_forget_gates:\n i_freq, j_freq, o_freq = array_ops.split(\n value=lstm_matrix_freq, num_or_size_splits=num_gates, axis=1)\n f_freq = None\n else:\n i_freq, j_freq, f_freq, o_freq = array_ops.split(\n value=lstm_matrix_freq, num_or_size_splits=num_gates, axis=1)\n # T-LSTM\n if self._share_time_frequency_weights:\n i_time = i_freq\n j_time = j_freq\n f_time = f_freq\n o_time = o_freq\n else:\n lstm_matrix_time = nn_ops.bias_add(math_ops.matmul(cell_inputs,\n concat_w_t), b_t)\n if self._couple_input_forget_gates:\n i_time, j_time, o_time = array_ops.split(\n value=lstm_matrix_time, num_or_size_splits=num_gates, axis=1)\n f_time = None\n else:\n i_time, j_time, f_time, o_time = array_ops.split(\n value=lstm_matrix_time, num_or_size_splits=num_gates, axis=1)\n\n # F-LSTM c_freq\n # input gate activations\n if self._use_peepholes:\n i_freq_g = sigmoid(i_freq +\n w_i_diag_freqf * c_prev_freq +\n w_i_diag_freqt * c_prev_time)\n else:\n i_freq_g = sigmoid(i_freq)\n # forget gate activations\n if self._couple_input_forget_gates:\n f_freq_g = 1.0 - i_freq_g\n else:\n if self._use_peepholes:\n f_freq_g = sigmoid(f_freq + self._forget_bias +\n w_f_diag_freqf * c_prev_freq +\n w_f_diag_freqt * c_prev_time)\n else:\n f_freq_g = sigmoid(f_freq + self._forget_bias)\n # cell state\n c_freq = f_freq_g * c_prev_freq + i_freq_g * tanh(j_freq)\n if self._cell_clip is not None:\n # pylint: disable=invalid-unary-operand-type\n c_freq = clip_ops.clip_by_value(c_freq, -self._cell_clip,\n self._cell_clip)\n # pylint: enable=invalid-unary-operand-type\n\n # T-LSTM c_freq\n # input gate activations\n if self._use_peepholes:\n if self._share_time_frequency_weights:\n i_time_g = sigmoid(i_time +\n w_i_diag_freqf * c_prev_freq +\n w_i_diag_freqt * c_prev_time)\n else:\n i_time_g = sigmoid(i_time +\n w_i_diag_timef * c_prev_freq +\n w_i_diag_timet * c_prev_time)\n else:\n i_time_g = sigmoid(i_time)\n # forget gate activations\n if self._couple_input_forget_gates:\n f_time_g = 1.0 - i_time_g\n else:\n if self._use_peepholes:\n if self._share_time_frequency_weights:\n f_time_g = sigmoid(f_time + self._forget_bias +\n w_f_diag_freqf * c_prev_freq +\n w_f_diag_freqt * c_prev_time)\n else:\n f_time_g = sigmoid(f_time + self._forget_bias +\n w_f_diag_timef * c_prev_freq +\n w_f_diag_timet * c_prev_time)\n else:\n f_time_g = sigmoid(f_time + self._forget_bias)\n # cell state\n c_time = f_time_g * c_prev_time + i_time_g * tanh(j_time)\n if self._cell_clip is not None:\n # pylint: disable=invalid-unary-operand-type\n c_time = clip_ops.clip_by_value(c_time, -self._cell_clip,\n self._cell_clip)\n # pylint: enable=invalid-unary-operand-type\n\n # F-LSTM m_freq\n if self._use_peepholes:\n m_freq = sigmoid(o_freq +\n w_o_diag_freqf * c_freq +\n w_o_diag_freqt * c_time) * tanh(c_freq)\n else:\n m_freq = sigmoid(o_freq) * tanh(c_freq)\n\n # T-LSTM m_time\n if self._use_peepholes:\n if self._share_time_frequency_weights:\n m_time = sigmoid(o_time +\n w_o_diag_freqf * c_freq +\n w_o_diag_freqt * c_time) * tanh(c_time)\n else:\n m_time = sigmoid(o_time +\n w_o_diag_timef * c_freq +\n w_o_diag_timet * c_time) * tanh(c_time)\n else:\n m_time = sigmoid(o_time) * tanh(c_time)\n\n m_prev_freq = m_freq\n c_prev_freq = c_freq\n # Concatenate the outputs for T-LSTM and F-LSTM for each shift\n if freq_index == 0:\n state_out_lst = [c_time, m_time]\n m_out_lst = [m_time, m_freq]\n else:\n state_out_lst.extend([c_time, m_time])\n m_out_lst.extend([m_time, m_freq])\n\n return m_out_lst, state_out_lst\n\n def _make_tf_features(self, input_feat, slice_offset=0):\n \"\"\"Make the frequency features.\n\n Args:\n input_feat: input Tensor, 2D, [batch, num_units].\n slice_offset: (optional) Python int, default 0, the slicing offset is only\n used for the backward processing in the BidirectionalGridLSTMCell. It\n specifies a different starting point instead of always 0 to enable the\n forward and backward processing look at different frequency blocks.\n\n Returns:\n A list of frequency features, with each element containing:\n - A 2D, [batch, output_dim], Tensor representing the time-frequency\n feature for that frequency index. Here output_dim is feature_size.\n Raises:\n ValueError: if input_size cannot be inferred from static shape inference.\n \"\"\"\n input_size = input_feat.get_shape().with_rank(2)[-1].value\n if input_size is None:\n raise ValueError(\"Cannot infer input_size from static shape inference.\")\n if slice_offset > 0:\n # Padding to the end\n inputs = array_ops.pad(\n input_feat, array_ops.constant([0, 0, 0, slice_offset], shape=[2, 2],\n dtype=dtypes.int32),\n \"CONSTANT\")\n elif slice_offset < 0:\n # Padding to the front\n inputs = array_ops.pad(\n input_feat, array_ops.constant([0, 0, -slice_offset, 0], shape=[2, 2],\n dtype=dtypes.int32),\n \"CONSTANT\")\n slice_offset = 0\n else:\n inputs = input_feat\n freq_inputs = []\n if not self._start_freqindex_list:\n if len(self._num_frequency_blocks) != 1:\n raise ValueError(\"Length of num_frequency_blocks\"\n \" is not 1, but instead is %d\",\n len(self._num_frequency_blocks))\n num_feats = int((input_size - self._feature_size) / (\n self._frequency_skip)) + 1\n if num_feats != self._num_frequency_blocks[0]:\n raise ValueError(\n \"Invalid num_frequency_blocks, requires %d but gets %d, please\"\n \" check the input size and filter config are correct.\" % (\n self._num_frequency_blocks[0], num_feats))\n block_inputs = []\n for f in range(num_feats):\n cur_input = array_ops.slice(\n inputs, [0, slice_offset + f * self._frequency_skip],\n [-1, self._feature_size])\n block_inputs.append(cur_input)\n freq_inputs.append(block_inputs)\n else:\n if len(self._start_freqindex_list) != len(self._end_freqindex_list):\n raise ValueError(\"Length of start and end freqindex_list\"\n \" does not match %d %d\",\n len(self._start_freqindex_list),\n len(self._end_freqindex_list))\n if len(self._num_frequency_blocks) != len(self._start_freqindex_list):\n raise ValueError(\"Length of num_frequency_blocks\"\n \" is not equal to start_freqindex_list %d %d\",\n len(self._num_frequency_blocks),\n len(self._start_freqindex_list))\n for b in range(len(self._start_freqindex_list)):\n start_index = self._start_freqindex_list[b]\n end_index = self._end_freqindex_list[b]\n cur_size = end_index - start_index\n block_feats = int((cur_size - self._feature_size) / (\n self._frequency_skip)) + 1\n if block_feats != self._num_frequency_blocks[b]:\n raise ValueError(\n \"Invalid num_frequency_blocks, requires %d but gets %d, please\"\n \" check the input size and filter config are correct.\" % (\n self._num_frequency_blocks[b], block_feats))\n block_inputs = []\n for f in range(block_feats):\n cur_input = array_ops.slice(\n inputs, [0, start_index + slice_offset + f *\n self._frequency_skip],\n [-1, self._feature_size])\n block_inputs.append(cur_input)\n freq_inputs.append(block_inputs)\n return freq_inputs\n\n\nclass BidirectionalGridLSTMCell(GridLSTMCell):\n \"\"\"Bidirectional GridLstm cell.\n\n The bidirection connection is only used in the frequency direction, which\n hence doesn't affect the time direction's real-time processing that is\n required for online recognition systems.\n The current implementation uses different weights for the two directions.\n \"\"\"\n\n def __init__(self, num_units, use_peepholes=False,\n share_time_frequency_weights=False,\n cell_clip=None, initializer=None,\n num_unit_shards=1, forget_bias=1.0,\n feature_size=None, frequency_skip=None,\n num_frequency_blocks=None,\n start_freqindex_list=None,\n end_freqindex_list=None,\n couple_input_forget_gates=False,\n backward_slice_offset=0,\n reuse=None):\n \"\"\"Initialize the parameters for an LSTM cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell\n use_peepholes: (optional) bool, default False. Set True to enable\n diagonal/peephole connections.\n share_time_frequency_weights: (optional) bool, default False. Set True to\n enable shared cell weights between time and frequency LSTMs.\n cell_clip: (optional) A float value, default None, if provided the cell\n state is clipped by this value prior to the cell output activation.\n initializer: (optional) The initializer to use for the weight and\n projection matrices, default None.\n num_unit_shards: (optional) int, defualt 1, How to split the weight\n matrix. If > 1,the weight matrix is stored across num_unit_shards.\n forget_bias: (optional) float, default 1.0, The initial bias of the\n forget gates, used to reduce the scale of forgetting at the beginning\n of the training.\n feature_size: (optional) int, default None, The size of the input feature\n the LSTM spans over.\n frequency_skip: (optional) int, default None, The amount the LSTM filter\n is shifted by in frequency.\n num_frequency_blocks: [required] A list of frequency blocks needed to\n cover the whole input feature splitting defined by start_freqindex_list\n and end_freqindex_list.\n start_freqindex_list: [optional], list of ints, default None, The\n starting frequency index for each frequency block.\n end_freqindex_list: [optional], list of ints, default None. The ending\n frequency index for each frequency block.\n couple_input_forget_gates: (optional) bool, default False, Whether to\n couple the input and forget gates, i.e. f_gate = 1.0 - i_gate, to reduce\n model parameters and computation cost.\n backward_slice_offset: (optional) int32, default 0, the starting offset to\n slice the feature for backward processing.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(BidirectionalGridLSTMCell, self).__init__(\n num_units, use_peepholes, share_time_frequency_weights, cell_clip,\n initializer, num_unit_shards, forget_bias, feature_size, frequency_skip,\n num_frequency_blocks, start_freqindex_list, end_freqindex_list,\n couple_input_forget_gates, True, reuse)\n self._backward_slice_offset = int(backward_slice_offset)\n state_names = \"\"\n for direction in [\"fwd\", \"bwd\"]:\n for block_index in range(len(self._num_frequency_blocks)):\n for freq_index in range(self._num_frequency_blocks[block_index]):\n name_prefix = \"%s_state_f%02d_b%02d\" % (direction, freq_index,\n block_index)\n state_names += (\"%s_c, %s_m,\" % (name_prefix, name_prefix))\n self._state_tuple_type = collections.namedtuple(\n \"BidirectionalGridLSTMStateTuple\", state_names.strip(\",\"))\n self._state_size = self._state_tuple_type(\n *([num_units, num_units] * self._total_blocks * 2))\n self._output_size = 2 * num_units * self._total_blocks * 2\n\n def call(self, inputs, state):\n \"\"\"Run one step of LSTM.\n\n Args:\n inputs: input Tensor, 2D, [batch, num_units].\n state: tuple of Tensors, 2D, [batch, state_size].\n\n Returns:\n A tuple containing:\n - A 2D, [batch, output_dim], Tensor representing the output of the LSTM\n after reading \"inputs\" when previous state was \"state\".\n Here output_dim is num_units.\n - A 2D, [batch, state_size], Tensor representing the new state of LSTM\n after reading \"inputs\" when previous state was \"state\".\n Raises:\n ValueError: if an input_size was specified and the provided inputs have\n a different dimension.\n \"\"\"\n batch_size = inputs.shape[0].value or array_ops.shape(inputs)[0]\n fwd_inputs = self._make_tf_features(inputs)\n if self._backward_slice_offset:\n bwd_inputs = self._make_tf_features(inputs, self._backward_slice_offset)\n else:\n bwd_inputs = fwd_inputs\n\n # Forward processing\n with vs.variable_scope(\"fwd\"):\n fwd_m_out_lst = []\n fwd_state_out_lst = []\n for block in range(len(fwd_inputs)):\n fwd_m_out_lst_current, fwd_state_out_lst_current = self._compute(\n fwd_inputs[block], block, state, batch_size,\n state_prefix=\"fwd_state\", state_is_tuple=True)\n fwd_m_out_lst.extend(fwd_m_out_lst_current)\n fwd_state_out_lst.extend(fwd_state_out_lst_current)\n # Backward processing\n bwd_m_out_lst = []\n bwd_state_out_lst = []\n with vs.variable_scope(\"bwd\"):\n for block in range(len(bwd_inputs)):\n # Reverse the blocks\n bwd_inputs_reverse = bwd_inputs[block][::-1]\n bwd_m_out_lst_current, bwd_state_out_lst_current = self._compute(\n bwd_inputs_reverse, block, state, batch_size,\n state_prefix=\"bwd_state\", state_is_tuple=True)\n bwd_m_out_lst.extend(bwd_m_out_lst_current)\n bwd_state_out_lst.extend(bwd_state_out_lst_current)\n state_out = self._state_tuple_type(*(fwd_state_out_lst + bwd_state_out_lst))\n # Outputs are always concated as it is never used separately.\n m_out = array_ops.concat(fwd_m_out_lst + bwd_m_out_lst, 1)\n return m_out, state_out\n\n\n# pylint: disable=protected-access\n_linear = core_rnn_cell_impl._linear\n# pylint: enable=protected-access\n\n\nclass AttentionCellWrapper(core_rnn_cell.RNNCell):\n \"\"\"Basic attention cell wrapper.\n\n Implementation based on https://arxiv.org/abs/1409.0473.\n \"\"\"\n\n def __init__(self, cell, attn_length, attn_size=None, attn_vec_size=None,\n input_size=None, state_is_tuple=True, reuse=None):\n \"\"\"Create a cell with attention.\n\n Args:\n cell: an RNNCell, an attention is added to it.\n attn_length: integer, the size of an attention window.\n attn_size: integer, the size of an attention vector. Equal to\n cell.output_size by default.\n attn_vec_size: integer, the number of convolutional features calculated\n on attention state and a size of the hidden layer built from\n base cell state. Equal attn_size to by default.\n input_size: integer, the size of a hidden linear layer,\n built from inputs and attention. Derived from the input tensor\n by default.\n state_is_tuple: If True, accepted and returned states are n-tuples, where\n `n = len(cells)`. By default (False), the states are all\n concatenated along the column axis.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n\n Raises:\n TypeError: if cell is not an RNNCell.\n ValueError: if cell returns a state tuple but the flag\n `state_is_tuple` is `False` or if attn_length is zero or less.\n \"\"\"\n super(AttentionCellWrapper, self).__init__(_reuse=reuse)\n if not rnn_cell_impl._like_rnncell(cell): # pylint: disable=protected-access\n raise TypeError(\"The parameter cell is not RNNCell.\")\n if nest.is_sequence(cell.state_size) and not state_is_tuple:\n raise ValueError(\"Cell returns tuple of states, but the flag \"\n \"state_is_tuple is not set. State size is: %s\"\n % str(cell.state_size))\n if attn_length <= 0:\n raise ValueError(\"attn_length should be greater than zero, got %s\"\n % str(attn_length))\n if not state_is_tuple:\n logging.warn(\n \"%s: Using a concatenated state is slower and will soon be \"\n \"deprecated. Use state_is_tuple=True.\", self)\n if attn_size is None:\n attn_size = cell.output_size\n if attn_vec_size is None:\n attn_vec_size = attn_size\n self._state_is_tuple = state_is_tuple\n self._cell = cell\n self._attn_vec_size = attn_vec_size\n self._input_size = input_size\n self._attn_size = attn_size\n self._attn_length = attn_length\n self._reuse = reuse\n\n @property\n def state_size(self):\n size = (self._cell.state_size, self._attn_size,\n self._attn_size * self._attn_length)\n if self._state_is_tuple:\n return size\n else:\n return sum(list(size))\n\n @property\n def output_size(self):\n return self._attn_size\n\n def call(self, inputs, state):\n \"\"\"Long short-term memory cell with attention (LSTMA).\"\"\"\n if self._state_is_tuple:\n state, attns, attn_states = state\n else:\n states = state\n state = array_ops.slice(states, [0, 0], [-1, self._cell.state_size])\n attns = array_ops.slice(\n states, [0, self._cell.state_size], [-1, self._attn_size])\n attn_states = array_ops.slice(\n states, [0, self._cell.state_size + self._attn_size],\n [-1, self._attn_size * self._attn_length])\n attn_states = array_ops.reshape(attn_states,\n [-1, self._attn_length, self._attn_size])\n input_size = self._input_size\n if input_size is None:\n input_size = inputs.get_shape().as_list()[1]\n inputs = _linear([inputs, attns], input_size, True)\n lstm_output, new_state = self._cell(inputs, state)\n if self._state_is_tuple:\n new_state_cat = array_ops.concat(nest.flatten(new_state), 1)\n else:\n new_state_cat = new_state\n new_attns, new_attn_states = self._attention(new_state_cat, attn_states)\n with vs.variable_scope(\"attn_output_projection\"):\n output = _linear([lstm_output, new_attns], self._attn_size, True)\n new_attn_states = array_ops.concat(\n [new_attn_states, array_ops.expand_dims(output, 1)], 1)\n new_attn_states = array_ops.reshape(\n new_attn_states, [-1, self._attn_length * self._attn_size])\n new_state = (new_state, new_attns, new_attn_states)\n if not self._state_is_tuple:\n new_state = array_ops.concat(list(new_state), 1)\n return output, new_state\n\n def _attention(self, query, attn_states):\n conv2d = nn_ops.conv2d\n reduce_sum = math_ops.reduce_sum\n softmax = nn_ops.softmax\n tanh = math_ops.tanh\n\n with vs.variable_scope(\"attention\"):\n k = vs.get_variable(\n \"attn_w\", [1, 1, self._attn_size, self._attn_vec_size])\n v = vs.get_variable(\"attn_v\", [self._attn_vec_size])\n hidden = array_ops.reshape(attn_states,\n [-1, self._attn_length, 1, self._attn_size])\n hidden_features = conv2d(hidden, k, [1, 1, 1, 1], \"SAME\")\n y = _linear(query, self._attn_vec_size, True)\n y = array_ops.reshape(y, [-1, 1, 1, self._attn_vec_size])\n s = reduce_sum(v * tanh(hidden_features + y), [2, 3])\n a = softmax(s)\n d = reduce_sum(\n array_ops.reshape(a, [-1, self._attn_length, 1, 1]) * hidden, [1, 2])\n new_attns = array_ops.reshape(d, [-1, self._attn_size])\n new_attn_states = array_ops.slice(attn_states, [0, 1, 0], [-1, -1, -1])\n return new_attns, new_attn_states\n\n\nclass HighwayWrapper(core_rnn_cell.RNNCell):\n \"\"\"RNNCell wrapper that adds highway connection on cell input and output.\n\n Based on:\n R. K. Srivastava, K. Greff, and J. Schmidhuber, \"Highway networks\",\n arXiv preprint arXiv:1505.00387, 2015.\n https://arxiv.org/abs/1505.00387\n \"\"\"\n\n def __init__(self, cell,\n couple_carry_transform_gates=True,\n carry_bias_init=1.0):\n \"\"\"Constructs a `HighwayWrapper` for `cell`.\n\n Args:\n cell: An instance of `RNNCell`.\n couple_carry_transform_gates: boolean, should the Carry and Transform gate\n be coupled.\n carry_bias_init: float, carry gates bias initialization.\n \"\"\"\n self._cell = cell\n self._couple_carry_transform_gates = couple_carry_transform_gates\n self._carry_bias_init = carry_bias_init\n\n @property\n def state_size(self):\n return self._cell.state_size\n\n @property\n def output_size(self):\n return self._cell.output_size\n\n def zero_state(self, batch_size, dtype):\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\n return self._cell.zero_state(batch_size, dtype)\n\n def _highway(self, inp, out):\n input_size = inp.get_shape().with_rank(2)[1].value\n carry_weight = vs.get_variable(\"carry_w\", [input_size, input_size])\n carry_bias = vs.get_variable(\n \"carry_b\", [input_size],\n initializer=init_ops.constant_initializer(\n self._carry_bias_init))\n carry = math_ops.sigmoid(nn_ops.xw_plus_b(inp, carry_weight, carry_bias))\n if self._couple_carry_transform_gates:\n transform = 1 - carry\n else:\n transform_weight = vs.get_variable(\"transform_w\",\n [input_size, input_size])\n transform_bias = vs.get_variable(\n \"transform_b\", [input_size],\n initializer=init_ops.constant_initializer(\n -self._carry_bias_init))\n transform = math_ops.sigmoid(nn_ops.xw_plus_b(inp,\n transform_weight,\n transform_bias))\n return inp * carry + out * transform\n\n def __call__(self, inputs, state, scope=None):\n \"\"\"Run the cell and add its inputs to its outputs.\n\n Args:\n inputs: cell inputs.\n state: cell state.\n scope: optional cell scope.\n\n Returns:\n Tuple of cell outputs and new state.\n\n Raises:\n TypeError: If cell inputs and outputs have different structure (type).\n ValueError: If cell inputs and outputs have different structure (value).\n \"\"\"\n outputs, new_state = self._cell(inputs, state, scope=scope)\n nest.assert_same_structure(inputs, outputs)\n # Ensure shapes match\n def assert_shape_match(inp, out):\n inp.get_shape().assert_is_compatible_with(out.get_shape())\n nest.map_structure(assert_shape_match, inputs, outputs)\n res_outputs = nest.map_structure(self._highway, inputs, outputs)\n return (res_outputs, new_state)\n\n\nclass LayerNormBasicLSTMCell(core_rnn_cell.RNNCell):\n \"\"\"LSTM unit with layer normalization and recurrent dropout.\n\n This class adds layer normalization and recurrent dropout to a\n basic LSTM unit. Layer normalization implementation is based on:\n\n https://arxiv.org/abs/1607.06450.\n\n \"Layer Normalization\"\n Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton\n\n and is applied before the internal nonlinearities.\n Recurrent dropout is base on:\n\n https://arxiv.org/abs/1603.05118\n\n \"Recurrent Dropout without Memory Loss\"\n Stanislau Semeniuta, Aliaksei Severyn, Erhardt Barth.\n \"\"\"\n\n def __init__(self, num_units, forget_bias=1.0,\n input_size=None, activation=math_ops.tanh,\n layer_norm=True, norm_gain=1.0, norm_shift=0.0,\n dropout_keep_prob=1.0, dropout_prob_seed=None,\n reuse=None):\n \"\"\"Initializes the basic LSTM cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell.\n forget_bias: float, The bias added to forget gates (see above).\n input_size: Deprecated and unused.\n activation: Activation function of the inner states.\n layer_norm: If `True`, layer normalization will be applied.\n norm_gain: float, The layer normalization gain initial value. If\n `layer_norm` has been set to `False`, this argument will be ignored.\n norm_shift: float, The layer normalization shift initial value. If\n `layer_norm` has been set to `False`, this argument will be ignored.\n dropout_keep_prob: unit Tensor or float between 0 and 1 representing the\n recurrent dropout probability value. If float and 1.0, no dropout will\n be applied.\n dropout_prob_seed: (optional) integer, the randomness seed.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(LayerNormBasicLSTMCell, self).__init__(_reuse=reuse)\n\n if input_size is not None:\n logging.warn(\"%s: The input_size parameter is deprecated.\", self)\n\n self._num_units = num_units\n self._activation = activation\n self._forget_bias = forget_bias\n self._keep_prob = dropout_keep_prob\n self._seed = dropout_prob_seed\n self._layer_norm = layer_norm\n self._g = norm_gain\n self._b = norm_shift\n self._reuse = reuse\n\n @property\n def state_size(self):\n return core_rnn_cell.LSTMStateTuple(self._num_units, self._num_units)\n\n @property\n def output_size(self):\n return self._num_units\n\n def _norm(self, inp, scope):\n shape = inp.get_shape()[-1:]\n gamma_init = init_ops.constant_initializer(self._g)\n beta_init = init_ops.constant_initializer(self._b)\n with vs.variable_scope(scope):\n # Initialize beta and gamma for use by layer_norm.\n vs.get_variable(\"gamma\", shape=shape, initializer=gamma_init)\n vs.get_variable(\"beta\", shape=shape, initializer=beta_init)\n normalized = layers.layer_norm(inp, reuse=True, scope=scope)\n return normalized\n\n def _linear(self, args):\n out_size = 4 * self._num_units\n proj_size = args.get_shape()[-1]\n weights = vs.get_variable(\"kernel\", [proj_size, out_size])\n out = math_ops.matmul(args, weights)\n if not self._layer_norm:\n bias = vs.get_variable(\"bias\", [out_size])\n out = nn_ops.bias_add(out, bias)\n return out\n\n def call(self, inputs, state):\n \"\"\"LSTM cell with layer normalization and recurrent dropout.\"\"\"\n c, h = state\n args = array_ops.concat([inputs, h], 1)\n concat = self._linear(args)\n\n i, j, f, o = array_ops.split(value=concat, num_or_size_splits=4, axis=1)\n if self._layer_norm:\n i = self._norm(i, \"input\")\n j = self._norm(j, \"transform\")\n f = self._norm(f, \"forget\")\n o = self._norm(o, \"output\")\n\n g = self._activation(j)\n if (not isinstance(self._keep_prob, float)) or self._keep_prob < 1:\n g = nn_ops.dropout(g, self._keep_prob, seed=self._seed)\n\n new_c = (c * math_ops.sigmoid(f + self._forget_bias)\n + math_ops.sigmoid(i) * g)\n if self._layer_norm:\n new_c = self._norm(new_c, \"state\")\n new_h = self._activation(new_c) * math_ops.sigmoid(o)\n\n new_state = core_rnn_cell.LSTMStateTuple(new_c, new_h)\n return new_h, new_state\n\n\nclass NASCell(core_rnn_cell.RNNCell):\n \"\"\"Neural Architecture Search (NAS) recurrent network cell.\n\n This implements the recurrent cell from the paper:\n\n https://arxiv.org/abs/1611.01578\n\n Barret Zoph and Quoc V. Le.\n \"Neural Architecture Search with Reinforcement Learning\" Proc. ICLR 2017.\n\n The class uses an optional projection layer.\n \"\"\"\n\n def __init__(self, num_units, num_proj=None,\n use_biases=False, reuse=None):\n \"\"\"Initialize the parameters for a NAS cell.\n\n Args:\n num_units: int, The number of units in the NAS cell\n num_proj: (optional) int, The output dimensionality for the projection\n matrices. If None, no projection is performed.\n use_biases: (optional) bool, If True then use biases within the cell. This\n is False by default.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(NASCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._num_proj = num_proj\n self._use_biases = use_biases\n self._reuse = reuse\n\n if num_proj is not None:\n self._state_size = core_rnn_cell.LSTMStateTuple(num_units, num_proj)\n self._output_size = num_proj\n else:\n self._state_size = core_rnn_cell.LSTMStateTuple(num_units, num_units)\n self._output_size = num_units\n\n @property\n def state_size(self):\n return self._state_size\n\n @property\n def output_size(self):\n return self._output_size\n\n def call(self, inputs, state):\n \"\"\"Run one step of NAS Cell.\n\n Args:\n inputs: input Tensor, 2D, batch x num_units.\n state: This must be a tuple of state Tensors, both `2-D`, with column\n sizes `c_state` and `m_state`.\n\n Returns:\n A tuple containing:\n - A `2-D, [batch x output_dim]`, Tensor representing the output of the\n NAS Cell after reading `inputs` when previous state was `state`.\n Here output_dim is:\n num_proj if num_proj was set,\n num_units otherwise.\n - Tensor(s) representing the new state of NAS Cell after reading `inputs`\n when the previous state was `state`. Same type and shape(s) as `state`.\n\n Raises:\n ValueError: If input size cannot be inferred from inputs via\n static shape inference.\n \"\"\"\n sigmoid = math_ops.sigmoid\n tanh = math_ops.tanh\n relu = nn_ops.relu\n\n num_proj = self._num_units if self._num_proj is None else self._num_proj\n\n (c_prev, m_prev) = state\n\n dtype = inputs.dtype\n input_size = inputs.get_shape().with_rank(2)[1]\n if input_size.value is None:\n raise ValueError(\"Could not infer input size from inputs.get_shape()[-1]\")\n # Variables for the NAS cell. W_m is all matrices multiplying the\n # hiddenstate and W_inputs is all matrices multiplying the inputs.\n concat_w_m = vs.get_variable(\n \"recurrent_kernel\", [num_proj, 8 * self._num_units],\n dtype)\n concat_w_inputs = vs.get_variable(\n \"kernel\", [input_size.value, 8 * self._num_units],\n dtype)\n\n m_matrix = math_ops.matmul(m_prev, concat_w_m)\n inputs_matrix = math_ops.matmul(inputs, concat_w_inputs)\n\n if self._use_biases:\n b = vs.get_variable(\n \"bias\",\n shape=[8 * self._num_units],\n initializer=init_ops.zeros_initializer(),\n dtype=dtype)\n m_matrix = nn_ops.bias_add(m_matrix, b)\n\n # The NAS cell branches into 8 different splits for both the hiddenstate\n # and the input\n m_matrix_splits = array_ops.split(axis=1, num_or_size_splits=8,\n value=m_matrix)\n inputs_matrix_splits = array_ops.split(axis=1, num_or_size_splits=8,\n value=inputs_matrix)\n\n # First layer\n layer1_0 = sigmoid(inputs_matrix_splits[0] + m_matrix_splits[0])\n layer1_1 = relu(inputs_matrix_splits[1] + m_matrix_splits[1])\n layer1_2 = sigmoid(inputs_matrix_splits[2] + m_matrix_splits[2])\n layer1_3 = relu(inputs_matrix_splits[3] * m_matrix_splits[3])\n layer1_4 = tanh(inputs_matrix_splits[4] + m_matrix_splits[4])\n layer1_5 = sigmoid(inputs_matrix_splits[5] + m_matrix_splits[5])\n layer1_6 = tanh(inputs_matrix_splits[6] + m_matrix_splits[6])\n layer1_7 = sigmoid(inputs_matrix_splits[7] + m_matrix_splits[7])\n\n # Second layer\n l2_0 = tanh(layer1_0 * layer1_1)\n l2_1 = tanh(layer1_2 + layer1_3)\n l2_2 = tanh(layer1_4 * layer1_5)\n l2_3 = sigmoid(layer1_6 + layer1_7)\n\n # Inject the cell\n l2_0 = tanh(l2_0 + c_prev)\n\n # Third layer\n l3_0_pre = l2_0 * l2_1\n new_c = l3_0_pre # create new cell\n l3_0 = l3_0_pre\n l3_1 = tanh(l2_2 + l2_3)\n\n # Final layer\n new_m = tanh(l3_0 * l3_1)\n\n # Projection layer if specified\n if self._num_proj is not None:\n concat_w_proj = vs.get_variable(\n \"projection_weights\", [self._num_units, self._num_proj],\n dtype)\n new_m = math_ops.matmul(new_m, concat_w_proj)\n\n new_state = core_rnn_cell.LSTMStateTuple(new_c, new_m)\n return new_m, new_state\n\n\nclass UGRNNCell(core_rnn_cell.RNNCell):\n \"\"\"Update Gate Recurrent Neural Network (UGRNN) cell.\n\n Compromise between a LSTM/GRU and a vanilla RNN. There is only one\n gate, and that is to determine whether the unit should be\n integrating or computing instantaneously. This is the recurrent\n idea of the feedforward Highway Network.\n\n This implements the recurrent cell from the paper:\n\n https://arxiv.org/abs/1611.09913\n\n Jasmine Collins, Jascha Sohl-Dickstein, and David Sussillo.\n \"Capacity and Trainability in Recurrent Neural Networks\" Proc. ICLR 2017.\n \"\"\"\n\n def __init__(self, num_units, initializer=None, forget_bias=1.0,\n activation=math_ops.tanh, reuse=None):\n \"\"\"Initialize the parameters for an UGRNN cell.\n\n Args:\n num_units: int, The number of units in the UGRNN cell\n initializer: (optional) The initializer to use for the weight matrices.\n forget_bias: (optional) float, default 1.0, The initial bias of the\n forget gate, used to reduce the scale of forgetting at the beginning\n of the training.\n activation: (optional) Activation function of the inner states.\n Default is `tf.tanh`.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(UGRNNCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._initializer = initializer\n self._forget_bias = forget_bias\n self._activation = activation\n self._reuse = reuse\n\n @property\n def state_size(self):\n return self._num_units\n\n @property\n def output_size(self):\n return self._num_units\n\n def call(self, inputs, state):\n \"\"\"Run one step of UGRNN.\n\n Args:\n inputs: input Tensor, 2D, batch x input size.\n state: state Tensor, 2D, batch x num units.\n\n Returns:\n new_output: batch x num units, Tensor representing the output of the UGRNN\n after reading `inputs` when previous state was `state`. Identical to\n `new_state`.\n new_state: batch x num units, Tensor representing the state of the UGRNN\n after reading `inputs` when previous state was `state`.\n\n Raises:\n ValueError: If input size cannot be inferred from inputs via\n static shape inference.\n \"\"\"\n sigmoid = math_ops.sigmoid\n\n input_size = inputs.get_shape().with_rank(2)[1]\n if input_size.value is None:\n raise ValueError(\"Could not infer input size from inputs.get_shape()[-1]\")\n\n with vs.variable_scope(vs.get_variable_scope(),\n initializer=self._initializer):\n cell_inputs = array_ops.concat([inputs, state], 1)\n rnn_matrix = _linear(cell_inputs, 2 * self._num_units, True)\n\n [g_act, c_act] = array_ops.split(\n axis=1, num_or_size_splits=2, value=rnn_matrix)\n\n c = self._activation(c_act)\n g = sigmoid(g_act + self._forget_bias)\n new_state = g * state + (1.0 - g) * c\n new_output = new_state\n\n return new_output, new_state\n\n\nclass IntersectionRNNCell(core_rnn_cell.RNNCell):\n \"\"\"Intersection Recurrent Neural Network (+RNN) cell.\n\n Architecture with coupled recurrent gate as well as coupled depth\n gate, designed to improve information flow through stacked RNNs. As the\n architecture uses depth gating, the dimensionality of the depth\n output (y) also should not change through depth (input size == output size).\n To achieve this, the first layer of a stacked Intersection RNN projects\n the inputs to N (num units) dimensions. Therefore when initializing an\n IntersectionRNNCell, one should set `num_in_proj = N` for the first layer\n and use default settings for subsequent layers.\n\n This implements the recurrent cell from the paper:\n\n https://arxiv.org/abs/1611.09913\n\n Jasmine Collins, Jascha Sohl-Dickstein, and David Sussillo.\n \"Capacity and Trainability in Recurrent Neural Networks\" Proc. ICLR 2017.\n\n The Intersection RNN is built for use in deeply stacked\n RNNs so it may not achieve best performance with depth 1.\n \"\"\"\n\n def __init__(self, num_units, num_in_proj=None,\n initializer=None, forget_bias=1.0,\n y_activation=nn_ops.relu, reuse=None):\n \"\"\"Initialize the parameters for an +RNN cell.\n\n Args:\n num_units: int, The number of units in the +RNN cell\n num_in_proj: (optional) int, The input dimensionality for the RNN.\n If creating the first layer of an +RNN, this should be set to\n `num_units`. Otherwise, this should be set to `None` (default).\n If `None`, dimensionality of `inputs` should be equal to `num_units`,\n otherwise ValueError is thrown.\n initializer: (optional) The initializer to use for the weight matrices.\n forget_bias: (optional) float, default 1.0, The initial bias of the\n forget gates, used to reduce the scale of forgetting at the beginning\n of the training.\n y_activation: (optional) Activation function of the states passed\n through depth. Default is 'tf.nn.relu`.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(IntersectionRNNCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._initializer = initializer\n self._forget_bias = forget_bias\n self._num_input_proj = num_in_proj\n self._y_activation = y_activation\n self._reuse = reuse\n\n @property\n def state_size(self):\n return self._num_units\n\n @property\n def output_size(self):\n return self._num_units\n\n def call(self, inputs, state):\n \"\"\"Run one step of the Intersection RNN.\n\n Args:\n inputs: input Tensor, 2D, batch x input size.\n state: state Tensor, 2D, batch x num units.\n\n Returns:\n new_y: batch x num units, Tensor representing the output of the +RNN\n after reading `inputs` when previous state was `state`.\n new_state: batch x num units, Tensor representing the state of the +RNN\n after reading `inputs` when previous state was `state`.\n\n Raises:\n ValueError: If input size cannot be inferred from `inputs` via\n static shape inference.\n ValueError: If input size != output size (these must be equal when\n using the Intersection RNN).\n \"\"\"\n sigmoid = math_ops.sigmoid\n tanh = math_ops.tanh\n\n input_size = inputs.get_shape().with_rank(2)[1]\n if input_size.value is None:\n raise ValueError(\"Could not infer input size from inputs.get_shape()[-1]\")\n\n with vs.variable_scope(vs.get_variable_scope(),\n initializer=self._initializer):\n # read-in projections (should be used for first layer in deep +RNN\n # to transform size of inputs from I --> N)\n if input_size.value != self._num_units:\n if self._num_input_proj:\n with vs.variable_scope(\"in_projection\"):\n inputs = _linear(inputs, self._num_units, True)\n else:\n raise ValueError(\"Must have input size == output size for \"\n \"Intersection RNN. To fix, num_in_proj should \"\n \"be set to num_units at cell init.\")\n\n n_dim = i_dim = self._num_units\n cell_inputs = array_ops.concat([inputs, state], 1)\n rnn_matrix = _linear(cell_inputs, 2*n_dim + 2*i_dim, True)\n\n gh_act = rnn_matrix[:, :n_dim] # b x n\n h_act = rnn_matrix[:, n_dim:2*n_dim] # b x n\n gy_act = rnn_matrix[:, 2*n_dim:2*n_dim+i_dim] # b x i\n y_act = rnn_matrix[:, 2*n_dim+i_dim:2*n_dim+2*i_dim] # b x i\n\n h = tanh(h_act)\n y = self._y_activation(y_act)\n gh = sigmoid(gh_act + self._forget_bias)\n gy = sigmoid(gy_act + self._forget_bias)\n\n new_state = gh * state + (1.0 - gh) * h # passed thru time\n new_y = gy * inputs + (1.0 - gy) * y # passed thru depth\n\n return new_y, new_state\n\n\n_REGISTERED_OPS = None\n\n\nclass CompiledWrapper(core_rnn_cell.RNNCell):\n \"\"\"Wraps step execution in an XLA JIT scope.\"\"\"\n\n def __init__(self, cell, compile_stateful=False):\n \"\"\"Create CompiledWrapper cell.\n\n Args:\n cell: Instance of `RNNCell`.\n compile_stateful: Whether to compile stateful ops like initializers\n and random number generators (default: False).\n \"\"\"\n self._cell = cell\n self._compile_stateful = compile_stateful\n\n @property\n def state_size(self):\n return self._cell.state_size\n\n @property\n def output_size(self):\n return self._cell.output_size\n\n def zero_state(self, batch_size, dtype):\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\n return self._cell.zero_state(batch_size, dtype)\n\n def __call__(self, inputs, state, scope=None):\n if self._compile_stateful:\n compile_ops = True\n else:\n def compile_ops(node_def):\n global _REGISTERED_OPS\n if _REGISTERED_OPS is None:\n _REGISTERED_OPS = op_def_registry.get_registered_ops()\n return not _REGISTERED_OPS[node_def.op].is_stateful\n\n with jit.experimental_jit_scope(compile_ops=compile_ops):\n return self._cell(inputs, state, scope)\n\n\ndef _random_exp_initializer(minval,\n maxval,\n seed=None,\n dtype=dtypes.float32):\n \"\"\"Returns an exponential distribution initializer.\n\n Args:\n minval: float or a scalar float Tensor. With value > 0. Lower bound of the\n range of random values to generate.\n maxval: float or a scalar float Tensor. With value > minval. Upper bound of\n the range of random values to generate.\n seed: An integer. Used to create random seeds.\n dtype: The data type.\n\n Returns:\n An initializer that generates tensors with an exponential distribution.\n \"\"\"\n\n def _initializer(shape, dtype=dtype, partition_info=None):\n del partition_info # Unused.\n return math_ops.exp(\n random_ops.random_uniform(\n shape,\n math_ops.log(minval),\n math_ops.log(maxval),\n dtype,\n seed=seed))\n\n return _initializer\n\n\nclass PhasedLSTMCell(core_rnn_cell.RNNCell):\n \"\"\"Phased LSTM recurrent network cell.\n\n https://arxiv.org/pdf/1610.09513v1.pdf\n \"\"\"\n\n def __init__(self,\n num_units,\n use_peepholes=False,\n leak=0.001,\n ratio_on=0.1,\n trainable_ratio_on=True,\n period_init_min=1.0,\n period_init_max=1000.0,\n reuse=None):\n \"\"\"Initialize the Phased LSTM cell.\n\n Args:\n num_units: int, The number of units in the Phased LSTM cell.\n use_peepholes: bool, set True to enable peephole connections.\n leak: float or scalar float Tensor with value in [0, 1]. Leak applied\n during training.\n ratio_on: float or scalar float Tensor with value in [0, 1]. Ratio of the\n period during which the gates are open.\n trainable_ratio_on: bool, weather ratio_on is trainable.\n period_init_min: float or scalar float Tensor. With value > 0.\n Minimum value of the initalized period.\n The period values are initialized by drawing from the distribution:\n e^U(log(period_init_min), log(period_init_max))\n Where U(.,.) is the uniform distribution.\n period_init_max: float or scalar float Tensor.\n With value > period_init_min. Maximum value of the initalized period.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already has\n the given variables, an error is raised.\n \"\"\"\n super(PhasedLSTMCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._use_peepholes = use_peepholes\n self._leak = leak\n self._ratio_on = ratio_on\n self._trainable_ratio_on = trainable_ratio_on\n self._period_init_min = period_init_min\n self._period_init_max = period_init_max\n self._reuse = reuse\n\n @property\n def state_size(self):\n return core_rnn_cell.LSTMStateTuple(self._num_units, self._num_units)\n\n @property\n def output_size(self):\n return self._num_units\n\n def _mod(self, x, y):\n \"\"\"Modulo function that propagates x gradients.\"\"\"\n return array_ops.stop_gradient(math_ops.mod(x, y) - x) + x\n\n def _get_cycle_ratio(self, time, phase, period):\n \"\"\"Compute the cycle ratio in the dtype of the time.\"\"\"\n phase_casted = math_ops.cast(phase, dtype=time.dtype)\n period_casted = math_ops.cast(period, dtype=time.dtype)\n shifted_time = time - phase_casted\n cycle_ratio = self._mod(shifted_time, period_casted) / period_casted\n return math_ops.cast(cycle_ratio, dtype=dtypes.float32)\n\n def call(self, inputs, state):\n \"\"\"Phased LSTM Cell.\n\n Args:\n inputs: A tuple of 2 Tensor.\n The first Tensor has shape [batch, 1], and type float32 or float64.\n It stores the time.\n The second Tensor has shape [batch, features_size], and type float32.\n It stores the features.\n state: core_rnn_cell.LSTMStateTuple, state from previous timestep.\n\n Returns:\n A tuple containing:\n - A Tensor of float32, and shape [batch_size, num_units], representing the\n output of the cell.\n - A core_rnn_cell.LSTMStateTuple, containing 2 Tensors of float32, shape\n [batch_size, num_units], representing the new state and the output.\n \"\"\"\n (c_prev, h_prev) = state\n (time, x) = inputs\n\n in_mask_gates = [x, h_prev]\n if self._use_peepholes:\n in_mask_gates.append(c_prev)\n\n with vs.variable_scope(\"mask_gates\"):\n mask_gates = math_ops.sigmoid(\n _linear(in_mask_gates, 2 * self._num_units, True))\n [input_gate, forget_gate] = array_ops.split(\n axis=1, num_or_size_splits=2, value=mask_gates)\n\n with vs.variable_scope(\"new_input\"):\n new_input = math_ops.tanh(\n _linear([x, h_prev], self._num_units, True))\n\n new_c = (c_prev * forget_gate + input_gate * new_input)\n\n in_out_gate = [x, h_prev]\n if self._use_peepholes:\n in_out_gate.append(new_c)\n\n with vs.variable_scope(\"output_gate\"):\n output_gate = math_ops.sigmoid(\n _linear(in_out_gate, self._num_units, True))\n\n new_h = math_ops.tanh(new_c) * output_gate\n\n period = vs.get_variable(\n \"period\", [self._num_units],\n initializer=_random_exp_initializer(\n self._period_init_min, self._period_init_max))\n phase = vs.get_variable(\n \"phase\", [self._num_units],\n initializer=init_ops.random_uniform_initializer(\n 0., period.initial_value))\n ratio_on = vs.get_variable(\n \"ratio_on\", [self._num_units],\n initializer=init_ops.constant_initializer(self._ratio_on),\n trainable=self._trainable_ratio_on)\n\n cycle_ratio = self._get_cycle_ratio(time, phase, period)\n\n k_up = 2 * cycle_ratio / ratio_on\n k_down = 2 - k_up\n k_closed = self._leak * cycle_ratio\n\n k = array_ops.where(cycle_ratio < ratio_on, k_down, k_closed)\n k = array_ops.where(cycle_ratio < 0.5 * ratio_on, k_up, k)\n\n new_c = k * new_c + (1 - k) * c_prev\n new_h = k * new_h + (1 - k) * h_prev\n\n new_state = core_rnn_cell.LSTMStateTuple(new_c, new_h)\n\n return new_h, new_state\n\n\nclass GLSTMCell(core_rnn_cell.RNNCell):\n \"\"\"Group LSTM cell (G-LSTM).\n\n The implementation is based on:\n\n https://arxiv.org/abs/1703.10722\n\n O. Kuchaiev and B. Ginsburg\n \"Factorization Tricks for LSTM Networks\", ICLR 2017 workshop.\n \"\"\"\n\n def __init__(self, num_units, initializer=None, num_proj=None,\n number_of_groups=1, forget_bias=1.0, activation=math_ops.tanh,\n reuse=None):\n \"\"\"Initialize the parameters of G-LSTM cell.\n\n Args:\n num_units: int, The number of units in the G-LSTM cell\n initializer: (optional) The initializer to use for the weight and\n projection matrices.\n num_proj: (optional) int, The output dimensionality for the projection\n matrices. If None, no projection is performed.\n number_of_groups: (optional) int, number of groups to use.\n If `number_of_groups` is 1, then it should be equivalent to LSTM cell\n forget_bias: Biases of the forget gate are initialized by default to 1\n in order to reduce the scale of forgetting at the beginning of\n the training.\n activation: Activation function of the inner states.\n reuse: (optional) Python boolean describing whether to reuse variables\n in an existing scope. If not `True`, and the existing scope already\n has the given variables, an error is raised.\n\n Raises:\n ValueError: If `num_units` or `num_proj` is not divisible by \n `number_of_groups`.\n \"\"\"\n super(GLSTMCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._initializer = initializer\n self._num_proj = num_proj\n self._forget_bias = forget_bias\n self._activation = activation\n self._number_of_groups = number_of_groups\n\n if self._num_units % self._number_of_groups != 0:\n raise ValueError(\"num_units must be divisible by number_of_groups\")\n if self._num_proj:\n if self._num_proj % self._number_of_groups != 0:\n raise ValueError(\"num_proj must be divisible by number_of_groups\")\n self._group_shape = [int(self._num_proj / self._number_of_groups),\n int(self._num_units / self._number_of_groups)]\n else:\n self._group_shape = [int(self._num_units / self._number_of_groups),\n int(self._num_units / self._number_of_groups)]\n\n if num_proj:\n self._state_size = core_rnn_cell.LSTMStateTuple(num_units, num_proj)\n self._output_size = num_proj\n else:\n self._state_size = core_rnn_cell.LSTMStateTuple(num_units, num_units)\n self._output_size = num_units\n\n @property\n def state_size(self):\n return self._state_size\n\n @property\n def output_size(self):\n return self._output_size\n\n def _get_input_for_group(self, inputs, group_id, group_size):\n \"\"\"Slices inputs into groups to prepare for processing by cell's groups\n\n Args:\n inputs: cell input or it's previous state,\n a Tensor, 2D, [batch x num_units]\n group_id: group id, a Scalar, for which to prepare input\n group_size: size of the group\n\n Returns:\n subset of inputs corresponding to group \"group_id\",\n a Tensor, 2D, [batch x num_units/number_of_groups]\n \"\"\"\n return array_ops.slice(input_=inputs,\n begin=[0, group_id * group_size],\n size=[self._batch_size, group_size],\n name=(\"GLSTM_group%d_input_generation\" % group_id))\n\n def call(self, inputs, state):\n \"\"\"Run one step of G-LSTM.\n\n Args:\n inputs: input Tensor, 2D, [batch x num_units].\n state: this must be a tuple of state Tensors, both `2-D`,\n with column sizes `c_state` and `m_state`.\n\n Returns:\n A tuple containing:\n\n - A `2-D, [batch x output_dim]`, Tensor representing the output of the\n G-LSTM after reading `inputs` when previous state was `state`.\n Here output_dim is:\n num_proj if num_proj was set,\n num_units otherwise.\n - LSTMStateTuple representing the new state of G-LSTM cell\n after reading `inputs` when the previous state was `state`.\n\n Raises:\n ValueError: If input size cannot be inferred from inputs via\n static shape inference.\n \"\"\"\n (c_prev, m_prev) = state\n\n self._batch_size = inputs.shape[0].value or array_ops.shape(inputs)[0]\n dtype = inputs.dtype\n scope = vs.get_variable_scope()\n with vs.variable_scope(scope, initializer=self._initializer):\n i_parts = []\n j_parts = []\n f_parts = []\n o_parts = []\n\n for group_id in range(self._number_of_groups):\n with vs.variable_scope(\"group%d\" % group_id):\n x_g_id = array_ops.concat(\n [self._get_input_for_group(inputs, group_id,\n self._group_shape[0]),\n self._get_input_for_group(m_prev, group_id,\n self._group_shape[0])], axis=1)\n R_k = _linear(x_g_id, 4 * self._group_shape[1], bias=False)\n i_k, j_k, f_k, o_k = array_ops.split(R_k, 4, 1)\n\n i_parts.append(i_k)\n j_parts.append(j_k)\n f_parts.append(f_k)\n o_parts.append(o_k)\n\n bi = vs.get_variable(name=\"bias_i\",\n shape=[self._num_units],\n dtype=dtype,\n initializer=\n init_ops.constant_initializer(0.0, dtype=dtype))\n bj = vs.get_variable(name=\"bias_j\",\n shape=[self._num_units],\n dtype=dtype,\n initializer=\n init_ops.constant_initializer(0.0, dtype=dtype))\n bf = vs.get_variable(name=\"bias_f\",\n shape=[self._num_units],\n dtype=dtype,\n initializer=\n init_ops.constant_initializer(0.0, dtype=dtype))\n bo = vs.get_variable(name=\"bias_o\",\n shape=[self._num_units],\n dtype=dtype,\n initializer=\n init_ops.constant_initializer(0.0, dtype=dtype))\n\n i = nn_ops.bias_add(array_ops.concat(i_parts, axis=1), bi)\n j = nn_ops.bias_add(array_ops.concat(j_parts, axis=1), bj)\n f = nn_ops.bias_add(array_ops.concat(f_parts, axis=1), bf)\n o = nn_ops.bias_add(array_ops.concat(o_parts, axis=1), bo)\n\n c = (math_ops.sigmoid(f + self._forget_bias) * c_prev +\n math_ops.sigmoid(i) * math_ops.tanh(j))\n m = math_ops.sigmoid(o) * self._activation(c)\n\n if self._num_proj is not None:\n with vs.variable_scope(\"projection\"):\n m = _linear(m, self._num_proj, bias=False)\n\n new_state = core_rnn_cell.LSTMStateTuple(c, m)\n return m, new_state\n"
] |
[
[
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.ops.array_ops.constant",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.split",
"tensorflow.contrib.compiler.jit.experimental_jit_scope",
"tensorflow.python.framework.op_def_registry.get_registered_ops",
"tensorflow.python.framework.ops.add_to_collection",
"tensorflow.python.ops.math_ops.tanh",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.ops.init_ops.random_uniform_initializer",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.python.ops.rnn_cell_impl._like_rnncell",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.ops.array_ops.where",
"tensorflow.python.ops.clip_ops.clip_by_value",
"tensorflow.python.ops.nn_ops.bias_add",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.util.nest.map_structure",
"tensorflow.contrib.layers.python.layers.layers.layer_norm",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.array_ops.slice",
"tensorflow.python.util.nest.is_sequence",
"tensorflow.python.ops.variable_scope.get_variable_scope",
"tensorflow.contrib.rnn.python.ops.core_rnn_cell.LSTMStateTuple",
"tensorflow.python.util.nest.assert_same_structure",
"tensorflow.python.ops.math_ops.sigmoid",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.ops.nn_ops.dropout",
"tensorflow.python.ops.variable_scope.get_variable",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.python.ops.math_ops.mod",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.nn_ops.xw_plus_b",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.util.nest.flatten"
]
] |
sxontheway/milliEye
|
[
"bfdb041c978a45d7481071e8e9579d226ce523ff",
"bfdb041c978a45d7481071e8e9579d226ce523ff"
] |
[
"module3_our_dataset/yolov3/models.py",
"module2_mixed/test_mixed.py"
] |
[
"from __future__ import division\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\nfrom utils.parse_config import *\nfrom utils.utils import build_targets, to_cpu\n\ndef create_modules(module_defs):\n \"\"\"\n Constructs module list of layer blocks from module configuration in module_defs\n \"\"\"\n hyperparams = module_defs.pop(0)\n output_filters = [int(hyperparams[\"channels\"])]\n module_list = nn.ModuleList()\n for module_i, module_def in enumerate(module_defs):\n modules = nn.Sequential()\n\n if module_def[\"type\"] == \"convolutional\":\n bn = int(module_def[\"batch_normalize\"])\n filters = int(module_def[\"filters\"])\n kernel_size = int(module_def[\"size\"])\n pad = (kernel_size - 1) // 2\n modules.add_module(\n f\"conv_{module_i}\",\n nn.Conv2d(\n in_channels=output_filters[-1],\n out_channels=filters,\n kernel_size=kernel_size,\n stride=int(module_def[\"stride\"]),\n padding=pad,\n bias=not bn,\n ),\n )\n if bn:\n modules.add_module(f\"batch_norm_{module_i}\", nn.BatchNorm2d(filters, momentum=0.9, eps=1e-5))\n if module_def[\"activation\"] == \"leaky\":\n modules.add_module(f\"leaky_{module_i}\", nn.LeakyReLU(0.1))\n\n elif module_def[\"type\"] == \"maxpool\":\n kernel_size = int(module_def[\"size\"])\n stride = int(module_def[\"stride\"])\n if kernel_size == 2 and stride == 1:\n modules.add_module(f\"_debug_padding_{module_i}\", nn.ZeroPad2d((0, 1, 0, 1)))\n maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=int((kernel_size - 1) // 2))\n modules.add_module(f\"maxpool_{module_i}\", maxpool)\n\n elif module_def[\"type\"] == \"upsample\":\n upsample = Upsample(scale_factor=int(module_def[\"stride\"]), mode=\"nearest\")\n modules.add_module(f\"upsample_{module_i}\", upsample)\n\n elif module_def[\"type\"] == \"route\":\n layers = [int(x) for x in module_def[\"layers\"].split(\",\")]\n filters = sum([output_filters[1:][i] for i in layers])\n modules.add_module(f\"route_{module_i}\", EmptyLayer())\n\n elif module_def[\"type\"] == \"shortcut\":\n filters = output_filters[1:][int(module_def[\"from\"])]\n modules.add_module(f\"shortcut_{module_i}\", EmptyLayer())\n\n elif module_def[\"type\"] == \"yolo\":\n anchor_idxs = [int(x) for x in module_def[\"mask\"].split(\",\")]\n # Extract anchors\n anchors = [int(x) for x in module_def[\"anchors\"].split(\",\")]\n anchors = [(anchors[i], anchors[i + 1]) for i in range(0, len(anchors), 2)]\n anchors = [anchors[i] for i in anchor_idxs]\n num_classes = int(module_def[\"classes\"])\n img_size = int(hyperparams[\"height\"])\n # Define detection layer\n yolo_layer = YOLOLayer(anchors, num_classes, img_size)\n modules.add_module(f\"yolo_{module_i}\", yolo_layer)\n # Register module list and number of output filters\n module_list.append(modules)\n output_filters.append(filters)\n\n return hyperparams, module_list\n\n\nclass Upsample(nn.Module):\n \"\"\" nn.Upsample is deprecated \"\"\"\n\n def __init__(self, scale_factor, mode=\"nearest\"):\n super(Upsample, self).__init__()\n self.scale_factor = scale_factor\n self.mode = mode\n\n def forward(self, x):\n x = F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode)\n return x\n\n\nclass EmptyLayer(nn.Module):\n \"\"\"Placeholder for 'route' and 'shortcut' layers\"\"\"\n\n def __init__(self):\n super(EmptyLayer, self).__init__()\n\n\nclass YOLOLayer(nn.Module):\n \"\"\"Detection layer\"\"\"\n\n def __init__(self, anchors, num_classes, img_dim=416):\n super(YOLOLayer, self).__init__()\n self.anchors = anchors\n self.num_anchors = len(anchors)\n self.num_classes = num_classes\n self.ignore_thres = 0.5\n self.mse_loss = nn.MSELoss()\n self.bce_loss = nn.BCELoss()\n self.obj_scale = 1\n self.noobj_scale = 100\n self.metrics = {}\n self.img_dim = img_dim\n self.grid_size = 0 # grid size\n\n def compute_grid_offsets(self, grid_size, cuda=True):\n self.grid_size = grid_size\n g = self.grid_size\n FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n self.stride = self.img_dim / self.grid_size # for yolo tinyr, self.stride = 16 or 32 \n # Calculate offsets for each grid\n self.grid_x = torch.arange(g).repeat(g, 1).view([1, 1, g, g]).type(FloatTensor)\n self.grid_y = torch.arange(g).repeat(g, 1).t().view([1, 1, g, g]).type(FloatTensor)\n self.scaled_anchors = FloatTensor([(a_w / self.stride, a_h / self.stride) for a_w, a_h in self.anchors])\n self.anchor_w = self.scaled_anchors[:, 0:1].view((1, self.num_anchors, 1, 1))\n self.anchor_h = self.scaled_anchors[:, 1:2].view((1, self.num_anchors, 1, 1))\n\n\n def forward(self, x, targets=None, img_dim=None):\n\n # Tensors for cuda support\n FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor\n LongTensor = torch.cuda.LongTensor if x.is_cuda else torch.LongTensor\n ByteTensor = torch.cuda.ByteTensor if x.is_cuda else torch.ByteTensor\n\n self.img_dim = img_dim\n num_samples = x.size(0)\n grid_size = x.size(2) # grid_size could change due to multi-scale training\n\n # x is with shape (batch_size, num_anchors*(number_classes+5), grid_size, grid_size)\n prediction = (\n x.view(num_samples, self.num_anchors, self.num_classes + 5, grid_size, grid_size)\n .permute(0, 1, 3, 4, 2)\n .contiguous()\n )\n\n # Get outputs\n x = torch.sigmoid(prediction[..., 0]) # Center x\n y = torch.sigmoid(prediction[..., 1]) # Center y\n w = prediction[..., 2] # Width\n h = prediction[..., 3] # Height\n pred_conf = torch.sigmoid(prediction[..., 4]) # Conf\n pred_cls = torch.sigmoid(prediction[..., 5:]) # Cls pred.\n\n # If grid size does not match current we compute new offsets\n if grid_size != self.grid_size:\n self.compute_grid_offsets(grid_size, cuda=x.is_cuda)\n\n # Add offset and scale with anchors\n pred_boxes = FloatTensor(prediction[..., :4].shape)\n pred_boxes[..., 0] = x.data + self.grid_x\n pred_boxes[..., 1] = y.data + self.grid_y\n pred_boxes[..., 2] = torch.exp(w.data) * self.anchor_w\n pred_boxes[..., 3] = torch.exp(h.data) * self.anchor_h\n\n output = torch.cat(\n (\n pred_boxes.view(num_samples, -1, 4) * self.stride,\n pred_conf.view(num_samples, -1, 1),\n pred_cls.view(num_samples, -1, self.num_classes),\n ),\n -1,\n ) # output the absolute position in 416*416\n\n if targets is None:\n return output, 0\n else:\n iou_scores, class_mask, obj_mask, noobj_mask, tx, ty, tw, th, tcls, tconf = build_targets(\n pred_boxes=pred_boxes, # e.g. shape (32,3,13,13,4)\n pred_cls=pred_cls, # e.g. shape(32,3,13,13,12)\n target=targets, # e.g. shape(107,6)\n anchors=self.scaled_anchors,\n ignore_thres=self.ignore_thres\n )\n\n obj_mask = obj_mask.bool()\n noobj_mask=noobj_mask.bool()\n \n # Loss : Mask outputs to ignore non-existing objects (except with conf. loss)\n loss_x = self.mse_loss(x[obj_mask], tx[obj_mask])\n loss_y = self.mse_loss(y[obj_mask], ty[obj_mask])\n loss_w = self.mse_loss(w[obj_mask], tw[obj_mask])\n loss_h = self.mse_loss(h[obj_mask], th[obj_mask])\n loss_conf_obj = self.bce_loss(pred_conf[obj_mask], tconf[obj_mask])\n loss_conf_noobj = self.bce_loss(pred_conf[noobj_mask], tconf[noobj_mask])\n loss_conf = self.obj_scale * loss_conf_obj + self.noobj_scale * loss_conf_noobj\n loss_cls = self.bce_loss(pred_cls[obj_mask], tcls[obj_mask])\n total_loss = loss_x + loss_y + loss_w + loss_h + loss_conf + loss_cls\n\n # Metrics\n cls_acc = 100 * class_mask[obj_mask].mean()\n conf_obj = pred_conf[obj_mask].mean()\n conf_noobj = pred_conf[noobj_mask].mean()\n conf50 = (pred_conf > 0.5).float()\n iou50 = (iou_scores > 0.5).float()\n iou75 = (iou_scores > 0.75).float()\n detected_mask = conf50 * class_mask * tconf\n precision = torch.sum(iou50 * detected_mask) / (conf50.sum() + 1e-16)\n recall50 = torch.sum(iou50 * detected_mask) / (obj_mask.sum() + 1e-16)\n recall75 = torch.sum(iou75 * detected_mask) / (obj_mask.sum() + 1e-16)\n\n self.metrics = {\n \"loss\": to_cpu(total_loss).item(),\n \"x\": to_cpu(loss_x).item(),\n \"y\": to_cpu(loss_y).item(),\n \"w\": to_cpu(loss_w).item(),\n \"h\": to_cpu(loss_h).item(),\n \"conf\": to_cpu(loss_conf).item(),\n \"cls\": to_cpu(loss_cls).item(),\n \"cls_acc\": to_cpu(cls_acc).item(),\n \"recall50\": to_cpu(recall50).item(),\n \"recall75\": to_cpu(recall75).item(),\n \"precision\": to_cpu(precision).item(),\n \"conf_obj\": to_cpu(conf_obj).item(),\n \"conf_noobj\": to_cpu(conf_noobj).item(),\n \"grid_size\": grid_size,\n }\n\n return output, total_loss\n\n\nclass Darknet(nn.Module):\n \"\"\"YOLOv3 object detection model\"\"\"\n\n def __init__(self, config_path, img_size=416):\n super(Darknet, self).__init__()\n self.module_defs = parse_model_config(config_path)\n self.hyperparams, self.module_list = create_modules(self.module_defs)\n self.yolo_layers = [layer[0] for layer in self.module_list if hasattr(layer[0], \"metrics\")]\n self.img_size = img_size\n self.seen = 0\n self.header_info = np.array([0, 0, 0, self.seen, 0], dtype=np.int32)\n\n def forward(self, x, targets=None):\n img_dim = x.shape[2]\n loss = 0\n layer_outputs, yolo_outputs = [], []\n for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)):\n if module_def[\"type\"] in [\"convolutional\", \"upsample\", \"maxpool\"]:\n x = module(x)\n if list(module.named_children())[0][0] == \"conv_8\":\n self.featuremap = x.detach()\n elif module_def[\"type\"] == \"route\":\n x = torch.cat([layer_outputs[int(layer_i)] for layer_i in module_def[\"layers\"].split(\",\")], 1)\n elif module_def[\"type\"] == \"shortcut\":\n layer_i = int(module_def[\"from\"])\n x = layer_outputs[-1] + layer_outputs[layer_i]\n elif module_def[\"type\"] == \"yolo\":\n x, layer_loss = module[0](x, targets, img_dim)\n loss += layer_loss\n yolo_outputs.append(x)\n layer_outputs.append(x)\n yolo_outputs = torch.cat(yolo_outputs, 1).detach()\n return (self.featuremap, yolo_outputs) if targets is None else (loss, self.featuremap, yolo_outputs)\n\n def load_darknet_weights(self, weights_path):\n \"\"\"Parses and loads the weights stored in 'weights_path'\"\"\"\n\n # Open the weights file\n with open(weights_path, \"rb\") as f:\n header = np.fromfile(f, dtype=np.int32, count=5) # First five are header values\n self.header_info = header # Needed to write header when saving weights\n self.seen = header[3] # number of images seen during training\n weights = np.fromfile(f, dtype=np.float32) # The rest are weights\n\n # Establish cutoff for loading backbone weights\n cutoff = None\n if \"darknet53.conv.74\" in weights_path:\n cutoff = 75\n if \"yolov3-tiny.conv.15\" in weights_path:\n cutoff = 15\n\n # print(self.module_defs)\n # print(\"\\n\", self.module_list)\n ptr = 0\n for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)):\n if i == cutoff:\n break\n if module_def[\"type\"] == \"convolutional\":\n conv_layer = module[0]\n if module_def[\"batch_normalize\"]:\n # Load BN bias, weights, running mean and running variance\n bn_layer = module[1]\n num_b = bn_layer.bias.numel() # Number of biases\n # Bias\n bn_b = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.bias)\n bn_layer.bias.data.copy_(bn_b)\n ptr += num_b\n # Weight\n bn_w = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.weight)\n bn_layer.weight.data.copy_(bn_w)\n ptr += num_b\n # Running Mean\n bn_rm = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.running_mean)\n bn_layer.running_mean.data.copy_(bn_rm)\n ptr += num_b\n # Running Var\n bn_rv = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.running_var)\n bn_layer.running_var.data.copy_(bn_rv)\n ptr += num_b\n else:\n # Load conv. bias\n num_b = conv_layer.bias.numel()\n conv_b = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(conv_layer.bias)\n conv_layer.bias.data.copy_(conv_b)\n ptr += num_b\n # Load conv. weights\n num_w = conv_layer.weight.numel()\n conv_w = torch.from_numpy(weights[ptr : ptr + num_w]).view_as(conv_layer.weight)\n conv_layer.weight.data.copy_(conv_w)\n ptr += num_w\n\n def save_darknet_weights(self, path, cutoff=-1):\n \"\"\"\n @:param path - path of the new weights file\n @:param cutoff - save layers between 0 and cutoff (cutoff = -1 -> all are saved)\n \"\"\"\n fp = open(path, \"wb\")\n self.header_info[3] = self.seen\n self.header_info.tofile(fp)\n\n # Iterate through layers\n for i, (module_def, module) in enumerate(zip(self.module_defs[:cutoff], self.module_list[:cutoff])):\n if module_def[\"type\"] == \"convolutional\":\n conv_layer = module[0]\n # If batch norm, load bn first\n if module_def[\"batch_normalize\"]:\n bn_layer = module[1]\n bn_layer.bias.data.cpu().numpy().tofile(fp)\n bn_layer.weight.data.cpu().numpy().tofile(fp)\n bn_layer.running_mean.data.cpu().numpy().tofile(fp)\n bn_layer.running_var.data.cpu().numpy().tofile(fp)\n # Load conv bias\n else:\n conv_layer.bias.data.cpu().numpy().tofile(fp)\n # Load conv weights\n conv_layer.weight.data.cpu().numpy().tofile(fp)\n\n fp.close()\n",
"from __future__ import division\n\nfrom yolov3.models import *\nfrom utils.utils import *\nfrom utils.datasets import *\nfrom utils.parse_config import *\n\nimport os\nimport sys\nimport time\nimport datetime\nimport argparse\nimport tqdm\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torch.autograd import Variable\nimport torch.optim as optim\n\n\ndef evaluate(model, mode, iou_thres, conf_thres, nms_thres, img_size, batch_size):\n \"\"\"\n params\n ---\n - model, mode, iou_thres, conf_thres, nms_thres, img_size, batch_size\n\n return\n ---\n - precision, recall, AP, f1, ap_class, box_stat, pr_curve\n \"\"\"\n model.eval()\n\n # Get dataloader\n dataset = ExDarkDataset(mode, coco_detector = False, augment=False, multiscale=False)\n dataloader = torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=32,\n collate_fn=dataset.collate_fn\n )\n\n Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\n labels = [] \n sample_metrics = [] # List of tuples (TP, confs, pred)\n box_stat = dict(before = [], after = [])\n\n for batch_i, (_, imgs, targets) in enumerate(\n tqdm.tqdm(dataloader, desc=\"Detecting objects\")\n ):\n\n # Extract class labels\n labels += targets[:, 1].tolist()\n # Rescale target\n targets[:, 2:] = xywh2xyxy(targets[:, 2:])\n targets[:, 2:] *= img_size\n\n imgs = Variable(imgs.type(Tensor), requires_grad=False)\n\n with torch.no_grad():\n _, outputs = model(imgs)\n outputs = outputs.to(torch.device(\"cpu\"))\n\n # boxes amount before NMS\n for image_pred in outputs:\n box_stat[\"before\"].append(len(image_pred[image_pred[:, 4] >= conf_thres]))\n \n # NMS\n outputs = non_max_suppression_cpp(\n outputs, conf_thresh=conf_thres, nms_thresh=nms_thres\n )\n for i, output in enumerate(outputs):\n if output is not None:\n outputs[i] = output[:, :7]\n\n # boxes amount after NMS\n for image_pred in outputs:\n box_stat[\"after\"].append(len(image_pred) if not image_pred==None else 0)\n\n sample_metrics += get_batch_statistics(\n outputs, targets, iou_threshold=iou_thres\n )\n\n # Concatenate sample statistics\n if sample_metrics == []:\n true_positives, pred_scores, pred_labels, labels = np.array([0]), np.array([1]), np.array([1]), np.array([1])\n else:\n true_positives, pred_scores, pred_labels = [\n np.concatenate(x, 0) for x in list(zip(*sample_metrics))\n ]\n precision, recall, AP, f1, ap_class, pr_curve = ap_per_class(\n true_positives, pred_scores, pred_labels, labels\n )\n\n return precision, recall, AP, f1, ap_class, box_stat, pr_curve\n\n\n\n\n'''\nYolo trained on COCO, test on Exdark\n'''\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--batch_size\", type=int, \n default=32, help=\"size of each image batch\"\n )\n parser.add_argument(\n \"--model_def\", type=str,\n default=\"config/yolov3-tiny-12.cfg\", help=\"path to model definition file\",\n )\n parser.add_argument(\n \"--weights_path\", type=str,\n default=\"weights/best_mixed.pt\", help=\"path to weights file\",\n )\n parser.add_argument(\n \"--classes_path\", type=str,\n default=\"config/exdark.names\", help=\"path to class label file\",\n )\n parser.add_argument(\n \"--iou_thres\", type=float,\n default=0.5, help=\"iou threshold required to qualify as detected\",\n )\n parser.add_argument(\n \"--conf_thres\", type=float, \n default=0.01, help=\"object confidence threshold\"\n )\n parser.add_argument(\n \"--nms_thres\", type=float,\n default=0.5, help=\"iou thresshold for non-maximum suppression\",\n )\n parser.add_argument(\n \"--img_size\", type=int, \n default=416, help=\"size of each image dimension\"\n )\n opt = parser.parse_args()\n print(opt)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Initiate model\n model = Darknet(opt.model_def).to(device)\n if opt.weights_path.endswith(\".weights\"):\n # Load darknet weights\n model.load_darknet_weights(opt.weights_path)\n elif opt.weights_path.endswith(\".pt\"):\n # load ultralytics yolov3 weights\n param = torch.load(opt.weights_path)[\"model\"] # param: a collections.OrderedDict\n module_list = model.state_dict() # module_list: a collections.OrderedDict\n para_name = list(param)\n for i, name in enumerate(module_list):\n module_list[name] = param[para_name[i]]\n model.load_state_dict(module_list)\n else:\n # Load checkpoint weights\n model.load_state_dict(torch.load(opt.weights_path))\n\n print(\"Compute mAP...\")\n\n precision, recall, ap, f1, ap_class, box_stat, pr_curve = evaluate(\n model,\n mode = \"test\",\n iou_thres = opt.iou_thres,\n conf_thres = opt.conf_thres,\n nms_thres = opt.nms_thres,\n img_size = opt.img_size,\n batch_size = opt.batch_size,\n )\n\n # draw figures\n print(f\"img_number: {len(box_stat['after'])}, sample_number: {len(pr_curve[0])}\")\n before, after = np.array(box_stat[\"before\"]), np.array(box_stat[\"after\"])\n p, r, conf = np.array(pr_curve)\n\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n mpl.rcParams['font.size'] = 20\n mpl.rcParams['figure.titlesize'] = 'medium'\n plt.figure(figsize=(10,5))\n plt.subplot(111)\n plt.plot(r,p,lw=3)\n plt.title('P-R Curve')\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.xlim((0, 1))\n plt.ylim((0, 1))\n\n plt.tight_layout()\n os.makedirs(\"plot\", exist_ok=True)\n plt.savefig(f\"plot/yolo_mixed/{opt.iou_thres}_{opt.conf_thres}.jpg\")\n plt.close()\n\n\n # print info\n ExDark_mAP = 0\n choosen_class = [*range(12)] # indices of chosen ExDark classes in coco.names \n class_names = load_classes(opt.classes_path) # coco class names \n for i, c in enumerate(ap_class):\n if c in choosen_class:\n print(f\"+ Class {c} ({class_names[c]})\".ljust(30) + f\"-AP: {ap[i]:.3f} -Precision:{precision[i]:.3f} -Recall:{recall[i]:.3f}\")\n ExDark_mAP += ap[i]\n else:\n print(f\"- Class {c} ({class_names[c]})\".ljust(30) + f\"-AP: {ap[i]:.3f} -Precision:{precision[i]:.3f} -Recall:{recall[i]:.3f}\")\n print(f\"mAP_chosen classes:{ExDark_mAP/len(choosen_class)}\")\n print(f\"mAP_all classes: {ap.mean()}\") # mAP on classes included in annotations. Go to datasets.py to modify.\n"
] |
[
[
"torch.nn.Sequential",
"torch.sigmoid",
"numpy.fromfile",
"torch.cat",
"torch.nn.ModuleList",
"torch.sum",
"torch.from_numpy",
"torch.arange",
"torch.nn.BCELoss",
"torch.exp",
"torch.nn.LeakyReLU",
"torch.nn.functional.interpolate",
"torch.nn.BatchNorm2d",
"torch.nn.ZeroPad2d",
"numpy.array",
"torch.nn.MSELoss"
],
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"torch.load",
"matplotlib.pyplot.ylim",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"torch.no_grad",
"matplotlib.pyplot.close",
"torch.cuda.is_available",
"torch.device",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure"
]
] |
zhangw106/FlamePyrometry
|
[
"8f0a9473e54bb4a898effc5bb310b8700e6dd9ad"
] |
[
"ExaminationTIF.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nA useful tool to examine a series of raw2tif images for the FlamePyrometry code.\r\nFor more information on the FlamePyrometry code, please see [https://doi.org/10.1364/AO.58.002662].\r\n\r\nThe inverse Abel transformation is very sensitive to the symmetry of flame and the uniformity of stacked images.\r\nThus, this code was developed to examine a series of raw2tif images from BlackflyS camera.\r\nSeveral flame images with similar flame shape can be selected for further processing in FlamePyrometry code.\r\n\r\nNote that several lines of this code are copied and modified from the original FlamePyrometry code.\r\n\r\nThe raw images from BlackflyS camera can be converted to Tif format images using ImageJ.\r\nThe Tif images need to be renamed as \"0, 1, 2, 3...\" using some kind of renamed tool, which can be found in the Internet.\r\nIn addition, these Tif images must be placed in \"//Photos//Examination//Input//\" folder.\r\n\r\nThen, variable \"img_number\" need to be changed by the number of these images. \r\nNote that the positions of HAB0 and flame tip, and flame width must be given.\r\n\r\nFor each image, the standard deviation of the detected centre points (i.e., line), \r\nand the position of flame tip can be saved in csv format in \"//Photos//Examination//\".\r\nThe demosaicing image of flame, and the R, G, and B channels of this image can also be saved.\r\n\r\nThe code can also save tecplor format files for all frames that stores the Red, Green and Blue channel of the flame image. \r\nNote that each tecplot file (*.dat) may be very large.\r\nIf you don't want to save the tecplot file, just change the save_tecplot to 'False'.\r\n\r\nCreated on Sat Jun 26, 2021\r\n\r\n@ zhangw106\r\n@ zhangw106@tju.edu.cn\r\n\"\"\"\r\n\r\nfrom skimage import io, exposure\r\nimport numpy as np\r\nfrom os.path import abspath\r\nfrom scipy import ndimage\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport gc\r\n\r\n# Number of images for examination\r\nimg_number = 3\r\n\r\n# mm for each pixel of flame images\r\npixelmm = 1/38.5\r\n\r\n# Save tecplot file. 'True' or 'False'\r\nsave_tecplot = True\r\n\r\n# Parameters defining position of flame and cropped image size. \r\n# Please use an uneven integer for flame_width.\r\nHAB0 = 3634 # 1614 for '100H_BG7_exp1563'\r\nHAB_tip = 1800 # 114 for '100H_BG7_exp1563'\r\nflame_width = 501 # 401 for '100H_BG7_exp1563'\r\nflame_height = HAB0 - HAB_tip\r\n\r\n# It is possible to slightly rotate tilded flame images\r\ndegree = 0\r\n\r\n# Threshold for the tip detection\r\nthresh_grn = 2000\r\n\r\n# Max. intensity count of the camera\r\nscale = 65535\r\n\r\n# Two arrows to save middle_std and tip for each frame\r\n# Another arrow to save both the middle_std and tip\r\nmiddle_std = np.zeros(img_number) \r\ntip = np.zeros(img_number)\r\ntif_exam = np.zeros((img_number, 3))\r\n\r\nfor k in range(0, img_number, 1):\r\n filename = k\r\n fname = abspath( '{0}{1}{2}'.format('Photos//Examination//Input//', filename, '.tif') )\r\n\r\n ImDatBayer = io.imread(fname) # Row*Column = 2048*1536\r\n\r\n ImDat = np.zeros(((len(ImDatBayer), len(ImDatBayer[0]), 3) ) ) # 2048*1536*3\r\n\r\n # Demosaic the image. COLOR_BayerGB2RGB, COLOR_BayerGB2RGB_EA, COLOR_BayerGB2RGB_VNG. \r\n ImDat = ndimage.rotate((cv2.cvtColor(ImDatBayer, cv2.COLOR_BayerGB2RGB_EA)), degree, reshape=False)\r\n\r\n # It is possible to adjust the lightness of color image.\r\n Img_color = exposure.adjust_gamma(ImDat, 1) # <1 means brighter, >1 means darker\r\n\r\n del ImDatBayer\r\n\r\n ImDatRed = ImDat[:,:,0] # 2048*1536\r\n ImDatGrn = ImDat[:,:,1] # 2048*1536\r\n ImDatBlu = ImDat[:,:,2] # 2048*1536\r\n \r\n left = np.zeros([len(ImDatGrn)], dtype=int) # 2048\r\n right = np.zeros([len(ImDatGrn)], dtype=int) # 2048\r\n middle = np.zeros([len(ImDatGrn)]) # 2048\r\n\r\n # Find left and right flame edge to calculate the flame centre at different pixel rows\r\n gray = cv2.cvtColor(np.uint8(ImDat/scale*255), cv2.COLOR_RGB2GRAY) # 2048*1536 \r\n th_gray = cv2.adaptiveThreshold(gray,1,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\\\r\n cv2.THRESH_BINARY,85,6) # 2048*1536 \r\n\r\n for i in range(0,len(ImDatGrn)):\r\n left[i] = np.argmax(th_gray[i,:]<0.5)\r\n right[i] = len(ImDatGrn[0]) - np.argmax(np.flip(th_gray[i,:],0)<0.5)- 1\r\n\r\n # Remove the noisy top and bottom part of the flame \r\n left[0:np.argmax(left[:]>0)+20] = 0\r\n left[len(left) - np.argmax(np.flip(left[:])>0)-50:-1] = 0\r\n\r\n middle = (left + right)/2 * (left!=0) * (right!=len(ImDatGrn[0])-1)\r\n middle_std[k] = np.std(middle[middle!=0]) \r\n\r\n # Find the flame tip at flame centre\r\n tip[k] = np.argmax(ImDatGrn[:,int(round(np.mean(middle[np.nonzero(middle)])))]>thresh_grn)\r\n\r\n del ImDat, left, right, gray, th_gray,\r\n \r\n # Save img_number, middle_std and tip in the exam_tif arrow\r\n tif_exam[k,0] = k\r\n tif_exam[k,1] = middle_std[k]\r\n tif_exam[k,2] = tip[k]\r\n\r\n #-----------------------------------------------------\r\n # Crop the flame image to desired size\r\n #-----------------------------------------------------\r\n middle_ave = int(np.average(middle[middle!=0]))\r\n Img_color_crop = Img_color[(HAB0 - flame_height) : HAB0, int(middle_ave - flame_width/2) : int(middle_ave + flame_width/2), :]\r\n ImDatRed_crop = ImDatRed[(HAB0 - flame_height) : HAB0, int(middle_ave - flame_width/2) : int(middle_ave + flame_width/2)]\r\n ImDatGrn_crop = ImDatGrn[(HAB0 - flame_height) : HAB0, int(middle_ave - flame_width/2) : int(middle_ave + flame_width/2)]\r\n ImDatBlu_crop = ImDatBlu[(HAB0 - flame_height) : HAB0, int(middle_ave - flame_width/2) : int(middle_ave + flame_width/2)]\r\n \r\n del middle, Img_color, ImDatRed, ImDatGrn, ImDatBlu\r\n\r\n ImDatRG = ImDatRed_crop / ImDatGrn_crop\r\n ImDatRB = ImDatRed_crop / ImDatBlu_crop\r\n ImDatBG = ImDatBlu_crop / ImDatGrn_crop\r\n \r\n # Save the debayer color image and the R G B images\r\n plt.figure()\r\n plt.title('Color image') \r\n \r\n plt.subplot(221)\r\n plt.axis('off') # Hide both the x and y axises\r\n plt.imshow(Img_color_crop/scale, vmin=0, vmax=scale)\r\n plt.title('Color')\r\n \r\n plt.subplot(222)\r\n plt.axis('off') \r\n plt.imshow(ImDatRed_crop, vmin=0, vmax=scale)\r\n plt.title('Red')\r\n \r\n plt.subplot(223)\r\n plt.axis('off') \r\n plt.imshow(ImDatGrn_crop, vmin=0, vmax=scale)\r\n plt.title('Green')\r\n \r\n plt.subplot(224)\r\n plt.axis('off') \r\n plt.imshow(ImDatBlu_crop, vmin=0, vmax=scale)\r\n plt.title('Blue')\r\n \r\n plt.subplots_adjust(hspace=None, wspace=-0.7)\r\n \r\n # Path to save the figure, and save it.\r\n fsave_color = abspath( '{0}{1}{2}'.format('Photos//Examination//Color_image-', str(k), '.png') )\r\n plt.savefig(fsave_color, bbox_inches='tight', dpi=500)\r\n\r\n #plt.draw()\r\n #plt.pause(3) # Figure will show for 5 seconds\r\n #plt.cla() # Clear axis\r\n #plt.clf() # clear figure\r\n plt.close() # close figure\r\n\r\n #-----------------------------------------------------\r\n # Save Red, Green and Blue channels in tecplot format\r\n #-----------------------------------------------------\r\n if save_tecplot == True:\r\n # Get the shape of ImDatRed_crop\r\n m = len(ImDatRed_crop) # Row\r\n n = len(ImDatRed_crop[0]) # Column\r\n tecplot = np.zeros((m*n, 5)) # Creat a matrix\r\n\r\n for i in range(0, m): # Searching each row\r\n for j in range(0, n): # Searching each column\r\n tecplot[i*n+j, 0] = (j-(n-1)/2)*pixelmm/10 # Set the middle pixel as r=0 cm\r\n tecplot[i*n+j, 1] = (m-i)*pixelmm/10 # Flip the image, cm\r\n tecplot[i*n+j, 2] = ImDatRed_crop[i,j]\r\n tecplot[i*n+j, 3] = ImDatGrn_crop[i,j]\r\n tecplot[i*n+j, 4] = ImDatBlu_crop[i,j]\r\n\r\n header_str = ('{0}{1}{2}{3}{4}{5}{6}{7}{8}'.format(' TITLE = \"Flame-', str(filename), '\" \\n VARIABLES = \"r (cm)\", \"HAB (cm)\", \"Red\", \"Green\", \"Blue\" \\n ZONE T = \"Flame-', str(filename), '\", I = ', str(n),', J = ', str(m), ', F = POINT'))\r\n \r\n ImPathtecplot = ('{0}{1}{2}{3}'.format('Photos//Examination//', 'Color_channel_', filename, '-tecplot.dat'))\r\n \r\n np.savetxt(ImPathtecplot, tecplot, delimiter=' ', header= header_str, comments='')\r\n\r\n del tecplot\r\n\r\n print('{0}{1}{2}'.format('Frame ', str(k), ' have been examined.'))\r\n\r\n del Img_color_crop, ImDatRed_crop, ImDatGrn_crop, ImDatBlu_crop\r\n \r\n # Release Ram\r\n gc.collect() # Release Ram\r\n\r\n#-----------------------------------------------------\r\n# Save data of flame centre and tip for all frames\r\n#-----------------------------------------------------\r\nheader_str = ('NO.,STD,Tip')\r\npath_exam = ('Photos/Examination/0_Flame_centre_and_tip.csv')\r\nnp.savetxt(path_exam, tif_exam, fmt='%3d,%1.3f,%4d', header= header_str, comments='')\r\nprint('Flame centre and tip detection finished.')\r\n\r\n#-----------------------------------------------------\r\n# Show figure of flame centre and tip, and save it\r\n#-----------------------------------------------------\r\nplt.figure()\r\nplt.title('Centre standard deviation')\r\nplt.xlabel(\"Image number\")\r\nplt.ylabel(\"Standard deviation\")\r\nplt.plot(middle_std, '*b')\r\nplt.savefig('./Photos/Examination/1_Flame_centre.png', bbox_inches='tight', dpi=500)\r\nif img_number != 1:\r\n plt.draw()\r\n plt.pause(3) # Figure will show for 3 seconds\r\nplt.close() # Close figure and continue\r\nprint('Flame centre standard deviation saved.')\r\n\r\nplt.figure()\r\nplt.title('Flame tip')\r\nplt.xlabel(\"Image number\")\r\nplt.ylabel(\"Flame tip\")\r\nplt.plot(tip, 'xr')\r\nplt.savefig('./Photos/Examination/2_Flame_tip.png', bbox_inches='tight', dpi=500)\r\nif img_number != 1:\r\n plt.draw()\r\n plt.pause(3) # Figure will show for 3 seconds\r\nplt.close() # Close figure and continue\r\nprint('Flame tip saved.')"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.plot",
"numpy.uint8",
"numpy.std",
"matplotlib.pyplot.subplot",
"numpy.argmax",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.axis",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.nonzero",
"matplotlib.pyplot.savefig",
"numpy.savetxt",
"numpy.flip",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.xlabel",
"numpy.average",
"matplotlib.pyplot.pause"
]
] |
bankbiz/image-matching-benchmark
|
[
"c314f067b2d7337b9e7de0875214bdbab9750afc"
] |
[
"methods/feature_matching/nn.py"
] |
[
"# Copyright 2020 Google LLC, University of Victoria, Czech Technical University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport cv2\nimport numpy as np\nfrom copy import deepcopy\nfrom time import time\nfrom utils.match_helper import get_matching_dist_type, remove_duplicate_matches\nWITH_FAISS = False\ntry:\n import faiss\n WITH_FAISS = True\nexcept:\n pass\n\ndef match(desc1, desc2, cfg, kps1=None, kps2=None):\n ''' Computes and returns matches with the ratio test\n\n param desc1: descriptors of the first image\n param desc2: descriptors of the second image\n param cfg: Configuration\n\n return matches: np.ndarray with match indices\n '''\n\n # Parse options\n cur_key = 'config_{}_{}'.format(cfg.dataset, cfg.task)\n method_match = cfg.method_dict[cur_key]['matcher']\n filter_type = method_match['filtering']['type'].lower()\n\n # Ratio test threshold\n if filter_type.lower() in [\n 'snn_ratio_pairwise', 'snn_ratio_vs_last', 'fginn_ratio_pairwise'\n ]:\n ratio_th = method_match['filtering']['threshold']\n if ratio_th < 0.1 or ratio_th > 1.01:\n raise ValueError('Ratio test threshold outside expected range')\n\n # FGINN spatial threshold\n if filter_type in ['fginn_ratio_pairwise']:\n fginn_spatial_th = method_match['filtering']['fginn_radius']\n if fginn_spatial_th < 0 or fginn_spatial_th > 500:\n raise ValueError('FGINN radius outside expected range')\n\n # Distance threshold\n max_dist = None\n if 'descriptor_distance_filter' in method_match:\n max_dist = method_match['descriptor_distance_filter']['threshold']\n\n # Skip this if there are no features\n if desc1.shape[0] == 0 or desc2.shape[0] == 0:\n return np.empty((2, 0)), 0\n\n # Reformat descriptors according to the distance type\n dist = get_matching_dist_type(cfg)\n if method_match['distance'].lower() == 'hamming':\n desc1 = desc1.astype(np.uint8)\n desc2 = desc2.astype(np.uint8)\n elif method_match['distance'].lower() in ['l1', 'l2']:\n desc1 = desc1.astype(np.float32)\n desc2 = desc2.astype(np.float32)\n else:\n raise ValueError('Unknown distance type')\n\n t_start = time()\n\n # Use opencv BF/FLANN matcher\n do_flann = method_match['flann']\n\n if do_flann:\n if dist == cv2.NORM_L2:\n FLANN_INDEX_KDTREE = 1 # FLANN_INDEX_KDTREE\n elif dist == cv2.NORM_HAMMING:\n FLANN_INDEX_KDTREE = 5 # FLANN_INDEX_HIERARCHICAL\n else:\n FLANN_INDEX_KDTREE = 0 # FLANN_INDEX_LINEAR\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=4)\n search_params = dict(checks=128) # or pass empty dictionary\n bf = cv2.FlannBasedMatcher(index_params, search_params)\n else:\n bf = cv2.BFMatcher(dist, crossCheck=False)\n\n # Matching\n num_nn = method_match['num_nn']\n try:\n if WITH_FAISS and dist == cv2.NORM_L2:\n #print (\"FAISS\")\n dbsize, dim = desc2.shape\n res = faiss.StandardGpuResources() # use a single GPU\n index_flat = faiss.IndexFlatL2(dim) # build a flat (CPU) index\n nn = faiss.index_cpu_to_gpu(res, 0, index_flat)\n nn.add(desc2) # add vectors to the index\n if 'fginn' in filter_type:\n k = 10 + num_nn\n else:\n k=max(2, num_nn + 1)\n dists,idx = nn.search(desc1, k)\n matches = []\n #print (dists.shape)\n for query_idx, (dd, ii) in enumerate(zip(dists, idx)):\n cur_match = []\n for db_idx, m_dist in zip(ii,dd):\n cur_match.append(cv2.DMatch(query_idx, db_idx, m_dist))\n matches.append(cur_match)\n else:\n if 'fginn' in filter_type:\n matches = bf.knnMatch(desc1, desc2, k=10 + num_nn)\n else:\n matches = bf.knnMatch(desc1, desc2, k=max(2, num_nn + 1))\n except:\n print (\"FAISS crashed, fallback to opnecv\")\n if 'fginn' in filter_type:\n matches = bf.knnMatch(desc1, desc2, k=10 + num_nn)\n else:\n matches = bf.knnMatch(desc1, desc2, k=max(2, num_nn + 1))\n # Apply filtering (ratio test or something else)\n valid_matches = []\n\n if filter_type == 'none':\n for cur_match in matches:\n tmp_valid_matches = [nn_1 for nn_1 in cur_match[:-1]]\n valid_matches.extend(tmp_valid_matches)\n elif filter_type == 'snn_ratio_pairwise':\n for cur_match in matches:\n tmp_valid_matches = [\n nn_1 for nn_1, nn_2 in zip(cur_match[:-1], cur_match[1:])\n if nn_1.distance <= ratio_th * nn_2.distance\n ]\n valid_matches.extend(tmp_valid_matches)\n elif filter_type == 'snn_ratio_vs_last':\n for cur_match in matches:\n nn_n = cur_match[-1]\n tmp_valid_matches = [\n nn_i for nn_i in cur_match[:-1]\n if nn_i.distance <= ratio_th * nn_n.distance\n ]\n valid_matches.extend(tmp_valid_matches)\n elif filter_type == 'fginn_ratio_pairwise':\n flann = cv2.BFMatcher(cv2.NORM_L2, crossCheck=False)\n not_fginns = flann.radiusMatch(kps2.astype(np.float32),\n kps2.astype(np.float32),\n fginn_spatial_th)\n for m_idx, cur_match in enumerate(matches):\n for mii in range(num_nn):\n cur_non_fginns = [\n x.trainIdx for x in not_fginns[cur_match[mii].trainIdx]\n ]\n for nn_2 in cur_match[mii + 1:]:\n if cur_match[mii].distance <= ratio_th * nn_2.distance:\n valid_matches.append(cur_match[mii])\n break\n if nn_2.trainIdx not in cur_non_fginns:\n break\n else:\n raise ValueError('Unknown filter type')\n\n # Filter matches by descriptor distance\n if max_dist:\n valid_matches_with_dist = []\n for valid_match in valid_matches:\n if valid_match.distance <= max_dist:\n valid_matches_with_dist.append(valid_match)\n valid_matches = valid_matches_with_dist\n\n # Turn opencv return format into numpy\n matches_list = []\n for m in valid_matches:\n matches_list.append([m.queryIdx, m.trainIdx])\n matches = np.asarray(matches_list).T\n\n # If two-way matching is enabled\n if method_match['symmetric']['enabled']:\n reduce_method = method_match['symmetric']['reduce'].lower()\n\n # Hacky but works: disable symmetric matching and call self\n cfg_temp = deepcopy(cfg)\n cfg_temp.method_dict['config_{}_{}'.format(\n cfg.dataset, cfg.task)]['matcher']['symmetric']['enabled'] = False\n matches_other_direction, ellapsed_other_direction = match(\n desc2, desc1, cfg_temp, kps2, kps1)\n\n if reduce_method == 'any':\n if len(matches.shape) == 2 and \\\n len(matches_other_direction.shape) == 2:\n matches = np.concatenate(\n [matches, matches_other_direction[::-1]], axis=1)\n elif reduce_method == 'both':\n m1 = matches.T\n m2 = matches_other_direction.T\n out = []\n if len(m2) < 2:\n matches = np.zeros((2, 0)).astype(np.int32)\n else:\n for i in range(len(m1)):\n i1, i2 = m1[i]\n mask = m2[:, 0] == i2\n row = m2[mask]\n if len(row) > 0:\n i22, i11 = row[0]\n if (i1 == i11) and (i2 == i22):\n out.append(m1[i].reshape(1, -1))\n if len(out) > 0:\n matches = np.concatenate(out, axis=0).T.astype(np.int32)\n else:\n matches = np.zeros((2, 0)).astype(np.int32)\n else:\n raise ValueError('Unknown symmetrical match reduce ',\n reduce_method)\n else:\n ellapsed_other_direction = 0\n\n # Remove duplicate matches\n matches = remove_duplicate_matches(matches, kps1, kps2)\n\n return matches, time() - t_start + ellapsed_other_direction\n"
] |
[
[
"numpy.asarray",
"numpy.zeros",
"numpy.concatenate",
"numpy.empty"
]
] |
ADMoreau/CapsNet_Keras
|
[
"9aa34b6da7e5528c50f72ecf102c4788df561eeb"
] |
[
"capsulenet-multi-gpu.py"
] |
[
"\"\"\"\nKeras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.\nThe current version maybe only works for TensorFlow backend. Actually it will be straightforward to re-write to TF code.\nAdopting to other backends should be easy, but I have not tested this.\n\nUsage:\n python capsulenet-multi-gpu.py\n python capsulenet-multi-gpu.py --gpus 2\n ... ...\n\nResult:\n About 55 seconds per epoch on two GTX1080Ti GPU cards\n\nAuthor: Xifeng Guo, E-mail: `guoxifeng1990@163.com`, Github: `https://github.com/XifengGuo/CapsNet-Keras`\n\"\"\"\n\nfrom keras import optimizers\nfrom keras import backend as K\n\nK.set_image_data_format('channels_last')\n\nfrom capsulenet import CapsNet, margin_loss, load_mnist, manipulate_latent, test\n\n\ndef train(model, data, args):\n \"\"\"\n Training a CapsuleNet\n :param model: the CapsuleNet model\n :param data: a tuple containing training and testing data, like `((x_train, y_train), (x_test, y_test))`\n :param args: arguments\n :return: The trained model\n \"\"\"\n # unpacking the data\n (x_train, y_train), (x_test, y_test) = data\n\n # callbacks\n log = callbacks.CSVLogger(args.save_dir + '/' + args.subject + '/log.csv')\n tb = callbacks.TensorBoard(log_dir=args.save_dir + '/' + args.subject + '/tensorboard-logs',\n batch_size=args.batch_size, histogram_freq=args.debug)\n lr_decay = callbacks.LearningRateScheduler(schedule=lambda epoch: args.lr * (0.9 ** epoch))\n\n # compile the model\n model.compile(optimizer=optimizers.Adam(lr=args.lr),\n loss=[margin_loss, 'mse'],\n loss_weights=[1., args.lam_recon])\n\n \"\"\"\n # Training without data augmentation:\n model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs,\n validation_data=[[x_test, y_test], [y_test, x_test]], callbacks=[log, tb, checkpoint, lr_decay])\n \"\"\"\n\n # Begin: Training with data augmentation ---------------------------------------------------------------------#\n def train_generator(x, y, batch_size, shift_fraction=0.):\n train_datagen = ImageDataGenerator(width_shift_range=shift_fraction,\n height_shift_range=shift_fraction) # shift up to 2 pixel for MNIST\n generator = train_datagen.flow(x, y, batch_size=batch_size)\n while 1:\n x_batch, y_batch = generator.next()\n yield ([x_batch, y_batch], [y_batch, x_batch])\n\n # Training with data augmentation. If shift_fraction=0., also no augmentation.\n model.fit_generator(generator=train_generator(x_train, y_train, args.batch_size, args.shift_fraction),\n steps_per_epoch=int(y_train.shape[0] / args.batch_size),\n epochs=args.epochs,\n validation_data=[[x_test, y_test], [y_test, x_test]],\n callbacks=[log, tb, lr_decay])\n # End: Training with data augmentation -----------------------------------------------------------------------#\n\n from utils import plot_log\n plot_log(args.save_dir + '/' + args.subject + '/log.csv', show=True)\n\n return model\n\n\nif __name__ == \"__main__\":\n import numpy as np\n import tensorflow as tf\n import os\n from keras.preprocessing.image import ImageDataGenerator\n from keras import callbacks\n from keras.utils.vis_utils import plot_model\n from keras.utils import multi_gpu_model\n\n # setting the hyper parameters\n import argparse\n parser = argparse.ArgumentParser(description=\"Capsule Network on MNIST.\")\n parser.add_argument('--epochs', default=50, type=int)\n parser.add_argument('--batch_size', default=300, type=int)\n parser.add_argument('--lam_recon', default=0.392, type=float,\n help=\"The coefficient for the loss of decoder\")\n parser.add_argument('-r', '--routings', default=3, type=int,\n help=\"Number of iterations used in routing algorithm. should > 0\")\n parser.add_argument('--shift_fraction', default=0.1, type=float,\n help=\"Fraction of pixels to shift at most in each direction.\")\n parser.add_argument('--debug', default=0, type=int,\n help=\"Save weights by TensorBoard\")\n parser.add_argument('--save_dir', default='./result')\n parser.add_argument('-t', '--testing', action='store_true',\n help=\"Test the trained model on testing dataset\")\n parser.add_argument('--digit', default=5, type=int,\n help=\"Digit to manipulate\")\n parser.add_argument('-w', '--weights', default=None,\n help=\"The path of the saved weights. Should be specified when testing\")\n parser.add_argument('--lr', default=0.001, type=float,\n help=\"Initial learning rate\")\n parser.add_argument('--gpus', default=2, type=int)\n args = parser.parse_args()\n print(args)\n if not os.path.exists(args.save_dir + '/' + args.subject):\n os.makedirs(args.save_dir + '/' + args.subject)\n\n # load data\n (x_train, y_train), (x_test, y_test) = utils.load_EEG(args.subject)\n print(\"Data Loaded\")\n\n # define model\n with tf.device('/cpu:0'):\n model, eval_model, manipulate_model = CapsNet(input_shape=x_train.shape[1:],\n n_class=len(np.unique(np.argmax(y_train, 1))),\n routings=args.routings)\n model.summary()\n plot_model(model, to_file=args.save_dir+'/' + args.subject + '/model.png', show_shapes=True)\n\n # train or test\n if args.weights is not None: # init the model weights with provided one\n model.load_weights(args.weights)\n if not args.testing:\n # define muti-gpu model\n multi_model = multi_gpu_model(model, gpus=args.gpus)\n train(model=multi_model, data=((x_train, y_train), (x_test, y_test)), args=args)\n model.save_weights(args.save_dir + '/' + args.subject + '/trained_model.h5')\n print('Trained model saved to \\'%s/trained_model.h5\\'' % args.save_dir)\n test(model=eval_model, data=(x_test, y_test), args=args)\n else: # as long as weights are given, will run testing\n if args.weights is None:\n print('No weights are provided. Will test using random initialized weights.')\n manipulate_latent(manipulate_model, (x_test, y_test), args)\n test(model=eval_model, data=(x_test, y_test), args=args)\n"
] |
[
[
"tensorflow.device",
"numpy.argmax"
]
] |
ami-a/MaskDetection
|
[
"9df329a24a987e63331c17db154319b3ebcaad74"
] |
[
"mask_example/keras_layers/keras_layer_AnchorBoxes.py"
] |
[
"'''\nA custom Keras layer to generate anchor boxes.\n\nCopyright (C) 2018 Pierluigi Ferrari\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\nfrom __future__ import division\nimport numpy as np\nimport keras.backend as K\nfrom keras.engine.topology import InputSpec\nfrom keras.engine.topology import Layer\n\nfrom bounding_box_utils.bounding_box_utils import convert_coordinates\n\nclass AnchorBoxes(Layer):\n '''\n A Keras layer to create an output tensor containing anchor box coordinates\n and variances based on the input tensor and the passed arguments.\n\n A set of 2D anchor boxes of different aspect ratios is created for each spatial unit of\n the input tensor. The number of anchor boxes created per unit depends on the arguments\n `aspect_ratios` and `two_boxes_for_ar1`, in the default case it is 4. The boxes\n are parameterized by the coordinate tuple `(xmin, xmax, ymin, ymax)`.\n\n The logic implemented by this layer is identical to the logic in the module\n `ssd_box_encode_decode_utils.py`.\n\n The purpose of having this layer in the network is to make the model self-sufficient\n at inference time. Since the model is predicting offsets to the anchor boxes\n (rather than predicting absolute box coordinates directly), one needs to know the anchor\n box coordinates in order to construct the final prediction boxes from the predicted offsets.\n If the model's output tensor did not contain the anchor box coordinates, the necessary\n information to convert the predicted offsets back to absolute coordinates would be missing\n in the model output. The reason why it is necessary to predict offsets to the anchor boxes\n rather than to predict absolute box coordinates directly is explained in `README.md`.\n\n Input shape:\n 4D tensor of shape `(batch, channels, height, width)` if `dim_ordering = 'th'`\n or `(batch, height, width, channels)` if `dim_ordering = 'tf'`.\n\n Output shape:\n 5D tensor of shape `(batch, height, width, n_boxes, 8)`. The last axis contains\n the four anchor box coordinates and the four variance values for each box.\n '''\n\n def __init__(self,\n img_height,\n img_width,\n this_scale,\n next_scale,\n aspect_ratios=[0.5, 1.0, 2.0],\n two_boxes_for_ar1=True,\n this_steps=None,\n this_offsets=None,\n clip_boxes=False,\n variances=[0.1, 0.1, 0.2, 0.2],\n coords='centroids',\n normalize_coords=False,\n **kwargs):\n '''\n All arguments need to be set to the same values as in the box encoding process, otherwise the behavior is undefined.\n Some of these arguments are explained in more detail in the documentation of the `SSDBoxEncoder` class.\n\n Arguments:\n img_height (int): The height of the input images.\n img_width (int): The width of the input images.\n this_scale (float): A float in [0, 1], the scaling factor for the size of the generated anchor boxes\n as a fraction of the shorter side of the input image.\n next_scale (float): A float in [0, 1], the next larger scaling factor. Only relevant if\n `self.two_boxes_for_ar1 == True`.\n aspect_ratios (list, optional): The list of aspect ratios for which default boxes are to be\n generated for this layer.\n two_boxes_for_ar1 (bool, optional): Only relevant if `aspect_ratios` contains 1.\n If `True`, two default boxes will be generated for aspect ratio 1. The first will be generated\n using the scaling factor for the respective layer, the second one will be generated using\n geometric mean of said scaling factor and next bigger scaling factor.\n clip_boxes (bool, optional): If `True`, clips the anchor box coordinates to stay within image boundaries.\n variances (list, optional): A list of 4 floats >0. The anchor box offset for each coordinate will be divided by\n its respective variance value.\n coords (str, optional): The box coordinate format to be used internally in the model (i.e. this is not the input format\n of the ground truth labels). Can be either 'centroids' for the format `(cx, cy, w, h)` (box center coordinates, width, and height),\n 'corners' for the format `(xmin, ymin, xmax, ymax)`, or 'minmax' for the format `(xmin, xmax, ymin, ymax)`.\n normalize_coords (bool, optional): Set to `True` if the model uses relative instead of absolute coordinates,\n i.e. if the model predicts box coordinates within [0,1] instead of absolute coordinates.\n '''\n if K.backend() != 'tensorflow':\n raise TypeError(\"This layer only supports TensorFlow at the moment, but you are using the {} backend.\".format(K.backend()))\n\n if (this_scale < 0) or (next_scale < 0) or (this_scale > 1):\n raise ValueError(\"`this_scale` must be in [0, 1] and `next_scale` must be >0, but `this_scale` == {}, `next_scale` == {}\".format(this_scale, next_scale))\n\n if len(variances) != 4:\n raise ValueError(\"4 variance values must be pased, but {} values were received.\".format(len(variances)))\n variances = np.array(variances)\n if np.any(variances <= 0):\n raise ValueError(\"All variances must be >0, but the variances given are {}\".format(variances))\n\n self.img_height = img_height\n self.img_width = img_width\n self.this_scale = this_scale\n self.next_scale = next_scale\n self.aspect_ratios = aspect_ratios\n self.two_boxes_for_ar1 = two_boxes_for_ar1\n self.this_steps = this_steps\n self.this_offsets = this_offsets\n self.clip_boxes = clip_boxes\n self.variances = variances\n self.coords = coords\n self.normalize_coords = normalize_coords\n # Compute the number of boxes per cell\n if (1 in aspect_ratios) and two_boxes_for_ar1:\n self.n_boxes = len(aspect_ratios) + 1\n else:\n self.n_boxes = len(aspect_ratios)\n super(AnchorBoxes, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.input_spec = [InputSpec(shape=input_shape)]\n super(AnchorBoxes, self).build(input_shape)\n\n def call(self, x, mask=None):\n '''\n Return an anchor box tensor based on the shape of the input tensor.\n\n The logic implemented here is identical to the logic in the module `ssd_box_encode_decode_utils.py`.\n\n Note that this tensor does not participate in any graph computations at runtime. It is being created\n as a constant once during graph creation and is just being output along with the rest of the model output\n during runtime. Because of this, all logic is implemented as Numpy array operations and it is sufficient\n to convert the resulting Numpy array into a Keras tensor at the very end before outputting it.\n\n Arguments:\n x (tensor): 4D tensor of shape `(batch, channels, height, width)` if `dim_ordering = 'th'`\n or `(batch, height, width, channels)` if `dim_ordering = 'tf'`. The input for this\n layer must be the output of the localization predictor layer.\n '''\n\n # Compute box width and height for each aspect ratio\n # The shorter side of the image will be used to compute `w` and `h` using `scale` and `aspect_ratios`.\n size = min(self.img_height, self.img_width)\n # Compute the box widths and and heights for all aspect ratios\n wh_list = []\n for ar in self.aspect_ratios:\n if (ar == 1):\n # Compute the regular anchor box for aspect ratio 1.\n box_height = box_width = self.this_scale * size\n wh_list.append((box_width, box_height))\n if self.two_boxes_for_ar1:\n # Compute one slightly larger version using the geometric mean of this scale value and the next.\n box_height = box_width = np.sqrt(self.this_scale * self.next_scale) * size\n wh_list.append((box_width, box_height))\n else:\n box_height = self.this_scale * size / np.sqrt(ar)\n box_width = self.this_scale * size * np.sqrt(ar)\n wh_list.append((box_width, box_height))\n wh_list = np.array(wh_list)\n\n # We need the shape of the input tensor\n if type(x) is list:\n x=x[0]\n if K.image_data_format() != 'tf':\n batch_size, feature_map_height, feature_map_width, feature_map_channels = x.shape\n else: # Not yet relevant since TensorFlow is the only supported backend right now, but it can't harm to have this in here for the future\n batch_size, feature_map_channels, feature_map_height, feature_map_width = x.shape\n\n # Compute the grid of box center points. They are identical for all aspect ratios.\n\n # Compute the step sizes, i.e. how far apart the anchor box center points will be vertically and horizontally.\n if (self.this_steps is None):\n step_height = self.img_height / feature_map_height\n step_width = self.img_width / feature_map_width\n else:\n if isinstance(self.this_steps, (list, tuple)) and (len(self.this_steps) == 2):\n step_height = self.this_steps[0]\n step_width = self.this_steps[1]\n elif isinstance(self.this_steps, (int, float)):\n step_height = self.this_steps\n step_width = self.this_steps\n # Compute the offsets, i.e. at what pixel values the first anchor box center point will be from the top and from the left of the image.\n if (self.this_offsets is None):\n offset_height = 0.5\n offset_width = 0.5\n else:\n if isinstance(self.this_offsets, (list, tuple)) and (len(self.this_offsets) == 2):\n offset_height = self.this_offsets[0]\n offset_width = self.this_offsets[1]\n elif isinstance(self.this_offsets, (int, float)):\n offset_height = self.this_offsets\n offset_width = self.this_offsets\n # Now that we have the offsets and step sizes, compute the grid of anchor box center points.\n cy = np.linspace(offset_height * step_height, (offset_height + feature_map_height - 1) * step_height, feature_map_height)\n cx = np.linspace(offset_width * step_width, (offset_width + feature_map_width - 1) * step_width, feature_map_width)\n cx_grid, cy_grid = np.meshgrid(cx, cy)\n cx_grid = np.expand_dims(cx_grid, -1) # This is necessary for np.tile() to do what we want further down\n cy_grid = np.expand_dims(cy_grid, -1) # This is necessary for np.tile() to do what we want further down\n\n # Create a 4D tensor template of shape `(feature_map_height, feature_map_width, n_boxes, 4)`\n # where the last dimension will contain `(cx, cy, w, h)`\n boxes_tensor = np.zeros((feature_map_height, feature_map_width, self.n_boxes, 4))\n\n boxes_tensor[:, :, :, 0] = np.tile(cx_grid, (1, 1, self.n_boxes)) # Set cx\n boxes_tensor[:, :, :, 1] = np.tile(cy_grid, (1, 1, self.n_boxes)) # Set cy\n boxes_tensor[:, :, :, 2] = wh_list[:, 0] # Set w\n boxes_tensor[:, :, :, 3] = wh_list[:, 1] # Set h\n\n # Convert `(cx, cy, w, h)` to `(xmin, xmax, ymin, ymax)`\n boxes_tensor = convert_coordinates(boxes_tensor, start_index=0, conversion='centroids2corners')\n\n # If `clip_boxes` is enabled, clip the coordinates to lie within the image boundaries\n if self.clip_boxes:\n x_coords = boxes_tensor[:,:,:,[0, 2]]\n x_coords[x_coords >= self.img_width] = self.img_width - 1\n x_coords[x_coords < 0] = 0\n boxes_tensor[:,:,:,[0, 2]] = x_coords\n y_coords = boxes_tensor[:,:,:,[1, 3]]\n y_coords[y_coords >= self.img_height] = self.img_height - 1\n y_coords[y_coords < 0] = 0\n boxes_tensor[:,:,:,[1, 3]] = y_coords\n\n # If `normalize_coords` is enabled, normalize the coordinates to be within [0,1]\n if self.normalize_coords:\n boxes_tensor[:, :, :, [0, 2]] /= self.img_width\n boxes_tensor[:, :, :, [1, 3]] /= self.img_height\n\n # TODO: Implement box limiting directly for `(cx, cy, w, h)` so that we don't have to unnecessarily convert back and forth.\n if self.coords == 'centroids':\n # Convert `(xmin, ymin, xmax, ymax)` back to `(cx, cy, w, h)`.\n boxes_tensor = convert_coordinates(boxes_tensor, start_index=0, conversion='corners2centroids', border_pixels='half')\n elif self.coords == 'minmax':\n # Convert `(xmin, ymin, xmax, ymax)` to `(xmin, xmax, ymin, ymax).\n boxes_tensor = convert_coordinates(boxes_tensor, start_index=0, conversion='corners2minmax', border_pixels='half')\n\n # Create a tensor to contain the variances and append it to `boxes_tensor`. This tensor has the same shape\n # as `boxes_tensor` and simply contains the same 4 variance values for every position in the last axis.\n variances_tensor = np.zeros_like(boxes_tensor) # Has shape `(feature_map_height, feature_map_width, n_boxes, 4)`\n variances_tensor += self.variances # Long live broadcasting\n # Now `boxes_tensor` becomes a tensor of shape `(feature_map_height, feature_map_width, n_boxes, 8)`\n boxes_tensor = np.concatenate((boxes_tensor, variances_tensor), axis=-1)\n\n # Now prepend one dimension to `boxes_tensor` to account for the batch size and tile it along\n # The result will be a 5D tensor of shape `(batch_size, feature_map_height, feature_map_width, n_boxes, 8)`\n boxes_tensor = np.expand_dims(boxes_tensor, axis=0)\n boxes_tensor = K.tile(K.constant(boxes_tensor, dtype='float32'), (K.shape(x)[0], 1, 1, 1, 1))\n\n return boxes_tensor\n\n def compute_output_shape(self, input_shape):\n if K.image_dim_ordering() == 'tf':\n batch_size, feature_map_height, feature_map_width, feature_map_channels = input_shape\n else: # Not yet relevant since TensorFlow is the only supported backend right now, but it can't harm to have this in here for the future\n batch_size, feature_map_channels, feature_map_height, feature_map_width = input_shape\n return (batch_size, feature_map_height, feature_map_width, self.n_boxes, 8)\n\n def get_config(self):\n config = {\n 'img_height': self.img_height,\n 'img_width': self.img_width,\n 'this_scale': self.this_scale,\n 'next_scale': self.next_scale,\n 'aspect_ratios': list(self.aspect_ratios),\n 'two_boxes_for_ar1': self.two_boxes_for_ar1,\n 'clip_boxes': self.clip_boxes,\n 'variances': list(self.variances),\n 'coords': self.coords,\n 'normalize_coords': self.normalize_coords\n }\n base_config = super(AnchorBoxes, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n"
] |
[
[
"numpy.expand_dims",
"numpy.sqrt",
"numpy.linspace",
"numpy.meshgrid",
"numpy.tile",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.any",
"numpy.array",
"numpy.zeros"
]
] |
pillera/cta-lstchain
|
[
"699b8385bc4bdc35b226c14020638f5d2fcf3c07",
"699b8385bc4bdc35b226c14020638f5d2fcf3c07"
] |
[
"lstchain/visualization/plot_drs4.py",
"lstchain/calib/camera/r0.py"
] |
[
"\nfrom matplotlib import pyplot as plt\nfrom traitlets.config.loader import Config\nimport numpy as np\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom ctapipe.io import event_source\nfrom lstchain.calib.camera.r0 import LSTR0Corrections\nfrom ctapipe.io.containers import PedestalContainer\nfrom ctapipe.instrument import CameraGeometry\n\n\nfrom ctapipe.calib.camera.pedestals import PedestalIntegrator\nfrom ctapipe.visualization import CameraDisplay\n\n__all__ = ['plot_pedestals',\n ]\n\nchannel = ['HG', 'LG']\n\n\ndef plot_pedestals(data_file, pedestal_file, run=0 , plot_file=\"none\", tel_id=1, offset_value=400):\n \"\"\"\n plot pedestal quantities quantities\n\n Parameters\n ----------\n data_file: pedestal run\n\n pedestal_file: file with drs4 corrections\n\n run: run number of data to be corrected\n\n plot_file: name of output pdf file\n \"\"\"\n\n # plot open pdf\n if plot_file != \"none\":\n pp = PdfPages(plot_file)\n\n plt.rc('font', size=15)\n\n # r0 calibrator\n r0_calib = LSTR0Corrections(pedestal_path=pedestal_file, offset=offset_value,\n r1_sample_start=2, r1_sample_end=38, tel_id=tel_id )\n\n # event_reader\n reader = event_source(data_file, max_events=1000)\n t = np.linspace(2, 37, 36)\n\n # configuration for the charge integrator\n charge_config = Config({\n \"FixedWindowSum\": {\n \"window_start\": 12,\n \"window_width\": 12,\n }\n\n })\n # declare the pedestal component\n pedestal = PedestalIntegrator(tel_id=tel_id,\n sample_size=1000,\n sample_duration=1000000,\n charge_median_cut_outliers=[-10, 10],\n charge_std_cut_outliers=[-10, 10],\n charge_product=\"FixedWindowSum\",\n config=charge_config)\n\n for i, event in enumerate(reader):\n\n # move from R0 to R1\n r0_calib.calibrate(event)\n\n ok = pedestal.calculate_pedestals(event)\n if ok:\n ped_data = event.mon.tel[tel_id].pedestal\n break\n\n camera = CameraGeometry.from_name(\"LSTCam\", 2)\n\n # plot open pdf\n if plot_file != \"none\":\n pp = PdfPages(plot_file)\n\n plt.rc('font', size=15)\n\n ### first figure\n fig = plt.figure(1, figsize=(12, 24))\n plt.tight_layout()\n n_samples = charge_config[\"FixedWindowSum\"]['window_width']\n fig.suptitle(f\"Run {run}, integration on {n_samples} samples\", fontsize=25)\n pad = 420\n\n image = ped_data.charge_median\n mask = ped_data.charge_median_outliers\n for chan in (np.arange(2)):\n pad += 1\n plt.subplot(pad)\n plt.tight_layout()\n disp = CameraDisplay(camera)\n mymin = np.median(image[chan]) - 2 * np.std(image[chan])\n mymax = np.median(image[chan]) + 2 * np.std(image[chan])\n disp.set_limits_minmax(mymin, mymax)\n disp.highlight_pixels(mask[chan], linewidth=2)\n disp.image = image[chan]\n disp.cmap = plt.cm.coolwarm\n # disp.axes.text(lposx, 0, f'{channel[chan]} pedestal [ADC]', rotation=90)\n plt.title(f'{channel[chan]} pedestal [ADC]')\n disp.add_colorbar()\n\n image = ped_data.charge_std\n mask = ped_data.charge_std_outliers\n for chan in (np.arange(2)):\n pad += 1\n plt.subplot(pad)\n plt.tight_layout()\n disp = CameraDisplay(camera)\n mymin = np.median(image[chan]) - 2 * np.std(image[chan])\n mymax = np.median(image[chan]) + 2 * np.std(image[chan])\n disp.set_limits_minmax(mymin, mymax)\n disp.highlight_pixels(mask[chan], linewidth=2)\n disp.image = image[chan]\n disp.cmap = plt.cm.coolwarm\n # disp.axes.text(lposx, 0, f'{channel[chan]} pedestal std [ADC]', rotation=90)\n plt.title(f'{channel[chan]} pedestal std [ADC]')\n disp.add_colorbar()\n\n ### histograms\n for chan in np.arange(2):\n mean_ped = ped_data.charge_mean[chan]\n ped_std = ped_data.charge_std[chan]\n\n # select good pixels\n select = np.logical_not(mask[chan])\n\n #fig.suptitle(f\"Run {run} channel: {channel[chan]}\", fontsize=25)\n pad += 1\n # pedestal charge\n plt.subplot(pad)\n plt.tight_layout()\n plt.ylabel('pixels')\n plt.xlabel(f'{channel[chan]} pedestal')\n median = np.median(mean_ped[select])\n rms = np.std(mean_ped[select])\n label = f\"{channel[chan]} Median {median:3.2f}, std {rms:3.2f}\"\n plt.hist(mean_ped[select], bins=50, label=label)\n plt.legend()\n pad += 1\n # pedestal std\n plt.subplot(pad)\n plt.ylabel('pixels')\n plt.xlabel(f'{channel[chan]} pedestal std')\n median = np.median(ped_std[select])\n rms = np.std(ped_std[select])\n label = f\" Median {median:3.2f}, std {rms:3.2f}\"\n plt.hist(ped_std[select], bins=50, label=label)\n plt.legend()\n\n plt.subplots_adjust(top=0.94)\n if plot_file != \"none\":\n\n pp.savefig()\n\n pix = 0\n pad = 420\n # plot corrected waveforms of first 8 events\n for i, ev in enumerate(reader):\n for chan in np.arange(2):\n\n if pad == 420:\n # new figure\n\n fig = plt.figure(ev.r0.event_id, figsize=(12, 24))\n fig.suptitle(f\"Run {run}, pixel {pix}\", fontsize=25)\n plt.tight_layout()\n pad += 1\n plt.subplot(pad)\n\n plt.subplots_adjust(top=0.92)\n label = f\"event {ev.r0.event_id}, {channel[chan]}: R0\"\n plt.step(t, ev.r0.tel[tel_id].waveform[chan, pix, 2:38], color=\"blue\", label=label)\n\n r0_calib.subtract_pedestal(ev,tel_id)\n label = \"+ pedestal substraction\"\n plt.step(t, ev.r1.tel[tel_id].waveform[chan, pix, 2:38], color=\"red\", alpha=0.5, label=label)\n\n r0_calib.time_lapse_corr(ev,tel_id)\n r0_calib.interpolate_spikes(ev,tel_id)\n label = \"+ dt corr + interp. spikes\"\n plt.step(t, ev.r1.tel[tel_id].waveform[chan, pix, 2:38], alpha=0.5, color=\"green\",label=label)\n plt.plot([0, 40], [offset_value, offset_value], 'k--', label=\"offset\")\n plt.xlabel(\"time sample [ns]\")\n plt.ylabel(\"counts [ADC]\")\n\n plt.legend()\n plt.ylim([-50, 500])\n\n if plot_file != \"none\" and pad == 428:\n pad = 420\n plt.subplots_adjust(top=0.92)\n pp.savefig()\n\n if i == 8:\n break\n\n if plot_file != \"none\":\n pp.close()\n\n",
"import numpy as np\nfrom astropy.io import fits\nfrom ctapipe.core import Component\nfrom ctapipe.core.traits import Unicode, Int\nfrom abc import abstractmethod\nfrom numba import jit, prange\n\n__all__ = [\n 'CameraR0Calibrator',\n 'LSTR0Corrections',\n 'NullR0Calibrator',\n]\n\n\nclass CameraR0Calibrator(Component):\n \"\"\"\n The base R0-level calibrator. Change the r0 container.\n The R0 calibrator performs the camera-specific R0 calibration that is\n usually performed on the raw data by the camera server. This calibrator\n exists in lstchain for testing and prototyping purposes.\n Parameters\n ----------\n config : traitlets.loader.Config\n Configuration specified by config file or cmdline arguments.\n Used to set traitlet values.\n Set to None if no configuration to pass.\n tool : ctapipe.core.Tool or None\n Tool executable that is calling this component.\n Passes the correct logger to the component.\n Set to None if no Tool to pass.\n kwargs\n \"\"\"\n tel_id = Int(1,\n help='id of the telescope to calibrate'\n ).tag(config=True)\n\n offset = Int(default_value=400,\n help='Define the offset of the baseline').tag(config=True)\n\n r1_sample_start = Int(default_value=2,\n help='Start sample for r1 waveform',\n allow_none=True).tag(config=True)\n\n r1_sample_end = Int(default_value=38,\n help='End sample for r1 waveform',\n allow_none=True).tag(config=True)\n\n def __init__(self, **kwargs):\n \"\"\"\n Parent class for the r0 calibrators. Change the r0 container.\n Parameters\n ----------\n config : traitlets.loader.Config\n Configuration specified by config file or cmdline arguments.\n Used to set traitlet values.\n Set to None if no configuration to pass.\n tool : ctapipe.core.Tool or None\n Tool executable that is calling this component.\n Passes the correct logger to the component.\n Set to None if no Tool to pass.\n kwargs\n \"\"\"\n super().__init__(**kwargs)\n\n @abstractmethod\n def calibrate(self, event):\n \"\"\"\n Abstract method to be defined in child class.\n Perform the conversion from raw R0 data to R1 data\n (ADC Samples -> PE Samples), and fill the r1 container.\n Parameters\n ----------\n event : container\n A `ctapipe` event container\n \"\"\"\n\n\nclass LSTR0Corrections(CameraR0Calibrator):\n \"\"\"\n The R0 calibrator class for LST Camera.\n \"\"\"\n\n pedestal_path = Unicode('',\n allow_none=True,\n help='Path to the LST pedestal binary file'\n ).tag(config=True)\n\n def __init__(self, **kwargs):\n \"\"\"\n The R0 calibrator for LST data.\n Fill the r1 container.\n Parameters\n ----------\n config : traitlets.loader.Config\n Configuration specified by config file or cmdline arguments.\n Used to set traitlet values.\n Set to None if no configuration to pass.\n tool : ctapipe.core.Tool\n Tool executable that is calling this component.\n Passes the correct logger to the component.\n Set to None if no Tool to pass.\n kwargs\n \"\"\"\n super().__init__(**kwargs)\n self.n_module = 265\n self.n_gain = 2\n self.n_pix = 7\n self.size4drs = 4 * 1024\n self.roisize = 40\n self.high_gain = 0\n self.low_gain = 1\n self.last_run_with_old_firmware = 1574\n self.pedestal_value_array = np.zeros((self.n_gain,\n self.n_pix*self.n_module,\n self.size4drs+40),\n dtype=np.int16)\n\n self.first_cap_array = np.zeros((self.n_module,\n self.n_gain,\n self.n_pix))\n\n self.first_cap_time_lapse_array = np.zeros((self.n_module,\n self.n_gain,\n self.n_pix))\n\n self.last_reading_time_array = np.zeros((self.n_module,\n self.n_gain,\n self.n_pix,\n self.size4drs))\n\n self.first_cap_array_spike = np.zeros((self.n_module,\n self.n_gain,\n self.n_pix))\n\n self.first_cap_old_array = np.zeros((self.n_module,\n self.n_gain,\n self.n_pix))\n\n self._load_calib()\n\n def calibrate(self, event):\n for tel_id in event.r0.tels_with_data:\n self.subtract_pedestal(event, tel_id)\n self.time_lapse_corr(event, tel_id)\n self.interpolate_spikes(event, tel_id)\n\n event.r1.tel[self.tel_id].trigger_type = event.r0.tel[self.tel_id].trigger_type\n\n event.r1.tel[self.tel_id].trigger_time = event.r0.tel[self.tel_id].trigger_time\n\n samples = event.r1.tel[tel_id].waveform[:, :, self.r1_sample_start:self.r1_sample_end]\n\n event.r1.tel[tel_id].waveform = samples.astype('int16') - self.offset\n\n def subtract_pedestal(self, event, tel_id):\n \"\"\"\n Subtract cell offset using pedestal file.\n Fill the R1 container.\n Parameters\n ----------\n event : `ctapipe` event-container\n tel_id : id of the telescope\n \"\"\"\n n_modules = event.lst.tel[tel_id].svc.num_modules\n\n for nr_module in range(0, n_modules):\n self.first_cap_array[nr_module, :, :] = self._get_first_capacitor(event, nr_module, tel_id)\n\n expected_pixel_id = event.lst.tel[tel_id].svc.pixel_ids\n samples = np.copy(event.r0.tel[tel_id].waveform)\n samples.astype('int16')\n\n samples = subtract_pedestal_jit(samples,\n expected_pixel_id,\n self.first_cap_array,\n self.pedestal_value_array,\n n_modules)\n\n event.r1.tel[self.tel_id].trigger_type = event.r0.tel[self.tel_id].trigger_type\n event.r1.tel[self.tel_id].trigger_time = event.r1.tel[self.tel_id].trigger_time\n event.r1.tel[self.tel_id].waveform = samples[:, :, :]\n\n\n def time_lapse_corr(self, event, tel_id):\n \"\"\"\n Perform time lapse baseline corrections.\n Fill the R1 container or modifies R0 container.\n Parameters\n ----------\n event : `ctapipe` event-container\n tel_id : id of the telescope\n \"\"\"\n\n run_id = event.lst.tel[tel_id].svc.configuration_id\n\n expected_pixel_id = event.lst.tel[tel_id].svc.pixel_ids\n local_clock_list = event.lst.tel[tel_id].evt.local_clock_counter\n n_modules = event.lst.tel[tel_id].svc.num_modules\n for nr_module in range(0, n_modules):\n self.first_cap_time_lapse_array[nr_module, :, :] = self._get_first_capacitor(event, nr_module, tel_id)\n\n #If R1 container exist modifies it\n if isinstance(event.r1.tel[self.tel_id].waveform, np.ndarray):\n samples = event.r1.tel[self.tel_id].waveform\n\n # We have 2 functions: one for data from 2018/10/10 to 2019/11/04 and\n # one for data from 2019/11/05 (from Run 1574) after update firmware.\n # The old readout (before 2019/11/05) is shifted by 1 cell.\n if run_id > self.last_run_with_old_firmware:\n do_time_lapse_corr(samples,\n expected_pixel_id,\n local_clock_list,\n self.first_cap_time_lapse_array,\n self.last_reading_time_array,\n n_modules)\n else:\n do_time_lapse_corr_data_from_20181010_to_20191104(samples,\n expected_pixel_id,\n local_clock_list,\n self.first_cap_time_lapse_array,\n self.last_reading_time_array,\n n_modules)\n\n event.r1.tel[self.tel_id].trigger_type = event.r0.tel[self.tel_id].trigger_type\n event.r1.tel[self.tel_id].trigger_time = event.r0.tel[self.tel_id].trigger_time\n event.r1.tel[self.tel_id].waveform = samples[:, :, :]\n\n else: # Modifies R0 container. This is for create pedestal file.\n samples = np.copy(event.r0.tel[self.tel_id].waveform)\n\n if run_id > self.last_run_with_old_firmware:\n do_time_lapse_corr(samples,\n expected_pixel_id,\n local_clock_list,\n self.first_cap_time_lapse_array,\n self.last_reading_time_array,\n n_modules)\n else:\n do_time_lapse_corr_data_from_20181010_to_20191104(samples,\n expected_pixel_id,\n local_clock_list,\n self.first_cap_time_lapse_array,\n self.last_reading_time_array,\n n_modules)\n\n event.r0.tel[self.tel_id].waveform = samples[:, :, :]\n\n\n def interpolate_spikes(self, event, tel_id):\n \"\"\"\n Interpolates spike A & B.\n Fill the R1 container.\n Parameters\n ----------\n event : `ctapipe` event-container\n tel_id : id of the telescope\n \"\"\"\n run_id = event.lst.tel[tel_id].svc.configuration_id\n\n self.first_cap_old_array[:, :, :] = self.first_cap_array_spike[:, :, :]\n n_modules = event.lst.tel[tel_id].svc.num_modules\n for nr_module in range(0, n_modules):\n self.first_cap_array_spike[nr_module, :, :] = self._get_first_capacitor(event, nr_module, tel_id)\n\n # Interpolate spikes should be done after pedestal subtraction and time lapse correction.\n if isinstance(event.r1.tel[tel_id].waveform, np.ndarray):\n waveform = event.r1.tel[tel_id].waveform[:, :, :]\n expected_pixel_id = event.lst.tel[tel_id].svc.pixel_ids\n samples = waveform.copy()\n\n # We have 2 functions: one for data from 2018/10/10 to 2019/11/04 and\n # one for data from 2019/11/05 (from Run 1574) after update firmware.\n # The old readout (before 2019/11/05) is shifted by 1 cell.\n if run_id > self.last_run_with_old_firmware:\n event.r1.tel[self.tel_id].waveform = self.interpolate_pseudo_pulses(samples,\n expected_pixel_id,\n self.first_cap_array_spike,\n self.first_cap_old_array,\n n_modules)\n else:\n event.r1.tel[self.tel_id].waveform = \\\n self.interpolate_pseudo_pulses_data_from_20181010_to_20191104(samples,\n expected_pixel_id,\n self.first_cap_array_spike,\n self.first_cap_old_array,\n n_modules)\n\n event.r1.tel[self.tel_id].trigger_type = event.r0.tel[self.tel_id].trigger_type\n event.r1.tel[self.tel_id].trigger_time = event.r0.tel[self.tel_id].trigger_time\n\n @staticmethod\n @jit(parallel=True)\n def interpolate_pseudo_pulses(waveform, expected_pixel_id, fc, fc_old, n_modules):\n \"\"\"\n Interpolate Spike A & B.\n Change waveform array.\n Parameters\n ----------\n waveform : ndarray\n Waveform stored in a numpy array of shape\n (n_gain, n_pix, n_samples).\n expected_pixel_id: ndarray\n Array stored expected pixel id\n (n_pix*n_modules).\n fc : ndarray\n Value of first capacitor stored in a numpy array of shape\n (n_clus, n_gain, n_pix).\n fc_old : ndarray\n Value of first capacitor from previous event\n stored in a numpy array of shape\n (n_clus, n_gain, n_pix).\n n_modules : int\n Number of modules\n \"\"\"\n roi_size = 40\n size1drs = 1024\n size4drs = 4096\n n_gain = 2\n n_pix = 7\n for nr_module in prange(0, n_modules):\n for gain in prange(0, n_gain):\n for pix in prange(0, n_pix):\n for k in prange(0, 4):\n # looking for spike A first case\n abspos = int(size1drs + 1 - roi_size - 2 - fc_old[nr_module, gain, pix] + k * size1drs + size4drs)\n spike_A_position = int((abspos - fc[nr_module, gain, pix] + size4drs) % size4drs)\n if (spike_A_position > 2 and spike_A_position < roi_size-2):\n # The correction is only needed for even\n # last capacitor (lc) in the first half of the\n # DRS4 ring\n if ((fc_old[nr_module, gain, pix] + (roi_size-1)) % 2 == 0 and (fc_old[nr_module, gain, pix] + (roi_size-1)) % size1drs <= size1drs//2-1):\n pixel = expected_pixel_id[nr_module * 7 + pix]\n interpolate_spike_A(waveform, gain, spike_A_position, pixel)\n\n # looking for spike A second case\n abspos = int(roi_size - 1 + fc_old[nr_module, gain, pix] + k * size1drs)\n spike_A_position = int((abspos - fc[nr_module, gain, pix] + size4drs) % size4drs)\n if (spike_A_position > 2 and spike_A_position < (roi_size-2)):\n # The correction is only needed for even last capacitor (lc) in the\n # first half of the DRS4 ring\n if ((fc_old[nr_module, gain, pix] + (roi_size-1)) % 2 == 0 and (fc_old[nr_module, gain, pix] + (roi_size-1)) % size1drs <= size1drs//2-1):\n pixel = expected_pixel_id[nr_module * 7 + pix]\n interpolate_spike_A(waveform, gain, spike_A_position, pixel)\n return waveform\n\n @staticmethod\n @jit(parallel=True)\n def interpolate_pseudo_pulses_data_from_20181010_to_20191104(waveform, expected_pixel_id, fc, fc_old, n_modules):\n \"\"\"\n Interpolate Spike A & B.\n This is function for data from 2018/10/10 to 2019/11/04 with old firmware.\n Change waveform array.\n Parameters\n ----------\n waveform : ndarray\n Waveform stored in a numpy array of shape\n (n_gain, n_pix, n_samples).\n expected_pixel_id: ndarray\n Array stored expected pixel id\n (n_pix*n_modules).\n fc : ndarray\n Value of first capacitor stored in a numpy array of shape\n (n_clus, n_gain, n_pix).\n fc_old : ndarray\n Value of first capacitor from previous event\n stored in a numpy array of shape\n (n_clus, n_gain, n_pix).\n n_modules : int\n Number of modules\n \"\"\"\n roi_size = 40\n size1drs = 1024\n size4drs = 4096\n n_gain = 2\n n_pix = 7\n for nr_module in prange(0, n_modules):\n for gain in prange(0, n_gain):\n for pix in prange(0, n_pix):\n for k in prange(0, 4):\n # looking for spike A first case\n abspos = int(size1drs - roi_size - 2 -fc_old[nr_module, gain, pix]+ k * size1drs + size4drs)\n spike_A_position = int((abspos - fc[nr_module, gain, pix]+ size4drs) % size4drs)\n if (spike_A_position > 2 and spike_A_position < roi_size-2):\n # The correction is only needed for even\n # last capacitor (lc) in the first half of the\n # DRS4 ring\n if ((fc_old[nr_module, gain, pix] + (roi_size-1)) % 2 == 0 and (fc_old[nr_module, gain, pix]+ (roi_size-1)) % size1drs <= size1drs//2-2):\n pixel = expected_pixel_id[nr_module*7 + pix]\n interpolate_spike_A(waveform, gain, spike_A_position, pixel)\n\n # looking for spike A second case\n abspos = int(roi_size - 2 + fc_old[nr_module, gain, pix]+ k * size1drs)\n spike_A_position = int((abspos -fc[nr_module, gain, pix] + size4drs) % size4drs)\n if (spike_A_position > 2 and spike_A_position < (roi_size-2)):\n # The correction is only needed for even last capacitor (lc) in the\n # first half of the DRS4 ring\n if ((fc_old[nr_module, gain, pix] + (roi_size-1)) % 2 == 0 and (fc_old[nr_module, gain, pix] + (roi_size-1)) % size1drs <= size1drs//2-2):\n pixel = expected_pixel_id[nr_module*7 + pix]\n interpolate_spike_A(waveform, gain, spike_A_position, pixel)\n return waveform\n\n def _load_calib(self):\n \"\"\"\n Function to load pedestal file.\n \"\"\"\n if self.pedestal_path:\n with fits.open(self.pedestal_path) as f:\n pedestal_data = np.int16(f[1].data)\n self.pedestal_value_array[:, :, :self.size4drs] = \\\n pedestal_data - self.offset\n self.pedestal_value_array[:, :, self.size4drs:self.size4drs + 40] \\\n = pedestal_data[:, :, 0:40] - self.offset\n\n def _get_first_capacitor(self, event, nr_module, tel_id):\n \"\"\"\n Get first capacitor values from event for nr module.\n Parameters\n ----------\n event : `ctapipe` event-container\n nr_module : number of module\n tel_id : id of the telescope\n \"\"\"\n fc = np.zeros((2, 7))\n first_cap = event.lst.tel[tel_id].evt.first_capacitor_id[nr_module * 8:\n (nr_module + 1) * 8]\n\n # First capacitor order according Dragon v5 board data format\n for i, j in zip([0, 1, 2, 3, 4, 5, 6], [0, 0, 1, 1, 2, 2, 3]):\n fc[self.high_gain, i] = first_cap[j]\n for i, j in zip([0, 1, 2, 3, 4, 5, 6], [4, 4, 5, 5, 6, 6, 7]):\n fc[self.low_gain, i] = first_cap[j]\n return fc\n\n@jit(parallel=True)\ndef subtract_pedestal_jit(event_waveform, expected_pixel_id, fc_cap, pedestal_value_array, n_modules):\n \"\"\"\n Numba function for subtract pedestal.\n Change waveform array.\n \"\"\"\n waveform = np.zeros(event_waveform.shape)\n size4drs = 4096\n roi_size = 40\n n_gain = 2\n n_pix = 7\n for nr_module in prange(0, n_modules):\n for gain in prange(0, n_gain):\n for pix in prange(0, n_pix):\n pixel = expected_pixel_id[nr_module*7 + pix]\n position = int((fc_cap[nr_module, gain, pix]) % size4drs)\n waveform[gain, pixel, :] = \\\n (event_waveform[gain, pixel, :] -\n pedestal_value_array[gain, pixel, position:position + roi_size])\n return waveform\n\n@jit(parallel=True)\ndef do_time_lapse_corr(waveform, expected_pixel_id, local_clock_list,\n fc, last_time_array, number_of_modules):\n \"\"\"\n Numba function for time lapse baseline correction.\n Change waveform array.\n \"\"\"\n size4drs = 4096\n size1drs = 1024\n roi_size = 40\n n_gain = 2\n n_pix = 7\n for nr_module in prange(0, number_of_modules):\n time_now = local_clock_list[nr_module]\n for gain in prange(0, n_gain):\n for pix in prange(0, n_pix):\n pixel = expected_pixel_id[nr_module*7 + pix]\n for k in prange(0, roi_size):\n posads = int((k + fc[nr_module, gain, pix]) % size4drs)\n if last_time_array[nr_module, gain, pix, posads] > 0:\n time_diff = time_now - last_time_array[nr_module, gain, pix, posads]\n time_diff_ms = time_diff / (133.e3)\n if time_diff_ms < 100:\n val =(waveform[gain, pixel, k] - ped_time(time_diff_ms))\n waveform[gain, pixel, k] = val\n\n posads0 = int((0 + fc[nr_module, gain, pix]) % size4drs)\n if posads0+roi_size < size4drs:\n last_time_array[nr_module, gain, pix, (posads0):(posads0+roi_size)] = time_now\n else:\n for k in prange(0, roi_size):\n posads = int((k + fc[nr_module, gain, pix]) % size4drs)\n last_time_array[nr_module, gain, pix, posads] = time_now\n\n # now the magic of Dragon,\n # extra conditions on the number of capacitor times being updated\n # if the ROI is in the last quarter of each DRS4\n # for even channel numbers extra 12 slices are read in a different place\n # code from Takayuki & Julian\n if pix % 2 == 0:\n first_cap = fc[nr_module, gain, pix]\n if first_cap % size1drs > 767 and first_cap % size1drs < 1013:\n start = int(first_cap) + size1drs\n end = int(first_cap) + size1drs + 12\n last_time_array[nr_module, gain, pix, (start%size4drs):(end%size4drs)] = time_now\n elif first_cap % size1drs >= 1013:\n channel = int(first_cap / size1drs)\n for kk in range(first_cap + size1drs, ((channel + 2) * size1drs)):\n last_time_array[nr_module, gain, pix, int(kk) % size4drs] = time_now\n\n@jit(parallel=True)\ndef do_time_lapse_corr_data_from_20181010_to_20191104(waveform, expected_pixel_id, local_clock_list,\n fc, last_time_array, number_of_modules):\n \"\"\"\n Numba function for time lapse baseline correction.\n This is function for data from 2018/10/10 to 2019/11/04 with old firmware.\n Change waveform array.\n \"\"\"\n size4drs = 4096\n size1drs = 1024\n roi_size = 40\n n_gain = 2\n n_pix = 7\n\n for nr_module in prange(0, number_of_modules):\n time_now = local_clock_list[nr_module]\n for gain in prange(0, n_gain):\n for pix in prange(0, n_pix):\n pixel = expected_pixel_id[nr_module * 7 + pix]\n for k in prange(0, roi_size):\n posads = int((k + fc[nr_module, gain, pix]) % size4drs)\n if last_time_array[nr_module, gain, pix, posads] > 0:\n time_diff = time_now - last_time_array[nr_module, gain, pix, posads]\n time_diff_ms = time_diff / (133.e3)\n if time_diff_ms < 100:\n val = waveform[gain, pixel, k] - ped_time(time_diff_ms)\n waveform[gain, pixel, k] = val\n\n posads0 = int((0 + fc[nr_module, gain, pix]) % size4drs)\n if posads0 + roi_size < size4drs and (posads0-1) > 1:\n last_time_array[nr_module, gain, pix, (posads0-1):(posads0 + (roi_size-1))] = time_now\n else:\n # Old firmware issue: readout shifted by 1 cell\n for k in prange(-1, roi_size-1):\n posads = int((k + fc[nr_module, gain, pix]) % size4drs)\n last_time_array[nr_module, gain, pix, posads] = time_now\n\n # now the magic of Dragon,\n # if the ROI is in the last quarter of each DRS4\n # for even channel numbers extra 12 slices are read in a different place\n # code from Takayuki & Julian\n if pix % 2 == 0:\n first_cap = fc[nr_module, gain, pix]\n if first_cap % size1drs > 766 and first_cap % size1drs < 1013:\n start = int(first_cap) + size1drs - 1\n end = int(first_cap) + size1drs + 11\n last_time_array[nr_module, gain, pix, (start % size4drs):(end % size4drs)] = time_now\n elif first_cap % size1drs >= 1013:\n channel = int(first_cap / size1drs)\n for kk in range(first_cap + size1drs, (channel + 2) * size1drs):\n last_time_array[nr_module, gain, pix, int(kk) % size4drs] = time_now\n\n@jit\ndef ped_time(timediff):\n \"\"\"\n Power law function for time lapse baseline correction.\n Coefficients from curve fitting to dragon test data\n at temperature 30 degC\n \"\"\"\n return 27.33 * np.power(timediff, -0.24) - 10.4\n\n@jit\ndef interpolate_spike_A(waveform, gain, position, pixel):\n \"\"\"\n Numba function for interpolation spike type A.\n Change waveform array.\n \"\"\"\n samples = waveform[gain, pixel, :]\n a = int(samples[position - 1])\n b = int(samples[position + 2])\n waveform[gain, pixel, position] = (samples[position - 1]) + (0.33 * (b - a))\n waveform[gain, pixel, position + 1] = (samples[position - 1]) + (0.66 * (b - a))\n\n\nclass NullR0Calibrator(CameraR0Calibrator):\n \"\"\"\n A dummy R0 calibrator that simply fills the r1 container with the samples\n from the r0 container.\n Parameters\n ----------\n config : traitlets.loader.Config\n Configuration specified by config file or cmdline arguments.\n Used to set traitlet values.\n Set to None if no configuration to pass.\n tool : ctapipe.core.Tool or None\n Tool executable that is calling this component.\n Passes the correct logger to the component.\n Set to None if no Tool to pass.\n kwargs\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.log.info(\"Using NullR0Calibrator, if event source is at \"\n \"the R0 level, then r1 samples will equal r0 samples\")\n\n def calibrate(self, event):\n for tel_id in event.r0.tels_with_data:\n event.r1.tel[tel_id].trigger_type = event.r0.tel[tel_id].trigger_type\n event.r1.tel[tel_id].trigger_time = event.r0.tel[tel_id].trigger_time\n samples = event.r0.tel[tel_id].waveform[:, :, self.r1_sample_start:self.r1_sample_end]\n event.r1.tel[tel_id].waveform = samples.astype('int16') - self.offset\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.linspace",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.step",
"matplotlib.pyplot.plot",
"matplotlib.backends.backend_pdf.PdfPages",
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"numpy.std",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.figure",
"numpy.logical_not",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"numpy.median",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
],
[
"numpy.copy",
"numpy.int16",
"numpy.zeros",
"numpy.power"
]
] |
amanyara/Boston-Home-Price-Forecast
|
[
"600ccb25c40240ffddee8871d77728a782a80498"
] |
[
"Paddle_house_predict.py"
] |
[
"# 19200300157\r\n# 张宇含\r\n#加载飞桨、Numpy和相关类库\r\nimport paddle\r\nfrom paddle.nn import Linear\r\nimport paddle.nn.functional as F\r\nimport numpy as np\r\n\r\n\r\ndef load_data():\r\n # 从文件导入数据\r\n datafile = 'housing.data'\r\n data = np.fromfile(datafile, sep=' ', dtype=np.float32)\r\n\r\n # 每条数据包括14项,其中前面13项是影响因素,第14项是相应的房屋价格中位数\r\n feature_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', \\\r\n 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']\r\n feature_num = len(feature_names)\r\n\r\n # 将原始数据进行Reshape,变成[N, 14]这样的形状\r\n data = data.reshape([data.shape[0] // feature_num, feature_num])\r\n\r\n # 将原数据集拆分成训练集和测试集\r\n # 这里使用80%的数据做训练,20%的数据做测试\r\n # 测试集和训练集必须是没有交集的\r\n ratio = 0.8\r\n offset = int(data.shape[0] * ratio)\r\n training_data = data[:offset]\r\n\r\n # 计算train数据集的最大值,最小值,平均值\r\n maximums, minimums, avgs = training_data.max(axis=0), training_data.min(axis=0), \\\r\n training_data.sum(axis=0) / training_data.shape[0]\r\n\r\n # 记录数据的归一化参数,在预测时对数据做归一化\r\n global max_values\r\n global min_values\r\n global avg_values\r\n max_values = maximums\r\n min_values = minimums\r\n avg_values = avgs\r\n\r\n # 对数据进行归一化处理\r\n for i in range(feature_num):\r\n data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])\r\n\r\n # 训练集和测试集的划分比例\r\n training_data = data[:offset]\r\n test_data = data[offset:]\r\n return training_data, test_data\r\n\r\n\r\nclass Regressor(paddle.nn.Layer):\r\n\r\n # self代表类的实例自身\r\n def __init__(self):\r\n # 初始化父类中的一些参数\r\n super(Regressor, self).__init__()\r\n\r\n # 定义一层全连接层,输入维度是13,输出维度是1\r\n self.fc = Linear(in_features=13, out_features=1)\r\n\r\n # 网络的前向计算\r\n def forward(self, inputs):\r\n x = self.fc(inputs)\r\n return x\r\n\r\n# 声明定义好的线性回归模型\r\nmodel = Regressor()\r\n# 开启模型训练模式\r\nmodel.train()\r\n# 加载数据\r\ntraining_data, test_data = load_data()\r\n# 定义优化算法,使用随机梯度下降SGD\r\n# 学习率设置为0.01\r\nopt = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters())\r\n\r\nEPOCH_NUM = 10 # 设置外层循环次数\r\nBATCH_SIZE = 10 # 设置batch大小\r\n\r\n# 定义外层循环\r\nfor epoch_id in range(EPOCH_NUM):\r\n # 在每轮迭代开始之前,将训练数据的顺序随机的打乱\r\n np.random.shuffle(training_data)\r\n # 将训练数据进行拆分,每个batch包含10条数据\r\n mini_batches = [training_data[k:k + BATCH_SIZE] for k in range(0, len(training_data), BATCH_SIZE)]\r\n # 定义内层循环\r\n for iter_id, mini_batch in enumerate(mini_batches):\r\n x = np.array(mini_batch[:, :-1]) # 获得当前批次训练数据\r\n y = np.array(mini_batch[:, -1:]) # 获得当前批次训练标签(真实房价)\r\n # 将numpy数据转为飞桨动态图tensor形式\r\n house_features = paddle.to_tensor(x)\r\n prices = paddle.to_tensor(y)\r\n # 前向计算\r\n predicts = model.forward(house_features)\r\n\r\n\r\n # 计算损失\r\n loss = F.square_error_cost(predicts, label=prices)\r\n avg_loss = paddle.mean(loss)\r\n\r\n if iter_id % 20 == 0:\r\n print(\"epoch: {}, iter: {}, loss is: {}\".format(epoch_id, iter_id, avg_loss.numpy()))\r\n\r\n # 反向传播\r\n avg_loss.backward()\r\n # 最小化loss,更新参数\r\n opt.step()\r\n # 清除梯度\r\n opt.clear_grad()\r\n\r\n\r\n\r\n# 保存模型参数,文件名为LR_model.pdparams\r\npaddle.save(model.state_dict(), 'LR_model.pdparams')\r\nprint(\"模型保存成功,模型参数保存在LR_model.pdparams中\")\r\n\r\n\r\ndef load_one_example():\r\n # 从上边已加载的测试集中,随机选择一条作为测试数据\r\n #idx = np.random.randint(0, test_data.shape[0])\r\n idx = -10\r\n one_data, label = test_data[idx, :-1], test_data[idx, -1]\r\n # 修改该条数据shape为[1,13]\r\n one_data = one_data.reshape([1, -1])\r\n\r\n return one_data, label\r\n\r\nmodel_dict = paddle.load('LR_model.pdparams')\r\nmodel.load_dict(model_dict)\r\nmodel.eval()\r\n\r\n# 参数为数据集的文件地址\r\none_data, label = load_one_example()\r\n# 将数据转为动态图的variable格式\r\none_data = paddle.to_tensor(one_data)\r\npredict = model(one_data)\r\n\r\n# 对结果做反归一化处理\r\npredict = predict * (max_values[-1] - min_values[-1]) + avg_values[-1]\r\n# 对label数据做反归一化处理\r\nlabel = label * (max_values[-1] - min_values[-1]) + avg_values[-1]\r\n\r\nprint(\"Inference result is {}, the corresponding label is {}\".format(predict.numpy(), label))"
] |
[
[
"numpy.array",
"numpy.fromfile",
"numpy.random.shuffle"
]
] |
infobeisel/lightmetrica-v3
|
[
"833d74e5ed8a470c33aca100c9494be11ecbf1be"
] |
[
"functest/func_render_all.py"
] |
[
"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.2.4\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# ## Rendering all scenes\n#\n# This test checks scene loading and basic rendering for all test scenes.\n\n# %load_ext autoreload\n# %autoreload 2\n\nimport lmenv\nenv = lmenv.load('.lmenv')\n\nimport os\nimport imageio\nimport pandas as pd\nimport numpy as np\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport lmscene\nimport lightmetrica as lm\n\nos.getpid()\n\n# %load_ext lightmetrica_jupyter\n\nlm.init()\nlm.log.init('jupyter')\nlm.progress.init('jupyter')\nlm.info()\n\nif not lm.Release:\n lm.debug.attach_to_debugger()\n\nlm.comp.load_plugin(os.path.join(env.bin_path, 'accel_embree'))\nlm.comp.load_plugin(os.path.join(env.bin_path, 'objloader_tinyobjloader'))\n\nlm.objloader.init('tinyobjloader')\n\nscene_names = lmscene.scenes_small()\n\nfor scene_name in scene_names:\n lm.reset()\n \n # Load scene\n accel = lm.load_accel('accel', 'embree', {})\n scene = lm.load_scene('scene', 'default', {\n 'accel': accel.loc()\n })\n lmscene.load(scene, env.scene_path, scene_name)\n scene.build()\n \n # Render\n film = lm.load_film('film_output', 'bitmap', {\n 'w': 1920,\n 'h': 1080\n })\n renderer = lm.load_renderer('renderer', 'raycast', {\n 'scene': scene.loc(),\n 'output': film.loc()\n })\n renderer.render()\n \n # Visualize\n img = np.copy(film.buffer())\n f = plt.figure(figsize=(15,15))\n ax = f.add_subplot(111)\n ax.imshow(np.clip(np.power(img,1/2.2),0,1), origin='lower')\n ax.set_title(scene)\n plt.show()\n\n\n"
] |
[
[
"matplotlib.pyplot.show",
"numpy.power",
"matplotlib.pyplot.figure"
]
] |
jamesthesken/stock-scraper
|
[
"619e6689a4963deeea2b60c63c869eb43d017f3d"
] |
[
"wsb_scraper.py"
] |
[
"import config\nimport praw\nfrom praw.models import MoreComments\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom sqlalchemy import create_engine\n\n# Creates a set of stock tickers in NASDAQ\ndef nasdaq_tickers():\n fin = open(\"nasdaqtraded.txt\", 'r')\n tickers = set()\n fin.readline()\n for line in fin.readlines():\n line = line[2:]\n tickers.add(line[:line.index(\"|\")])\n return tickers\n\n# Search wsb top level comments given a flair and time interval (week, day, hour, etc.). \n# Returns: \n# results - dictionary containing ticker and amount of times it was mentioned in the time interval.\n# ticker_info - list of dictionaries containing ticker name and sentiment. used later in a Pandas dataframe for agg. functions\ndef searchFlairs(flair, time):\n reddit = praw.Reddit(client_id = config.client_id, client_secret = config.client_secret, user_agent = config.user_agent)\n counter = 0\n flagged_words = [\"YOLO\", \"PUMP\", \"RH\", \"EOD\", \"IPO\", \"ATH\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \n \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n ticker_set = nasdaq_tickers()\n tickers = {}\n\n ticker_info = []\n\n analyzer = SentimentIntensityAnalyzer()\n\n for submission in reddit.subreddit('wallstreetbets').search('flair:\"%s\"'%(flair), sort='new', time_filter='%s'%(time)):\n print(submission.title)\n for top_level_comment in submission.comments:\n ticker_sentiment = {}\n if isinstance(top_level_comment, MoreComments):\n continue \n for word in top_level_comment.body.split():\n if word == word.upper() and word in ticker_set and word not in flagged_words:\n vs = analyzer.polarity_scores(top_level_comment.body)\n ticker_sentiment['ticker'] = word\n ticker_sentiment['sent'] = vs['compound']\n ticker_sentiment['ts'] = top_level_comment.created_utc\n ticker_info.append(ticker_sentiment)\n if word not in tickers:\n tickers[word] = 1\n else:\n tickers[word] += 1\n return tickers, ticker_info\n\n# Plotting the tickers on a pie chart\ndef popularTickers():\n #result = ticker_count()\n result, ticker_info = searchFlairs('Daily Discussion', 'week')\n x = []\n y = []\n for a, b in result.items():\n # Can change value to see choose the threshold stock mention count \n if b > 5:\n x.append(a)\n y.append(b)\n # Uncomment to see a pie chart \n fig1, ax1 = plt.subplots()\n ax1.pie(y, labels=x, autopct='%1.1f%%', shadow=True, startangle=90)\n ax1.axis('equal')\n plt.show()\n plt.savefig('mygraph1.png')\n return x, y\n\n# TODO: Don't replace the table if it exists, should be smart enough to handle duplicates\ndef wsbPostgres(df):\n engine = create_engine('postgresql://{db_user}:{db_pass}@{db_host}:5432/{db_server}'.format(\n db_user=config.db_user, db_pass=config.password, db_host=config.db_host, db_server=config.db_name\n ))\n df.to_sql('wsb-test', engine, method='multi', if_exists='replace')\n\n\nresults, ticker_info = searchFlairs('Daily Discussion', 'day')\n\n# Calculate the average compound sentiment for the mentioned ticker comment: https://github.com/cjhutto/vaderSentiment#python-demo-and-code-examples\ndf = pd.DataFrame(ticker_info)\nprint(df)\ndf_new = df.groupby(df['ticker'])['sent'].agg(['mean'])\n\nwsbPostgres(df_new)\n\nprint(df_new)"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"matplotlib.pyplot.savefig"
]
] |
Lucien-MG/torchreinforce
|
[
"5ba852bb255c14140d7bc300a44e60e7b4b572ff"
] |
[
"torchreinforce/agents/temporal_difference.py"
] |
[
"import warnings\nfrom collections import namedtuple, defaultdict\nfrom functools import partial\nfrom typing import Optional, Tuple, List, Callable, Any\n\nimport torch\nfrom torch import Tensor\nfrom torch import distributions\nfrom torch import nn\n\nclass TemporalDifference(nn.Module):\n def __init__(\n self,\n num_actions: int = 4,\n gamma: float = 0.9,\n ) -> None:\n \"\"\"\n MonteCarlo main class\n Args:\n features : Module specifying the input layer to use\n num_actions (int): Number of classes\n \"\"\"\n super().__init__()\n \n def _forward(self, x: Tensor) -> List[Tensor]:\n return x\n\n def forward(self, x: Tensor) -> Tensor:\n outputs = self._forward(x)\n return outputs\n\nclass Sarsa(nn.Module):\n def __init__(\n self,\n num_actions: int,\n epsilon: float = 0.4,\n gamma: float = 0.2,\n alpha: float = 0.4\n ) -> None:\n \"\"\"\n Sarsa main class\n Args:\n num_actions (int): Number of classes\n gamma (float): Reward propagation factor\n \"\"\"\n super().__init__()\n self.num_actions = num_actions\n\n self.epsilon = epsilon\n self.gamma = gamma\n self.alpha = alpha\n\n self.state_values = defaultdict(lambda: torch.zeros(num_actions))\n \n def _forward(self, x: Tensor) -> Tensor:\n state_action_values = self.state_values[x]\n policy = torch.where(state_action_values == torch.max(state_action_values), 1 - self.epsilon + (self.epsilon / self.num_actions), self.epsilon / self.num_actions)\n return policy\n\n def forward(self, x: Tensor) -> Tensor:\n policy = self._forward(x)\n\n if self.training:\n policy = distributions.binomial.Binomial(10, probs=policy).sample()\n\n outputs = torch.argmax(policy)\n \n return outputs\n \n def push(self, state, new_state, action, reward, done):\n discounted_reward = reward + self.gamma * self.state_values[new_state][self(new_state)]\n loss = (discounted_reward - self.state_values[state][action])\n self.state_values[state][action] += self.alpha * loss\n\nclass Qlearning(nn.Module):\n def __init__(\n self,\n num_actions: int,\n epsilon: float = 0.4,\n gamma: float = 0.2,\n alpha: float = 0.4\n ) -> None:\n \"\"\"\n Sarsa main class\n Args:\n num_actions (int): Number of classes\n gamma (float): Reward propagation factor\n \"\"\"\n super().__init__()\n self.num_actions = num_actions\n\n self.epsilon = epsilon\n self.gamma = gamma\n self.alpha = alpha\n\n self.state_values = defaultdict(lambda: torch.zeros(num_actions))\n \n def _forward(self, x: Tensor) -> Tensor:\n state_action_values = self.state_values[x]\n policy = torch.where(state_action_values == torch.max(state_action_values), 1 - self.epsilon + (self.epsilon / self.num_actions), self.epsilon / self.num_actions)\n return policy\n\n def forward(self, x: Tensor) -> Tensor:\n policy = self._forward(x)\n\n if self.training:\n policy = distributions.binomial.Binomial(10, probs=policy).sample()\n\n outputs = torch.argmax(policy)\n \n return outputs\n \n def push(self, state, new_state, action, reward, done):\n best_state_value = torch.argmax(self.state_values[new_state])\n discounted_reward = reward + self.gamma * self.state_values[new_state][best_state_value]\n loss = (discounted_reward - self.state_values[state][action])\n self.state_values[state][action] += self.alpha * loss\n"
] |
[
[
"torch.distributions.binomial.Binomial",
"torch.zeros",
"torch.max",
"torch.argmax"
]
] |
frankling2020/Self-learn-Repo
|
[
"294df18469d6d4ef6d479b1b533f42445cd01ac1"
] |
[
"GNN_PRP/prp_3_21/adgcl/test_transfer_finetune_chem.py"
] |
[
"import argparse\nimport logging\nimport random\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom sklearn.metrics import roc_auc_score\nfrom torch_geometric.data import DataLoader\nfrom tqdm import tqdm\n\nfrom datasets import MoleculeDataset\nfrom transfer.model import GNN_graphpred\nfrom transfer.utils import scaffold_split\n\n\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n np.random.seed(seed)\n random.seed(seed)\n\ndef train(model, device, loader, optimizer, criterion):\n model.train()\n loss_all = 0\n for step, batch in enumerate(loader):\n batch = batch.to(device)\n pred = model(batch.x, batch.edge_index, batch.edge_attr, batch.batch)\n y = batch.y.view(pred.shape).to(torch.float64)\n\n # Whether y is non-null or not.\n is_valid = y ** 2 > 0\n # Loss matrix\n loss_mat = criterion(pred.double(), (y + 1) / 2)\n # loss matrix after removing null target\n loss_mat = torch.where(is_valid, loss_mat, torch.zeros(loss_mat.shape).to(loss_mat.device).to(loss_mat.dtype))\n\n optimizer.zero_grad()\n loss = torch.sum(loss_mat) / torch.sum(is_valid)\n loss.backward()\n\n optimizer.step()\n loss_all += loss.item() * batch.num_graphs\n return loss_all/len(loader)\n\n\ndef eval(model, device, loader):\n model.eval()\n y_true = []\n y_scores = []\n\n for step, batch in enumerate(loader):\n batch = batch.to(device)\n\n with torch.no_grad():\n pred = model(batch.x, batch.edge_index, batch.edge_attr, batch.batch)\n\n y_true.append(batch.y.view(pred.shape))\n y_scores.append(pred)\n\n y_true = torch.cat(y_true, dim=0).cpu().numpy()\n y_scores = torch.cat(y_scores, dim=0).cpu().numpy()\n\n roc_list = []\n for i in range(y_true.shape[1]):\n # AUC is only defined when there is at least one positive data.\n if np.sum(y_true[:, i] == 1) > 0 and np.sum(y_true[:, i] == -1) > 0:\n is_valid = y_true[:, i] ** 2 > 0\n roc_list.append(roc_auc_score((y_true[is_valid, i] + 1) / 2, y_scores[is_valid, i]))\n\n if len(roc_list) < y_true.shape[1]:\n print(\"Some target is missing!\")\n print(\"Missing ratio: {}\".format(1 - float(len(roc_list)) / y_true.shape[1]))\n\n return sum(roc_list) / len(roc_list) # y_true.shape[1]\n\n\ndef arg_parse():\n parser = argparse.ArgumentParser(description='Finetuning Chem after pre-training of graph neural networks')\n parser.add_argument('--device', type=int, default=0,\n help='which gpu to use if any (default: 0)')\n parser.add_argument('--batch_size', type=int, default=32,\n help='input batch size for training (default: 32)')\n parser.add_argument('--epochs', type=int, default=100,\n help='number of epochs to train (default: 100)')\n parser.add_argument('--lr', type=float, default=0.001,\n help='learning rate (default: 0.001)')\n parser.add_argument('--lr_scale', type=float, default=1,\n help='relative learning rate for the feature extraction layer (default: 1)')\n parser.add_argument('--decay', type=float, default=0,\n help='weight decay (default: 0)')\n parser.add_argument('--num_layer', type=int, default=5,\n help='number of GNN message passing layers (default: 5).')\n parser.add_argument('--emb_dim', type=int, default=300,\n help='embedding dimensions (default: 300)')\n parser.add_argument('--dropout_ratio', type=float, default=0.5,\n help='dropout ratio (default: 0.5)')\n parser.add_argument('--graph_pooling', type=str, default=\"mean\",\n help='graph level pooling (sum, mean, max, set2set, attention)')\n parser.add_argument('--JK', type=str, default=\"last\",\n help='how the node features across layers are combined. last, sum, max or concat')\n parser.add_argument('--gnn_type', type=str, default=\"gin\")\n parser.add_argument('--dataset', type=str, default='tox21',\n help='dataset. For now, only classification.')\n parser.add_argument('--input_model_file', type=str, default='',\n help='filename to read the pretrain model (if there is any)')\n parser.add_argument('--seed', type=int, default=0, help=\"Seed for minibatch selection, random initialization.\")\n parser.add_argument('--split', type=str, default=\"scaffold\", help=\"random or scaffold or random_scaffold\")\n parser.add_argument('--eval_train', type=int, default=1, help='evaluating training or not')\n parser.add_argument('--num_workers', type=int, default=4, help='number of workers for dataset loading')\n return parser.parse_args()\n\ndef run(args):\n # Training settings\n\n\n logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(\"Using Device: %s\" % device)\n logging.info(\"Seed: %d\" % args.seed)\n logging.info(args)\n\n setup_seed(args.seed)\n\n # Bunch of classification tasks\n if args.dataset == \"tox21\":\n num_tasks = 12\n elif args.dataset == \"hiv\":\n num_tasks = 1\n elif args.dataset == \"pcba\":\n num_tasks = 128\n elif args.dataset == \"muv\":\n num_tasks = 17\n elif args.dataset == \"bace\":\n num_tasks = 1\n elif args.dataset == \"bbbp\":\n num_tasks = 1\n elif args.dataset == \"toxcast\":\n num_tasks = 617\n elif args.dataset == \"sider\":\n num_tasks = 27\n elif args.dataset == \"clintox\":\n num_tasks = 2\n else:\n raise ValueError(\"Invalid dataset name.\")\n\n # set up dataset\n dataset = MoleculeDataset(\"original_datasets/transfer/\" + args.dataset, dataset=args.dataset)\n\n logging.info(dataset)\n\n if args.split == \"scaffold\":\n smiles_list = pd.read_csv('original_datasets/transfer/' + args.dataset + '/processed/smiles.csv', header=None)[0].tolist()\n train_dataset, valid_dataset, test_dataset = scaffold_split(dataset, smiles_list, null_value=0, frac_train=0.8,\n frac_valid=0.1, frac_test=0.1)\n logging.info(\"scaffold\")\n else:\n raise ValueError(\"Invalid split option.\")\n\n logging.info(train_dataset[0])\n\n train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers)\n val_loader = DataLoader(valid_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)\n test_loader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)\n\n # set up model\n model = GNN_graphpred(args.num_layer, args.emb_dim, num_tasks, JK=args.JK, drop_ratio=args.dropout_ratio,\n graph_pooling=args.graph_pooling, gnn_type=args.gnn_type)\n if not args.input_model_file == \"\":\n model.from_pretrained(args.input_model_file)\n\n model.to(device)\n\n criterion = nn.BCEWithLogitsLoss(reduction=\"none\")\n\n # set up optimizer\n # different learning rate for different part of GNN\n model_param_group = []\n model_param_group.append({\"params\": model.gnn.parameters()})\n if args.graph_pooling == \"attention\":\n model_param_group.append({\"params\": model.pool.parameters(), \"lr\": args.lr * args.lr_scale})\n model_param_group.append({\"params\": model.graph_pred_linear.parameters(), \"lr\": args.lr * args.lr_scale})\n optimizer = optim.Adam(model_param_group, lr=args.lr, weight_decay=args.decay)\n\n train_curve = []\n valid_curve = []\n test_curve = []\n\n\n for epoch in tqdm(range(1, args.epochs + 1)):\n\n\n loss = train(model, device, train_loader, optimizer, criterion)\n logging.info(\"====epoch {} SupervisedLoss {}\".format(epoch, loss))\n\n logging.info(\"====Evaluation\")\n if args.eval_train:\n train_acc = eval(model, device, train_loader)\n else:\n # print(\"omit the training accuracy computation\")\n train_acc = 0\n val_acc = eval(model, device, val_loader)\n test_acc = eval(model, device, test_loader)\n\n logging.info(\"EvalTrain: {} EvalVal: {} EvalTestt: {}\".format (train_acc, val_acc, test_acc))\n\n train_curve.append(train_acc)\n valid_curve.append(val_acc)\n test_curve.append(test_acc)\n\n logging.info(train_curve)\n logging.info(valid_curve)\n logging.info(test_curve)\n\n best_val_epoch = np.argmax(np.array(valid_curve))\n best_train = max(train_curve)\n logging.info('FinishedTraining!')\n logging.info('BestEpoch: {}'.format(best_val_epoch))\n logging.info('BestTrainScore: {}'.format(best_train))\n logging.info('BestValidationScore: {}'.format(valid_curve[best_val_epoch]))\n logging.info('FinalTestScore: {}'.format(test_curve[best_val_epoch]))\n\n return valid_curve[best_val_epoch], test_curve[best_val_epoch]\n\n\n\nif __name__ == \"__main__\":\n args = arg_parse()\n run(args)"
] |
[
[
"torch.optim.Adam",
"sklearn.metrics.roc_auc_score",
"pandas.read_csv",
"numpy.random.seed",
"torch.cat",
"torch.zeros",
"torch.manual_seed",
"torch.sum",
"torch.nn.BCEWithLogitsLoss",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"numpy.array",
"numpy.sum"
]
] |
ChristophReich1996/ECG_Classification
|
[
"d281e0d3df85e7917e7a838529d073cf4b0a71a4"
] |
[
"predict.py"
] |
[
"from typing import List, Tuple, Union, Dict\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport torch_optimizer\nimport numpy as np\nimport os\nfrom tqdm import tqdm\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nfrom ecg_classification import *\nfrom wettbewerb import load_references\n\n\ndef predict_labels(ecg_leads: List[np.ndarray], fs: int, ecg_names: List[str],\n use_pretrained: bool = False, is_binary_classifier: bool = True,\n return_probability: bool = True, device: Union[str, torch.device] = \"cpu\") -> Union[\n List[Tuple[str, str]], List[Tuple[str, str, float]], List[Tuple[str, str, Dict[str, float]]]]:\n \"\"\"\n Function to produce predictions\n :param ecg_leads: (List[np.ndarray]) ECG leads as a list of numpy arrays\n :param fs: (int) Sampling frequency\n :param ecg_names: (List[str]) List of strings with name of each ecg lead\n :param use_pretrained: (bool) If true pre-trained (trained!) model is used\n :param is_binary_classifier: (bool) If true model for two classes is utilized else four class model is used\n :param return_probability: (bool) If true P(AF) is also returned as part of the result tuple (only for binary case)\n :param device: (Union[str, torch.device]) Device to be utilized\n :return: (Union[List[Tuple[str, str]], List[Tuple[str, str, float]]]) List of tuples including name, prediction and\n probability P(AF) if utilized\n \"\"\"\n # Init model\n config = ECGCNN_CONFIG_XL\n config[\"classes\"] = 2 if is_binary_classifier else config[\"classes\"]\n network = ECGCNN(config=config)\n # Train model if utilized\n if not use_pretrained:\n # Load weights pre-trained on the Icentia11k dataset\n try:\n state_dict = torch.load(\"experiments/21_05_2021__12_15_06ECGCNN_XL_icentia11k_dataset/models/best_model.pt\",\n map_location=device)\n except FileNotFoundError as _:\n print(\"State dict not found. Download the state dict of ECG-DualNet XL (Icentia11k). \"\n \"Link in README. Put the state dict into the relative directory \"\n \"experiments/21_05_2021__12_15_06ECGCNN_XL_icentia11k_dataset/models/\")\n exit(1904)\n model_state_dict = network.state_dict()\n state_dict = {key: value for key, value in state_dict.items() if model_state_dict[key].shape == value.shape}\n model_state_dict.update(state_dict)\n network.load_state_dict(model_state_dict)\n # Perform training\n network = _train(network=network, two_classes=is_binary_classifier)\n # Load model\n else:\n if is_binary_classifier:\n try:\n state_dict = torch.load(\"experiments/\"\n \"17_12_2021__03_39_19ECGCNN_XL_physio_net_dataset_challange_two_classes/\"\n \"models/best_model.pt\", map_location=device)\n except FileNotFoundError as _:\n print(\"State dict not found. Download the state dict of ECG-DualNet XL (two class, challange). \"\n \"Link in README. Put the state dict into the relative directory \"\n \"experiments/17_12_2021__03_39_19ECGCNN_XL_physio_net_dataset_challange_two_classes/models/\")\n exit(1904)\n else:\n try:\n state_dict = torch.load(\"experiments/25_05_2021__02_02_11ECGCNN_XL_physio_net_dataset_challange/\"\n \"models/best_model.pt\", map_location=device)\n except FileNotFoundError as _:\n print(\"State dict not found. Download the state dict of ECG-DualNet XL (four class, challange). \"\n \"Link in README. Put the state dict into the relative directory \"\n \"experiments/25_05_2021__02_02_11ECGCNN_XL_physio_net_dataset_challange/models/\")\n exit(1904)\n # Apply state dict\n network.load_state_dict(state_dict)\n # Init dataset for prediction\n dataset = PhysioNetDataset(ecg_leads=ecg_leads, ecg_labels=[\"A\"] * len(ecg_leads), fs=fs,\n augmentation_pipeline=None, two_classes=is_binary_classifier)\n dataset = DataLoader(dataset=dataset, batch_size=1, num_workers=0, pin_memory=False, drop_last=False, shuffle=False)\n # Make prediction\n return _predict(network=network, dataset=dataset, ecg_names=ecg_names, two_classes=is_binary_classifier,\n return_probability=return_probability, device=device)\n\n\ndef _train(network: nn.Module, two_classes: bool) -> nn.Module:\n \"\"\"\n Private function which trains the given model\n :param network: (nn.Module) Model to be trained\n :param two_classes: (bool) If true only two classes are utilized\n :return: (nn.Module) Trained model\n \"\"\"\n # Init data logger\n data_logger = Logger(experiment_path_extension=\"ECGCNN_XL_predict_training\")\n # Init optimizer\n optimizer = torch_optimizer.RAdam(params=network.parameters(), lr=1e-03)\n # Init learning rate schedule\n learning_rate_schedule = torch.optim.lr_scheduler.MultiStepLR(\n optimizer=optimizer, milestones=[1 * 100 // 4, 2 * 100 // 4, 3 * 100 // 4], gamma=0.1)\n # Init datasets\n if two_classes:\n training_split = TRAINING_SPLIT_CHALLANGE_2_CLASSES\n validation_split = VALIDATION_SPLIT_CHALLANGE_2_CLASSES\n else:\n training_split = TRAINING_SPLIT_CHALLANGE\n validation_split = VALIDATION_SPLIT_CHALLANGE\n # Load data\n try:\n ecg_leads, ecg_labels, fs, ecg_names = load_references(\"data/training2017/\")\n except RuntimeError as exception:\n print(\"Download the PhysioNet training data or change path. Link is in the repo. Full PhysioNet is used!\")\n exit(1904)\n training_dataset = DataLoader(\n PhysioNetDataset(ecg_leads=[ecg_leads[index] for index in training_split],\n ecg_labels=[ecg_labels[index] for index in training_split], fs=fs,\n augmentation_pipeline=AugmentationPipeline(\n AUGMENTATION_PIPELINE_CONFIG if not two_classes else AUGMENTATION_PIPELINE_CONFIG_2C),\n two_classes=two_classes),\n batch_size=24, num_workers=20, pin_memory=True, drop_last=False, shuffle=True)\n validation_dataset = DataLoader(\n PhysioNetDataset(ecg_leads=[ecg_leads[index] for index in validation_split],\n ecg_labels=[ecg_labels[index] for index in validation_split], fs=fs,\n augmentation_pipeline=None,\n two_classes=two_classes),\n batch_size=24, num_workers=20, pin_memory=True, drop_last=False, shuffle=False)\n # Init model wrapper\n model_wrapper = ModelWrapper(network=network,\n optimizer=optimizer,\n loss_function=SoftmaxCrossEntropyLoss(\n weight=(1., 1) if two_classes else (0.4, 0.7, 0.9, 0.9)),\n training_dataset=training_dataset,\n validation_dataset=validation_dataset,\n data_logger=data_logger,\n learning_rate_schedule=learning_rate_schedule,\n device=\"cuda\")\n # Perform training\n model_wrapper.train(epochs=100)\n # Load best model\n network.load_state_dict(torch.load(model_wrapper.data_logger.path_models + \"/best_model.pt\"))\n return network\n\n\n@torch.no_grad()\ndef _predict(network: nn.Module, dataset: DataLoader, ecg_names: List[str],\n two_classes: bool, return_probability: bool,\n device: Union[str, torch.device] = \"cpu\") -> Union[List[Tuple[str, str]], List[Tuple[str, str, float]],\n List[Tuple[str, str, Dict[str, float]]]]:\n \"\"\"\n Private function to make predictions\n :param network: (nn.Module) Trained model\n :param dataset: (DataLoader) Dataset to be predicted\n :param ecg_names: (List[str]) Name of each sample\n :param two_classes: (bool) If true only two classes are utilized\n :param return_probability: (bool) If true P(AF) is also returned as part of the result tuple (only for binary case)\n :param device: (Union[str, torch.device]) Device to be utilized\n :return: (Union[List[Tuple[str, str]], List[Tuple[str, str, float]]]) List of tuples including name, prediction and\n probability P(AF) if utilized\n \"\"\"\n # Init list to store predictions\n predictions: Union[List[Tuple[str, str]], List[Tuple[str, str, float]], List[Tuple[str, Dict[str, float]]]] = []\n # Network to device\n network.to(device)\n # Network into eval mode\n network.eval()\n # Init progress bar\n progress_bar = tqdm(total=len(dataset))\n # Prediction loop\n for name, data in zip(ecg_names, dataset):\n # Update progress bar\n progress_bar.update(n=1)\n # Unpack data\n ecg_lead, spectrogram, _ = data\n # Data to cuda\n ecg_lead = ecg_lead.to(device)\n spectrogram = spectrogram.to(device)\n # Make prediction\n prediction: torch.Tensor = network(ecg_lead, spectrogram)\n # Threshold prediction\n prediction_argmax = prediction.argmax(dim=-1)\n # Construct prediction\n if return_probability:\n if two_classes:\n predictions.append((name, _get_prediction_name(prediction=prediction_argmax, two_classes=two_classes),\n prediction[..., -1].item()))\n else:\n predictions.append((name, _get_prediction_name(prediction=prediction_argmax, two_classes=two_classes), dict(zip([\"N\", \"O\", \"A\", \"~\"], prediction.reshape(-1).tolist()))))\n else:\n predictions.append((name, _get_prediction_name(prediction=prediction_argmax, two_classes=two_classes)))\n # Close progress bar\n progress_bar.close()\n return predictions\n\n\ndef _get_prediction_name(prediction: torch.Tensor, two_classes: bool) -> str:\n \"\"\"\n Function produces string prediction from raw class prediction\n :param prediction: (torch.Tensor) Prediction of the shape [batch size = 1]\n :param two_classes: (bool) If true two class case is utilized\n :return: (str) String including the class name\n \"\"\"\n # Check batch size\n assert prediction.shape[0] == 1, \"Only a batch size of one is supported.\"\n # Two class case\n if two_classes:\n if int(prediction.item()) == 0:\n return \"N\"\n elif int(prediction.item()) == 1:\n return \"A\"\n else:\n raise RuntimeError(\"Wrong prediction encountered\")\n # Four class case\n if int(prediction.item()) == 0:\n return \"N\"\n elif int(prediction.item()) == 1:\n return \"O\"\n elif int(prediction.item()) == 2:\n return \"A\"\n elif int(prediction.item()) == 3:\n return \"~\"\n else:\n raise RuntimeError(\"Wrong prediction encountered\")\n"
] |
[
[
"torch.optim.lr_scheduler.MultiStepLR",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.load"
]
] |
sagar1993/BrainNet_server
|
[
"70972f4ccd06bb2615afc19a8e077fb9e39470f3"
] |
[
"service/feature_extractor.py"
] |
[
"import numpy as np\nfrom pyedflib import EdfReader\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\n\n\ndef featureVecs(out, sample_size):\n # sample_size = 120\n fVec = np.zeros((sample_size, 6), dtype=float)\n\n i = 0\n j = 0\n while i < len(out) and j < sample_size:\n fVec[j][:6] = out[i:i + 6]\n # print 'fVec : ', fVec[j][:5], out[i:i+5], i\n i = i + 6\n j = j + 1\n return fVec\n\n\ndef FeatureExt(signal, signal_len):\n # in seconds\n # signal_len = 120;\n # sample rate in HZ\n SR = 160;\n out = np.zeros((signal_len * 6), dtype=float);\n S_FFT = np.zeros((SR));\n\n for i in range(signal_len):\n offset = (i) * SR\n S_FFT[0:SR] = FFT(signal[offset:offset + SR])\n out[i * 6:(i * 6) + 5 + 1] = S_FFT[8:14]\n\n # plot_graph(out)\n featureVectors = featureVecs(out, signal_len)\n return featureVectors\n\n\ndef FFT(signal):\n L = len(signal)\n Y = np.fft.fft(signal, 1);\n # y = 2 * abs(Y(1:NFFT / 2 + 1));\n y = 2 * abs(Y);\n return y\n\n\ndef NaiveBayes(train_arr, test_arr, train_size, test_size):\n # sample_size = 120\n labels = np.ones((train_size + test_size), dtype=float)\n labels[train_size:train_size + test_size - 1] = 0\n\n ### Al data\n train_data = np.zeros((train_size + test_size, 6), dtype=float)\n train_data[0:train_size - 1][:] = train_arr[0:train_size - 1][:]\n train_data[train_size:train_size + test_size - 1][:] = test_arr[0:test_size - 1][:]\n\n gnb = GaussianNB()\n y_pred = gnb.fit(train_data, labels).predict(train_data)\n mat = confusion_matrix(labels, y_pred)\n # print 'Confusion Matrix: ', mat\n\n if (mat[0][0] > mat[0][1]) and (mat[1][1] > mat[1][0]):\n authenticated = 0\n else:\n authenticated = 1\n return authenticated\n\n\ndef get_feature(edf_file):\n reader = EdfReader(edf_file)\n n = reader.signals_in_file\n buffer = np.zeros((n, reader.getNSamples()[0]))\n for i in np.arange(n):\n buffer[i, :] = reader.readSignal(i)\n\n signal = list(buffer[0])\n\n signal_len = 64\n\n return FeatureExt(signal, signal_len)\n\ndef get_feature_signal(signal):\n\n signal_len = 64\n\n return FeatureExt(signal, signal_len)"
] |
[
[
"sklearn.naive_bayes.GaussianNB",
"numpy.fft.fft",
"numpy.arange",
"sklearn.metrics.confusion_matrix",
"numpy.ones",
"numpy.zeros"
]
] |
ivanB1975/scipy
|
[
"8fed46cd7e7b5b63eb101c5d5d521ff7d7bac9b9"
] |
[
"setup.py"
] |
[
"#!/usr/bin/env python\n\"\"\"SciPy: Scientific Library for Python\n\nSciPy (pronounced \"Sigh Pie\") is open-source software for mathematics,\nscience, and engineering. The SciPy library\ndepends on NumPy, which provides convenient and fast N-dimensional\narray manipulation. The SciPy library is built to work with NumPy\narrays, and provides many user-friendly and efficient numerical\nroutines such as routines for numerical integration and optimization.\nTogether, they run on all popular operating systems, are quick to\ninstall, and are free of charge. NumPy and SciPy are easy to use,\nbut powerful enough to be depended upon by some of the world's\nleading scientists and engineers. If you need to manipulate\nnumbers on a computer and display or publish the results,\ngive SciPy a try!\n\n\"\"\"\n\nDOCLINES = (__doc__ or '').split(\"\\n\")\n\nimport os\nimport sys\nimport subprocess\nimport textwrap\nimport warnings\nimport sysconfig\nfrom distutils.version import LooseVersion\n\n\nif sys.version_info[:2] < (3, 7):\n raise RuntimeError(\"Python version >= 3.7 required.\")\n\nimport builtins\n\n\nCLASSIFIERS = \"\"\"\\\nDevelopment Status :: 5 - Production/Stable\nIntended Audience :: Science/Research\nIntended Audience :: Developers\nLicense :: OSI Approved :: BSD License\nProgramming Language :: C\nProgramming Language :: Python\nProgramming Language :: Python :: 3\nProgramming Language :: Python :: 3.7\nProgramming Language :: Python :: 3.8\nProgramming Language :: Python :: 3.9\nTopic :: Software Development\nTopic :: Scientific/Engineering\nOperating System :: Microsoft :: Windows\nOperating System :: POSIX\nOperating System :: Unix\nOperating System :: MacOS\n\n\"\"\"\n\nMAJOR = 1\nMINOR = 7\nMICRO = 0\nISRELEASED = False\nVERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)\n\n\n# Return the git revision as a string\ndef git_version():\n def _minimal_ext_cmd(cmd):\n # construct minimal environment\n env = {}\n for k in ['SYSTEMROOT', 'PATH']:\n v = os.environ.get(k)\n if v is not None:\n env[k] = v\n # LANGUAGE is used on win32\n env['LANGUAGE'] = 'C'\n env['LANG'] = 'C'\n env['LC_ALL'] = 'C'\n out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0]\n return out\n\n try:\n out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])\n GIT_REVISION = out.strip().decode('ascii')\n except OSError:\n GIT_REVISION = \"Unknown\"\n\n return GIT_REVISION\n\n\n# BEFORE importing setuptools, remove MANIFEST. Otherwise it may not be\n# properly updated when the contents of directories change (true for distutils,\n# not sure about setuptools).\nif os.path.exists('MANIFEST'):\n os.remove('MANIFEST')\n\n# This is a bit hackish: we are setting a global variable so that the main\n# scipy __init__ can detect if it is being loaded by the setup routine, to\n# avoid attempting to load components that aren't built yet. While ugly, it's\n# a lot more robust than what was previously being used.\nbuiltins.__SCIPY_SETUP__ = True\n\n\ndef get_version_info():\n # Adding the git rev number needs to be done inside\n # write_version_py(), otherwise the import of scipy.version messes\n # up the build under Python 3.\n FULLVERSION = VERSION\n if os.path.exists('.git'):\n GIT_REVISION = git_version()\n elif os.path.exists('scipy/version.py'):\n # must be a source distribution, use existing version file\n # load it as a separate module to not load scipy/__init__.py\n import runpy\n ns = runpy.run_path('scipy/version.py')\n GIT_REVISION = ns['git_revision']\n else:\n GIT_REVISION = \"Unknown\"\n\n if not ISRELEASED:\n FULLVERSION += '.dev0+' + GIT_REVISION[:7]\n\n return FULLVERSION, GIT_REVISION\n\n\ndef write_version_py(filename='scipy/version.py'):\n cnt = \"\"\"\n# THIS FILE IS GENERATED FROM SCIPY SETUP.PY\nshort_version = '%(version)s'\nversion = '%(version)s'\nfull_version = '%(full_version)s'\ngit_revision = '%(git_revision)s'\nrelease = %(isrelease)s\n\nif not release:\n version = full_version\n\"\"\"\n FULLVERSION, GIT_REVISION = get_version_info()\n\n a = open(filename, 'w')\n try:\n a.write(cnt % {'version': VERSION,\n 'full_version': FULLVERSION,\n 'git_revision': GIT_REVISION,\n 'isrelease': str(ISRELEASED)})\n finally:\n a.close()\n\n\ntry:\n from sphinx.setup_command import BuildDoc\n HAVE_SPHINX = True\nexcept Exception:\n HAVE_SPHINX = False\n\nif HAVE_SPHINX:\n class ScipyBuildDoc(BuildDoc):\n \"\"\"Run in-place build before Sphinx doc build\"\"\"\n def run(self):\n ret = subprocess.call([sys.executable, sys.argv[0], 'build_ext', '-i'])\n if ret != 0:\n raise RuntimeError(\"Building Scipy failed!\")\n BuildDoc.run(self)\n\n\ndef check_submodules():\n \"\"\" verify that the submodules are checked out and clean\n use `git submodule update --init`; on failure\n \"\"\"\n if not os.path.exists('.git'):\n return\n with open('.gitmodules') as f:\n for l in f:\n if 'path' in l:\n p = l.split('=')[-1].strip()\n if not os.path.exists(p):\n raise ValueError('Submodule %s missing' % p)\n\n\n proc = subprocess.Popen(['git', 'submodule', 'status'],\n stdout=subprocess.PIPE)\n status, _ = proc.communicate()\n status = status.decode(\"ascii\", \"replace\")\n for line in status.splitlines():\n if line.startswith('-') or line.startswith('+'):\n raise ValueError('Submodule not clean: %s' % line)\n\n\nclass concat_license_files():\n \"\"\"Merge LICENSE.txt and LICENSES_bundled.txt for sdist creation\n\n Done this way to keep LICENSE.txt in repo as exact BSD 3-clause (see\n NumPy gh-13447). This makes GitHub state correctly how SciPy is licensed.\n \"\"\"\n def __init__(self):\n self.f1 = 'LICENSE.txt'\n self.f2 = 'LICENSES_bundled.txt'\n\n def __enter__(self):\n \"\"\"Concatenate files and remove LICENSES_bundled.txt\"\"\"\n with open(self.f1, 'r') as f1:\n self.bsd_text = f1.read()\n\n with open(self.f1, 'a') as f1:\n with open(self.f2, 'r') as f2:\n self.bundled_text = f2.read()\n f1.write('\\n\\n')\n f1.write(self.bundled_text)\n\n def __exit__(self, exception_type, exception_value, traceback):\n \"\"\"Restore content of both files\"\"\"\n with open(self.f1, 'w') as f:\n f.write(self.bsd_text)\n\n\nfrom distutils.command.sdist import sdist\nclass sdist_checked(sdist):\n \"\"\" check submodules on sdist to prevent incomplete tarballs \"\"\"\n def run(self):\n check_submodules()\n with concat_license_files():\n sdist.run(self)\n\n\ndef get_build_ext_override():\n \"\"\"\n Custom build_ext command to tweak extension building.\n \"\"\"\n from numpy.distutils.command.build_ext import build_ext as old_build_ext\n\n class build_ext(old_build_ext):\n def finalize_options(self):\n super().finalize_options()\n\n # Disable distutils parallel build, due to race conditions\n # in numpy.distutils (Numpy issue gh-15957)\n if self.parallel:\n print(\"NOTE: -j build option not supportd. Set NPY_NUM_BUILD_JOBS=4 \"\n \"for parallel build.\")\n self.parallel = None\n\n def build_extension(self, ext):\n # When compiling with GNU compilers, use a version script to\n # hide symbols during linking.\n if self.__is_using_gnu_linker(ext):\n export_symbols = self.get_export_symbols(ext)\n text = '{global: %s; local: *; };' % (';'.join(export_symbols),)\n\n script_fn = os.path.join(self.build_temp, 'link-version-{}.map'.format(ext.name))\n with open(script_fn, 'w') as f:\n f.write(text)\n # line below fixes gh-8680\n ext.extra_link_args = [arg for arg in ext.extra_link_args if not \"version-script\" in arg]\n ext.extra_link_args.append('-Wl,--version-script=' + script_fn)\n\n # Allow late configuration\n hooks = getattr(ext, '_pre_build_hook', ())\n _run_pre_build_hooks(hooks, (self, ext))\n\n old_build_ext.build_extension(self, ext)\n\n def __is_using_gnu_linker(self, ext):\n if not sys.platform.startswith('linux'):\n return False\n\n # Fortran compilation with gfortran uses it also for\n # linking. For the C compiler, we detect gcc in a similar\n # way as distutils does it in\n # UnixCCompiler.runtime_library_dir_option\n if ext.language == 'f90':\n is_gcc = (self._f90_compiler.compiler_type in ('gnu', 'gnu95'))\n elif ext.language == 'f77':\n is_gcc = (self._f77_compiler.compiler_type in ('gnu', 'gnu95'))\n else:\n is_gcc = False\n if self.compiler.compiler_type == 'unix':\n cc = sysconfig.get_config_var(\"CC\")\n if not cc:\n cc = \"\"\n compiler_name = os.path.basename(cc.split(\" \")[0])\n is_gcc = \"gcc\" in compiler_name or \"g++\" in compiler_name\n return is_gcc and sysconfig.get_config_var('GNULD') == 'yes'\n\n return build_ext\n\n\ndef get_build_clib_override():\n \"\"\"\n Custom build_clib command to tweak library building.\n \"\"\"\n from numpy.distutils.command.build_clib import build_clib as old_build_clib\n\n class build_clib(old_build_clib):\n def finalize_options(self):\n super().finalize_options()\n\n # Disable parallelization (see build_ext above)\n self.parallel = None\n\n def build_a_library(self, build_info, lib_name, libraries):\n # Allow late configuration\n hooks = build_info.get('_pre_build_hook', ())\n _run_pre_build_hooks(hooks, (self, build_info))\n old_build_clib.build_a_library(self, build_info, lib_name, libraries)\n\n return build_clib\n\n\ndef _run_pre_build_hooks(hooks, args):\n \"\"\"Call a sequence of pre-build hooks, if any\"\"\"\n if hooks is None:\n hooks = ()\n elif not hasattr(hooks, '__iter__'):\n hooks = (hooks,)\n for hook in hooks:\n hook(*args)\n\n\ndef generate_cython():\n cwd = os.path.abspath(os.path.dirname(__file__))\n print(\"Cythonizing sources\")\n p = subprocess.call([sys.executable,\n os.path.join(cwd, 'tools', 'cythonize.py'),\n 'scipy'],\n cwd=cwd)\n if p != 0:\n # Could be due to a too old pip version and build isolation, check that\n try:\n # Note, pip may not be installed or not have been used\n import pip\n if LooseVersion(pip.__version__) < LooseVersion('18.0.0'):\n raise RuntimeError(\"Cython not found or too old. Possibly due \"\n \"to `pip` being too old, found version {}, \"\n \"needed is >= 18.0.0.\".format(\n pip.__version__))\n else:\n raise RuntimeError(\"Running cythonize failed!\")\n except ImportError:\n raise RuntimeError(\"Running cythonize failed!\")\n\n\ndef parse_setuppy_commands():\n \"\"\"Check the commands and respond appropriately. Disable broken commands.\n\n Return a boolean value for whether or not to run the build or not (avoid\n parsing Cython and template files if False).\n \"\"\"\n args = sys.argv[1:]\n\n if not args:\n # User forgot to give an argument probably, let setuptools handle that.\n return True\n\n info_commands = ['--help-commands', '--name', '--version', '-V',\n '--fullname', '--author', '--author-email',\n '--maintainer', '--maintainer-email', '--contact',\n '--contact-email', '--url', '--license', '--description',\n '--long-description', '--platforms', '--classifiers',\n '--keywords', '--provides', '--requires', '--obsoletes']\n\n for command in info_commands:\n if command in args:\n return False\n\n # Note that 'alias', 'saveopts' and 'setopt' commands also seem to work\n # fine as they are, but are usually used together with one of the commands\n # below and not standalone. Hence they're not added to good_commands.\n good_commands = ('develop', 'sdist', 'build', 'build_ext', 'build_py',\n 'build_clib', 'build_scripts', 'bdist_wheel', 'bdist_rpm',\n 'bdist_wininst', 'bdist_msi', 'bdist_mpkg',\n 'build_sphinx')\n\n for command in good_commands:\n if command in args:\n return True\n\n # The following commands are supported, but we need to show more\n # useful messages to the user\n if 'install' in args:\n print(textwrap.dedent(\"\"\"\n Note: for reliable uninstall behaviour and dependency installation\n and uninstallation, please use pip instead of using\n `setup.py install`:\n\n - `pip install .` (from a git repo or downloaded source\n release)\n - `pip install scipy` (last SciPy release on PyPI)\n\n \"\"\"))\n return True\n\n if '--help' in args or '-h' in sys.argv[1]:\n print(textwrap.dedent(\"\"\"\n SciPy-specific help\n -------------------\n\n To install SciPy from here with reliable uninstall, we recommend\n that you use `pip install .`. To install the latest SciPy release\n from PyPI, use `pip install scipy`.\n\n For help with build/installation issues, please ask on the\n scipy-user mailing list. If you are sure that you have run\n into a bug, please report it at https://github.com/scipy/scipy/issues.\n\n Setuptools commands help\n ------------------------\n \"\"\"))\n return False\n\n\n # The following commands aren't supported. They can only be executed when\n # the user explicitly adds a --force command-line argument.\n bad_commands = dict(\n test=\"\"\"\n `setup.py test` is not supported. Use one of the following\n instead:\n\n - `python runtests.py` (to build and test)\n - `python runtests.py --no-build` (to test installed scipy)\n - `>>> scipy.test()` (run tests for installed scipy\n from within an interpreter)\n \"\"\",\n upload=\"\"\"\n `setup.py upload` is not supported, because it's insecure.\n Instead, build what you want to upload and upload those files\n with `twine upload -s <filenames>` instead.\n \"\"\",\n upload_docs=\"`setup.py upload_docs` is not supported\",\n easy_install=\"`setup.py easy_install` is not supported\",\n clean=\"\"\"\n `setup.py clean` is not supported, use one of the following instead:\n\n - `git clean -xdf` (cleans all files)\n - `git clean -Xdf` (cleans all versioned files, doesn't touch\n files that aren't checked into the git repo)\n \"\"\",\n check=\"`setup.py check` is not supported\",\n register=\"`setup.py register` is not supported\",\n bdist_dumb=\"`setup.py bdist_dumb` is not supported\",\n bdist=\"`setup.py bdist` is not supported\",\n flake8=\"`setup.py flake8` is not supported, use flake8 standalone\",\n )\n bad_commands['nosetests'] = bad_commands['test']\n for command in ('upload_docs', 'easy_install', 'bdist', 'bdist_dumb',\n 'register', 'check', 'install_data', 'install_headers',\n 'install_lib', 'install_scripts', ):\n bad_commands[command] = \"`setup.py %s` is not supported\" % command\n\n for command in bad_commands.keys():\n if command in args:\n print(textwrap.dedent(bad_commands[command]) +\n \"\\nAdd `--force` to your command to use it anyway if you \"\n \"must (unsupported).\\n\")\n sys.exit(1)\n\n # Commands that do more than print info, but also don't need Cython and\n # template parsing.\n other_commands = ['egg_info', 'install_egg_info', 'rotate']\n for command in other_commands:\n if command in args:\n return False\n\n # If we got here, we didn't detect what setup.py command was given\n warnings.warn(\"Unrecognized setuptools command ('{}'), proceeding with \"\n \"generating Cython sources and expanding templates\".format(\n ' '.join(sys.argv[1:])))\n return True\n\ndef check_setuppy_command():\n run_build = parse_setuppy_commands()\n if run_build:\n try:\n import numpy\n import pybind11\n except ImportError as exc: # We do not have our build deps installed\n print(textwrap.dedent(\n \"\"\"Error: '%s' must be installed before running the build.\n \"\"\"\n % (exc.name,)))\n sys.exit(1)\n\n return run_build\n\ndef configuration(parent_package='', top_path=None):\n from scipy._build_utils.system_info import get_info, NotFoundError\n from numpy.distutils.misc_util import Configuration\n\n lapack_opt = get_info('lapack_opt')\n\n if not lapack_opt:\n if sys.platform == \"darwin\":\n msg = ('No BLAS/LAPACK libraries found. '\n 'Note: Accelerate is no longer supported.')\n else:\n msg = 'No BLAS/LAPACK libraries found.'\n msg += (\"\\n\"\n \"To build Scipy from sources, BLAS & LAPACK libraries \"\n \"need to be installed.\\n\"\n \"See site.cfg.example in the Scipy source directory and\\n\"\n \"https://docs.scipy.org/doc/scipy/reference/building/index.html \"\n \"for details.\")\n raise NotFoundError(msg)\n\n config = Configuration(None, parent_package, top_path)\n config.set_options(ignore_setup_xxx_py=True,\n assume_default_configuration=True,\n delegate_options_to_subpackages=True,\n quiet=True)\n\n config.add_subpackage('scipy')\n config.add_data_files(('scipy', '*.txt'))\n\n config.get_version('scipy/version.py')\n\n return config\n\n\ndef setup_package():\n # Rewrite the version file every time\n write_version_py()\n\n cmdclass = {'sdist': sdist_checked}\n if HAVE_SPHINX:\n cmdclass['build_sphinx'] = ScipyBuildDoc\n\n metadata = dict(\n name='scipy',\n maintainer=\"SciPy Developers\",\n maintainer_email=\"scipy-dev@python.org\",\n description=DOCLINES[0],\n long_description=\"\\n\".join(DOCLINES[2:]),\n url=\"https://www.scipy.org\",\n download_url=\"https://github.com/scipy/scipy/releases\",\n project_urls={\n \"Bug Tracker\": \"https://github.com/scipy/scipy/issues\",\n \"Documentation\": \"https://docs.scipy.org/doc/scipy/reference/\",\n \"Source Code\": \"https://github.com/scipy/scipy\",\n },\n license='BSD',\n cmdclass=cmdclass,\n classifiers=[_f for _f in CLASSIFIERS.split('\\n') if _f],\n platforms=[\"Windows\", \"Linux\", \"Solaris\", \"Mac OS-X\", \"Unix\"],\n test_suite='nose.collector',\n install_requires=[\n 'numpy>=1.16.5',\n ],\n python_requires='>=3.7',\n )\n\n if \"--force\" in sys.argv:\n run_build = True\n sys.argv.remove('--force')\n else:\n # Raise errors for unsupported commands, improve help output, etc.\n run_build = check_setuppy_command()\n\n # Disable OSX Accelerate, it has too old LAPACK\n os.environ['ACCELERATE'] = 'None'\n\n # This import is here because it needs to be done before importing setup()\n # from numpy.distutils, but after the MANIFEST removing and sdist import\n # higher up in this file.\n from setuptools import setup\n\n if run_build:\n from numpy.distutils.core import setup\n\n # Customize extension building\n cmdclass['build_ext'] = get_build_ext_override()\n cmdclass['build_clib'] = get_build_clib_override()\n\n cwd = os.path.abspath(os.path.dirname(__file__))\n if not os.path.exists(os.path.join(cwd, 'PKG-INFO')):\n # Generate Cython sources, unless building from source release\n generate_cython()\n\n metadata['configuration'] = configuration\n else:\n # Don't import numpy here - non-build actions are required to succeed\n # without NumPy for example when pip is used to install Scipy when\n # NumPy is not yet present in the system.\n\n # Version number is added to metadata inside configuration() if build\n # is run.\n metadata['version'] = get_version_info()[0]\n\n setup(**metadata)\n\n\nif __name__ == '__main__':\n setup_package()\n"
] |
[
[
"numpy.distutils.misc_util.Configuration",
"numpy.distutils.core.setup",
"numpy.distutils.command.build_clib.build_clib.build_a_library",
"scipy._build_utils.system_info.get_info",
"scipy._build_utils.system_info.NotFoundError",
"numpy.distutils.command.build_ext.build_ext.build_extension"
]
] |
amessadiqi/humorDetection
|
[
"998a46219b0ef593d7ad416a649f232e6a79c2c2"
] |
[
"HumorDetector.py"
] |
[
"import pandas as pd\nfrom data_processing.DataProcessor import DataProcessor\nfrom humor_features.HumorFeatures import HumorFeatures\nfrom humor_model.Models import Models\nfrom prediction_server.app import app\n\n\nclass HumorDetector:\n def __init__(self, dataset = None):\n if isinstance(dataset, pd.DataFrame):\n print('Calculating the features...')\n self.dataset = HumorFeatures(dataset).getAllFeatures()\n print('Processing the dataset...')\n self.dataset = DataProcessor(dataset=self.dataset).get_processed_df()\n\n\n def get_processed_dataset(self):\n return self.dataset\n\n\n def predict(self , val , method):\n data = pd.DataFrame({\"text\": val}, index=[\"text\"])\n X = DataProcessor(\n HumorFeatures(data).getAllFeatures()\n ).get_processed_df()\n \n return Models().predict(method=method , val=X)\n\n\n def performance_overview(self):\n Models(dataset=self.dataset).displayScores()\n\n\n def prediction_server(self, host, port):\n app.run(host=host, port=port)\n"
] |
[
[
"pandas.DataFrame"
]
] |
Jakob-Unfried/jax
|
[
"bec943cee0234178a9143a0447b224a5faa9fbdc"
] |
[
"tests/api_test.py"
] |
[
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport collections\nimport collections.abc\nfrom contextlib import contextmanager\nimport copy\nimport enum\nfrom functools import partial\nimport operator\nimport re\nimport subprocess\nimport sys\nimport types\nimport unittest\nimport warnings\nimport weakref\nimport functools\nimport itertools as it\nimport operator as op\n\nfrom absl import logging\nfrom absl.testing import absltest, parameterized\nimport numpy as np\n\nimport concurrent.futures\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\nfrom jax import core, dtypes, lax\nfrom jax._src import api\nfrom jax.core import Primitive\nfrom jax.errors import UnexpectedTracerError\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters.sharded_jit import PartitionSpec as P\nimport jax._src.lib\nfrom jax._src.lib import xla_client\nfrom jax._src import test_util as jtu\nfrom jax import tree_util\nfrom jax import linear_util as lu\nimport jax._src.util\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n\n\npython_version = (sys.version_info[0], sys.version_info[1])\nnumpy_version = tuple(map(int, np.__version__.split('.')[:3]))\n\n\nclass CPPJitTest(jtu.BufferDonationTestCase):\n \"\"\"Shared tests between the Python and the C++ jax,jit implementations.\n\n Because the Python implementation supports more features, we need to have the\n Python tests that extend the C++ tests (and not the other way around).\n \"\"\"\n\n @property\n def jit(self):\n # Right now, the CPP tests also test the Python code-path when jaxlib is\n # too old.\n # TODO(jblespiau,phawkins): Remove this when jaxlib has been released.\n # This is in the future, because we are making a breaking change to\n # Tensorflow.\n return api._cpp_jit\n\n def test_jit_of_noncallable(self):\n self.assertRaisesRegex(TypeError, \"Expected a callable value.*\",\n lambda: self.jit(3))\n\n def test_jit_of_generator(self):\n\n def gen(x):\n yield x\n\n self.assertRaisesRegex(TypeError,\n \"Expected a function, got a generator function.*\",\n lambda: self.jit(gen))\n\n @parameterized.parameters([\n # Integer support\n (1, 2, 3, 4, 5),\n # Numpy array support\n (\n np.asarray(1, np.int32),\n np.asarray(2, np.int32),\n np.asarray(3, np.int32),\n np.asarray(4, np.int32),\n np.asarray(5, np.int32),\n ),\n ])\n def test_jit_static_args(self, one, two, three, four, five):\n side = []\n\n def f(x, y, z, flag=False, flag2=False):\n del flag2 # unused\n assert flag\n side.append(None)\n return 100 * x + 10 * y + z\n\n f1 = self.jit(f, static_argnums=(3, 4))\n assert f1(one, two, three, True, False) == 123\n assert len(side) == 1\n assert f1(one, two, three, True, False) == 123\n assert len(side) == 1 # Obvious cache hit.\n assert f1(two, one, three, True, False) == 213\n assert len(side) == 1 # Should cache hit because same signature.\n assert f1(two, one, three, True, True) == 213\n assert len(side) == 2\n\n side[:] = []\n f2 = self.jit(f, static_argnums=(0, 2, 3, 4))\n assert f2(1, 2, 3, True, False) == 123\n assert len(side) == 1\n assert f2(1, 3, 3, True, False) == 133\n assert len(side) == 1\n assert f2(2, 2, 3, True, False) == 223\n assert len(side) == 2\n assert f2(2, 4, 3, True, False) == 243\n assert len(side) == 2\n assert f2(2, 4, 3, True, True) == 243\n assert len(side) == 3\n assert f2(2, 5, 3, True, True) == 253\n assert len(side) == 3\n\n def test_static_args_equality(self):\n class A():\n\n def __hash__(self):\n return 1\n\n def __eq__(self, other):\n return isinstance(other, A)\n\n side = []\n def f(x, static_arg):\n del static_arg\n side.append(None)\n return x * 100\n\n f1 = self.jit(f, static_argnums=(1,))\n\n self.assertEqual(f1(1, A()), 100)\n self.assertLen(side, 1)\n self.assertEqual(f1(1, A()), 100)\n self.assertLen(side, 1)\n if self.jit == api._cpp_jit:\n f1_cpp = getattr(f1, \"_cpp_jitted_f\", f1)\n self.assertEqual(f1_cpp._cache_size(), 1)\n\n @parameterized.parameters([\n (1, 2, 3),\n (\n np.asarray(1, np.int32),\n np.asarray(2, np.int32),\n np.asarray(3, np.int32),\n ),\n ])\n def test_jit_kwargs(self, one, two, three):\n side = []\n # For the CPP jit, we need to clear the cache to prevent cache hits between\n # parameterized tests.\n if hasattr(self.jit, \"cache_clear\"):\n self.jit.cache_clear()\n\n def f(x, y, z):\n side.append(None)\n return 100 * x + 10 * y + z\n\n f = self.jit(f)\n assert f(one, two, three) == 123\n assert len(side) == 1\n assert f(one, two, three) == 123\n assert len(side) == 1\n\n assert f(one, two, z=three) == 123\n assert len(side) == 2 # actually recompiles from kwarg\n assert f(one, two, z=three) == 123\n assert len(side) == 2 # but should still cache\n\n f(one, two, z=np.zeros(3)) # doesn't crash\n if config.x64_enabled:\n # In the above call, three is of a new type (int64), thus it should\n # trigger a new compilation.\n assert len(side) == 3\n\n def test_jit_device(self):\n device = jax.devices()[-1]\n x = self.jit(lambda x: x, device=device)(3.)\n self.assertIsInstance(x, xla.DeviceArray)\n self.assertEqual(x.device_buffer.device(), device)\n\n def test_complex_support(self):\n self.assertEqual(self.jit(lambda x: x + 1)(1 + 1j), 2 + 1j)\n\n def test_jit_with_many_args_works(self):\n\n @self.jit\n def f(args_list):\n return sum(args_list)\n\n self.assertEqual(f(list(range(500))), sum(range(500)))\n\n # Jit and Donate arguments\n\n def test_jit_donate_argnums_warning_raised(self):\n x = jnp.array([1.0, 2.0], jnp.float32)\n y = jnp.array([1, 2], jnp.int32)\n f = self.jit(lambda x, y: x.sum() + y.sum(), donate_argnums=(0, 1))\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n f(x, y)\n\n self.assertLen(w, 1)\n self.assertTrue(issubclass(w[-1].category, UserWarning))\n self.assertIn(\n \"Some donated buffers were not usable: f32[2]{0}, s32[2]{0}\",\n str(w[-1].message))\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jit_donate_argnums_invalidates_input(self):\n # We can't just use `lambda x: x` because JAX simplifies this away to an\n # empty XLA computation.\n move = self.jit(lambda x: x + x - x, donate_argnums=0)\n x = jnp.ones([])\n y = move(x)\n self.assertDeleted(x)\n self.assertEqual(y, 1.)\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jit_donate_argnums_static_argnums(self):\n jit_fun = self.jit(\n lambda a, b, c, d: ((a + b + c), (a + b + d)),\n static_argnums=(0, 1),\n donate_argnums=(2, 3))\n\n c = jax.device_put(jnp.array([1., 1.]))\n d = jax.device_put(jnp.array([1., 1., 1.]))\n e, f = jit_fun(1, 2, c, d)\n np.testing.assert_allclose(e, jnp.array([4., 4.]))\n np.testing.assert_allclose(f, jnp.array([4., 4., 4.]))\n self.assertDeleted(c)\n self.assertDeleted(d)\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jnp_array_copy(self):\n # https://github.com/google/jax/issues/3412\n\n @partial(self.jit, donate_argnums=(0,))\n def _test(array):\n return array.at[0].set(77)\n\n x = jnp.asarray([0, 1])\n x_copy = jnp.array(x, copy=True)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n _test(x) # donation\n\n # Gives: RuntimeError: Invalid argument: CopyToHostAsync() called on invalid buffer.\n print(x_copy) # doesn't crash\n\n def test_jit_global_cache(self):\n def f(x):\n assert python_should_be_executing\n return x\n\n python_should_be_executing = True\n self.jit(f)(2)\n python_should_be_executing = False\n self.jit(f)(3)\n\n def test_jit_shallow_copy(self):\n def f(x):\n return copy.copy(x)\n self.jit(f)(1)\n\n def test_jit_deep_copy(self):\n def f(x):\n return copy.deepcopy(x)\n self.jit(f)(1)\n\n def test_disable_jit(self):\n effects = []\n\n @self.jit\n def f(x):\n effects.append(1)\n return x\n\n with api.disable_jit():\n f(2)\n f(2)\n assert len(effects) == 2\n\n f(2)\n f(2)\n assert len(effects) == 3\n\n def test_static_argnum_on_method(self):\n\n class A:\n\n @functools.partial(self.jit, static_argnums=(0,))\n def my_func_jit(self, x):\n return x+2\n\n A().my_func_jit(3)\n\n def test_static_argnum_on_static_method_is_not_supported(self):\n with self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\n\n class A:\n\n @functools.partial(self.jit, static_argnums=(0,))\n @classmethod\n def my_classmethod_jit(cls, x):\n return x+2\n\n def test_staticmethod_is_not_supported(self):\n with self.assertRaisesRegex(TypeError,\n \"staticmethod arguments are not supported\"):\n\n class A:\n\n @functools.partial(self.jit)\n @staticmethod\n def my_staticmethod_jit(x):\n return x + 2\n\n def test_concurrent_jit(self):\n @self.jit\n def f(x):\n return x + x - 3.\n\n xs = [np.random.randn(i) for i in range(10)]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [executor.submit(partial(f, x)) for x in xs]\n ys = [f.result() for f in futures]\n for x, y in zip(xs, ys):\n self.assertAllClose(x * 2 - 3., y)\n\n def test_trivial_computations(self):\n x = jnp.array([1, 2, 3])\n y = self.jit(lambda x: x)(x)\n self.assertIs(x, y)\n\n z1, z2 = self.jit(lambda x: (x, x))(x)\n self.assertIs(z1, z2)\n\n x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])\n z1, z2, z3 = self.jit(lambda x, y: (y, 1, x))(x1, x2)\n self.assertIs(z1, x2)\n self.assertIs(z3, x1)\n self.assertEqual(z2, 1)\n\n def test_trivial_computations_with_tokens(self):\n @self.jit\n def noop(arr, token):\n return arr, token\n\n arr = jax.numpy.ones(10)\n token = jax.lax.create_token()\n\n self.assertEqual(token, noop(arr, token)[1])\n\n def test_jit_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: self.jit(f)(\"foo\"))\n\n def test_jit_on_all_devices(self):\n # Verifies we can run the same computation on every device present, even\n # if they are, for example, different models of GPU.\n data = np.random.rand(1000).astype(np.float32)\n f = self.jit(jnp.negative)\n for device in jax.local_devices():\n x = device_put(data, device=device)\n np.testing.assert_array_equal(-data, f(x))\n\n def test_jit_nested_donate_ignored(self):\n jit_fun = self.jit(lambda x: self.jit(lambda y: y**2, donate_argnums=0)(x))\n a = jax.device_put(jnp.array(1))\n\n # NOTE(mattjj): stopped raising error here and instead just ignored\n # with self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\n # jit_fun(a)\n\n jit_fun(a) # doesn't crash\n\n def test_jit_reference_dropping(self):\n x = jnp.ones(10)\n f = (lambda x: lambda: x)(x) # reference to x in f's closure\n g = self.jit(f)\n x = weakref.ref(x) # no more strong ref to x in this scope\n assert x() is not None # x is still around\n f() # f runs\n g() # g runs\n g() # g runs a second time\n del f # delete the raw callable\n assert x() is not None # x is still around\n g() # g still runs\n del g # no more references to x\n assert x() is None # x is gone\n\n def test_jit_raises_on_first_invocation_on_non_hashable_static_argnum(self):\n if self.jit != api._python_jit:\n raise unittest.SkipTest(\"this test only applies to _python_jit\")\n f = lambda x, y: x + 3\n jitted_f = self.jit(f, static_argnums=(1,))\n\n msg = (\"Non-hashable static arguments are not supported, as this can lead \"\n \"to unexpected cache-misses. Static argument (index 1) of type \"\n \"<class 'numpy.ndarray'> for function <lambda> is non-hashable.\")\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n jitted_f(1, np.asarray(1))\n\n def test_cpp_jit_raises_on_non_hashable_static_argnum(self):\n if self.jit != api._cpp_jit:\n raise unittest.SkipTest(\"this test only applies to _cpp_jit\")\n\n f = lambda x, y: x + 3\n jitted_f = api._cpp_jit(f, static_argnums=[1])\n\n jitted_f(1, 1)\n\n msg = (\"Non-hashable static arguments are not supported. An error occured \"\n \".*while trying to hash an object of type \"\n \"<class 'numpy\\\\.ndarray'>, 1. The error was:\\nTypeError: \"\n \"unhashable type: 'numpy\\\\.ndarray'\")\n\n with self.assertRaisesRegex(ValueError, msg):\n jitted_f(1, np.asarray(1))\n\n class HashableWithoutEq:\n\n def __hash__(self):\n return 1\n\n def __eq__(self, other):\n raise NotImplementedError(\n \"A Python error is as is, without stack trace\")\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\"static arguments should be comparable using __eq__\")):\n jitted_f(1, HashableWithoutEq())\n\n def test_cpp_jitted_function_returns_PyBuffer(self):\n if self.jit != api._cpp_jit:\n raise unittest.SkipTest(\"this test only applies to _cpp_jit\")\n\n jitted_f = self.jit(lambda a: a + 1)\n jitted_f(1)\n self.assertIsInstance(jitted_f(2), xla._CppDeviceArray)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_explicit_backend(self):\n f = lambda x: x + 1\n jitted_f = jit(f, backend=jtu.device_under_test())\n jitted_f_cpu = jit(f, backend=\"cpu\")\n\n result = jitted_f(1.)\n result_cpu = jitted_f_cpu(1.)\n self.assertEqual(result.device_buffer.platform(), jtu.device_under_test())\n self.assertEqual(result_cpu.device_buffer.platform(), \"cpu\")\n\n @jtu.skip_on_devices(\"cpu\")\n def test_device_to_device_copy_between_backends(self):\n # b/186624243\n f = lambda x: x + 1\n jitted_f = jit(f, backend=jtu.device_under_test())\n jitted_f_cpu = jit(f, backend=\"cpu\")\n\n x = np.arange(30).reshape(1, 10, 3)\n result = jitted_f(x)\n result_cpu = jitted_f_cpu(result)\n result_2 = jitted_f(result_cpu)\n result_cpu_2 = jitted_f_cpu(result_2)\n self.assertAllClose(result_2, x + 3)\n self.assertAllClose(result_cpu_2, x + 4)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_mismatched_nested_backends(self):\n @partial(jit, backend=jtu.device_under_test())\n def f(x):\n return jit(lambda x: x + 1, backend=\"cpu\")(x)\n\n with self.assertRaisesRegex(\n ValueError,\n f\"Outer-jit backend specification {jtu.device_under_test()} must match \"\n f\"explicit inner-jit backend specification cpu.\"):\n f(1.)\n\n def test_omnistaging(self):\n # See https://github.com/google/jax/issues/5206\n\n # TODO(frostig): remove once we always enable_custom_prng\n def _prng_key_as_array(key):\n return key.keys if config.jax_enable_custom_prng else key\n\n # TODO(frostig): remove once we always enable_custom_prng\n def _array_as_prng_key(arr):\n arr = np.array(arr, dtype=np.uint32)\n if config.jax_enable_custom_prng:\n return jax._src.prng.PRNGKeyArray(\n jax._src.prng.threefry_prng_impl, arr)\n else:\n return arr\n\n key_list = [None]\n\n def init():\n key, subkey = jax.random.split(key_list[0])\n key_list[0] = key\n return jax.random.normal(subkey, ())\n\n key_list[0] = _array_as_prng_key([2384771982, 3928867769])\n init()\n self.jit(init)()\n self.assertIsInstance(_prng_key_as_array(key_list[0]), core.Tracer)\n\n def test_jit_wrapped_attributes(self):\n def f(x: int) -> int:\n \"\"\"docstring of f.\"\"\"\n return x + 1\n f.some_value = 4\n jf = self.jit(f)\n for attr in [\"doc\", \"name\", \"module\", \"qualname\", \"annotations\"]:\n self.assertEqual(\n {attr: getattr(f, f\"__{attr}__\")},\n {attr: getattr(jf, f\"__{attr}__\")})\n self.assertEqual(f.some_value, jf.some_value)\n\n def test_jit_python_builtin(self):\n x = jnp.array([1, 2])\n expected = x + 1\n jit_add = self.jit(operator.add, static_argnums=(1,))\n actual = jit_add(x, 1)\n self.assertArraysEqual(expected, actual)\n\n def test__infer_argnums_and_argnames(self):\n def f(x, y=1):\n pass\n\n argnums, argnames = api._infer_argnums_and_argnames(\n f, argnums=None, argnames=None)\n assert argnums == ()\n assert argnames == ()\n\n argnums, argnames = api._infer_argnums_and_argnames(\n f, argnums=0, argnames=None)\n assert argnums == (0,)\n assert argnames == ('x',)\n\n argnums, argnames = api._infer_argnums_and_argnames(\n f, argnums=None, argnames='y')\n assert argnums == (1,)\n assert argnames == ('y',)\n\n argnums, argnames = api._infer_argnums_and_argnames(\n f, argnums=0, argnames='y') # no validation\n assert argnums == (0,)\n assert argnames == ('y',)\n\n def g(x, y, *args):\n pass\n\n argnums, argnames = api._infer_argnums_and_argnames(\n g, argnums=(1, 2), argnames=None)\n assert argnums == (1, 2)\n assert argnames == ('y',)\n\n def h(x, y, **kwargs):\n pass\n\n argnums, argnames = api._infer_argnums_and_argnames(\n h, argnums=None, argnames=('foo', 'bar'))\n assert argnums == ()\n assert argnames == ('foo', 'bar')\n\n def test_jit_with_static_argnames(self):\n\n def f(x):\n assert x == 'foo'\n return 1\n\n f_nums = self.jit(f, static_argnums=0)\n assert f_nums('foo') == 1\n assert f_nums(x='foo') == 1\n\n f_names = self.jit(f, static_argnames='x')\n assert f_names('foo') == 1\n assert f_names(x='foo') == 1\n\n def test_new_static_argnum_on_keyword_arguments(self):\n f = self.jit(lambda x: x, static_argnums=0)\n y = f(x=4)\n assert y == 4\n\n def test_new_static_argnum_with_default_arguments(self):\n f = self.jit(lambda x=4: x, static_argnums=0)\n y = f()\n assert y == 4\n\n def test_jit_with_mismatched_static_argnames(self):\n x_is_tracer, y_is_tracer = False, False\n def f(x, y):\n assert isinstance(x, core.Tracer) == x_is_tracer\n assert isinstance(y, core.Tracer) == y_is_tracer\n return 1\n\n # If both static_argnums and static_argnames are provided, they are allowed\n # to disagree and `jit` will respect the user's choices.\n f_nums = self.jit(f, static_argnums=1, static_argnames=())\n x_is_tracer, y_is_tracer = True, False\n assert f_nums(2, 'foo') == 1\n x_is_tracer, y_is_tracer = True, True\n assert f_nums(1, y=2) == 1\n\n f_names = self.jit(f, static_argnums=(), static_argnames='y')\n x_is_tracer, y_is_tracer = True, True\n assert f_names(2, 3) == 1\n x_is_tracer, y_is_tracer = True, False\n assert f_names(1, y='foo') == 1\n\n f_mixed = self.jit(f, static_argnums=(1,), static_argnames='x')\n x_is_tracer, y_is_tracer = True, False\n assert f_mixed(2, 'foo') == 1\n x_is_tracer, y_is_tracer = True, True\n assert f_mixed(1, y=3) == 1\n x_is_tracer, y_is_tracer = False, True\n assert f_mixed(x='foo', y=3) == 1\n\n # TODO(zhangqiaorjc): Test pruning constants after DCE pass prunes primitive\n # applications.\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_num_args={}\".format(num_args),\n \"num_args\": num_args}\n for num_args in [2, 3, 4]))\n def test_jit_with_pruned_args(self, num_args):\n def f(*args):\n used = np.array(2)\n return args[1] + used\n f_pruned = self.jit(f)\n args = range(num_args)\n with jtu.count_device_put() as count:\n np.testing.assert_allclose(f_pruned(*args), 3)\n self.assertEqual(count[0], 1)\n\n @unittest.skipIf(jax._src.lib._xla_extension_version <= 36,\n \"Test requires jaxlib 0.1.71\")\n def testBuffersAreFreedPromptly(self):\n # Regression test for a bug where garbage collection was delayed too long\n # for NumPy buffers that are aliased zero-copy by the runtime.\n @self.jit\n def f(x):\n return x + 1\n\n refs = []\n x = np.ones((10000,), np.float32)\n for step in range(1000):\n x = f(x)\n refs.append(weakref.ref(x))\n x = np.asarray(x)\n\n # We expect most of the input buffers to have been garbage\n # collected in parallel with the execution. We can't call\n # block_until_ready() here because it would force a garbage collection.\n live_refs = len([ref for ref in refs if ref() is not None])\n self.assertLessEqual(live_refs, 100)\n\n def test_lower_compile(self):\n def f(x):\n return jnp.sqrt(x ** 2) + 1.\n\n f_jit = self.jit(f)\n f_low = f_jit.lower(1.)\n f_exe = f_low.compile()\n self.assertAllClose(f_exe(1.), 2.)\n\n def test_lower_compile_in_tree_mismatch(self):\n def f(x):\n return jnp.sqrt(x ** 2) + 1.\n\n f_jit = self.jit(f)\n f_low = f_jit.lower(1.)\n f_exe = f_low.compile()\n self.assertRaisesRegex(\n TypeError, \"function compiled for .*, called with .*\",\n lambda: f_exe([1.]))\n\n def test_lower_compile_trivial(self):\n def f(x): return x\n out = self.jit(f).lower(1.).compile()(4.)\n self.assertAllClose(out, 4.)\n\n def test_lower_compile_trivial_in_tree_mismatch(self):\n def f(x): return x\n f_exe = self.jit(f).lower(1.).compile()\n self.assertRaisesRegex(\n TypeError, \"function compiled for .*, called with .*\",\n lambda: f_exe([4.]))\n\n\nclass PythonJitTest(CPPJitTest):\n\n @property\n def jit(self):\n return api._python_jit\n\n\nclass APITest(jtu.JaxTestCase):\n\n def test_grad_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: grad(f)(\"foo\"))\n\n def test_grad_argnums(self):\n def f(x, y, z, flag=False):\n assert flag\n return 1.0 * x + 2.0 * y + 3.0 * z\n\n assert grad(f)(1.0, 1.0, 1.0, flag=True) == 1.0\n assert grad(f, argnums=1)(1.0, 1.0, 1.0, flag=True) == 2.0\n assert grad(f, argnums=(2, 0))(1.0, 1.0, 1.0, flag=True) == (3.0, 1.0)\n\n def test_value_and_grad_argnums(self):\n def f(x, y, z, flag=False):\n assert flag\n return 1.0 * x + 2.0 * y + 3.0 * z\n\n y = f(1.0, 1.0, 1.0, flag=True)\n assert api.value_and_grad(f)(1.0, 1.0, 1.0, flag=True) == (y, 1.0)\n assert api.value_and_grad(f, argnums=1)(1.0, 1.0, 1.0, flag=True) == (y, 2.0)\n assert api.value_and_grad(f, argnums=(2, 0))(1.0, 1.0, 1.0, flag=True) == (y, (3.0, 1.0))\n\n def test_grad_of_jit(self):\n side = []\n\n @jit\n def f(x):\n side.append(None)\n return x * x\n\n assert grad(f)(1.0) == 2.0\n assert len(side) == 1\n assert grad(f)(2.0) == 4.0\n assert len(side) == 1\n\n def test_jit_of_grad(self):\n side = []\n\n @jit\n def f(x):\n side.append(None)\n return x * x\n\n g = jit(grad(f))\n assert g(1.0) == 2.0\n assert len(side) == 1\n assert g(2.0) == 4.0\n assert len(side) == 1\n\n def test_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: grad(f)(\"foo\"))\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: jit(f)(\"foo\"))\n\n def test_grad_tuple_output(self):\n jtu.check_raises(lambda: grad(lambda x: (x,x))(1.0), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_grad_unit_output(self):\n jtu.check_raises(lambda: grad(lambda x: ())(np.zeros(3)), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_grad_nonscalar_output(self):\n jtu.check_raises(lambda: grad(lambda x: x)(np.zeros(3)), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_unwrapped_numpy(self):\n def f(x):\n return np.exp(x)\n\n with self.assertRaisesRegex(Exception, \"The numpy.ndarray conversion .*\"):\n grad(f)(np.zeros(3))\n\n def test_binop_mismatch(self):\n def f(x, y):\n return x + y\n\n jtu.check_raises(\n lambda: f(jnp.zeros(3), jnp.zeros(4)),\n TypeError,\n \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n\n jtu.check_raises(\n lambda: grad(f)(np.zeros(3), np.zeros(4)),\n TypeError,\n \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n\n def test_dot_mismatch(self):\n def f(x, y):\n return jnp.dot(x, y)\n\n self.assertRaisesRegex(\n TypeError, \"Incompatible shapes for dot: got \\\\(3L?,\\\\) and \\\\(4L?,\\\\).\",\n lambda: grad(f)(np.zeros(3), np.zeros(4)))\n\n def test_abstract_error_message(self):\n for castfun in [float, complex, int]:\n def f(x):\n return castfun(x)\n\n self.assertRaisesRegex(\n TypeError,\n f\"[Tt]ry using `x.astype\\\\({castfun.__name__}\\\\)`\",\n lambda: jit(f)(1.0))\n\n def test_switch_value_jit(self):\n def f(x):\n y = x > 0\n if y:\n return x\n else:\n return -x\n\n assert grad(f)(1.0) == 1.0\n assert grad(f)(-1.0) == -1.0\n with self.assertRaisesRegex(core.ConcretizationTypeError,\n \"Abstract tracer value\"):\n jit(f)(1)\n\n def test_list_index_err(self):\n L = [1, 2, 3]\n def f(n):\n return L[n]\n\n assert jit(f, static_argnums=(0,))(0) == L[0]\n self.assertRaisesRegex(\n TypeError,\n r\"The __index__\\(\\) method was called on the JAX Tracer object.*\",\n lambda: jit(f)(0))\n\n def test_range_err(self):\n def f(x, n):\n for i in range(n):\n x = x + i\n return x\n\n assert jit(f, static_argnums=(1,))(0, 5) == 10\n self.assertRaisesRegex(\n TypeError,\n r\"The __index__\\(\\) method was called on the JAX Tracer object.*\",\n lambda: jit(f)(0, 5))\n\n def test_cast_int(self):\n f = lambda x: int(x)\n self.assertRaisesRegex(\n TypeError,\n \"('(?:JaxprTracer|DynamicJaxprTracer)' object cannot be interpreted as an integer\"\n \"|Abstract tracer value encountered where concrete value is expected.*)\", lambda: jit(f)(0))\n\n def test_casts(self):\n for castfun in [hex, oct]:\n f = lambda x: castfun(x)\n self.assertRaisesRegex(\n TypeError,\n r\"The __index__\\(\\) method was called on the JAX Tracer object.*\", lambda: jit(f)(0))\n\n def test_unimplemented_interpreter_rules(self):\n foo_p = Primitive('foo')\n def foo(x):\n return foo_p.bind(x)\n\n jtu.check_raises(lambda: foo(1.0), NotImplementedError,\n \"Evaluation rule for 'foo' not implemented\")\n\n jtu.check_raises(lambda: jit(foo)(1.0), NotImplementedError,\n \"Abstract evaluation for 'foo' not implemented\")\n\n jtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n \"Differentiation rule for 'foo' not implemented\")\n\n foo_p.def_abstract_eval(lambda x: x)\n\n jtu.check_raises(lambda: jit(foo)(1.0), NotImplementedError,\n \"XLA translation rule for primitive 'foo' not found\")\n\n foo_p.def_impl(lambda x: x)\n ad.defjvp(foo_p, lambda g, x: foo(g))\n\n jtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n \"Transpose rule (for reverse-mode differentiation) for 'foo' not implemented\")\n\n def test_is_subclass(self):\n self.assertTrue(issubclass(xla.DeviceArray, jnp.ndarray))\n self.assertTrue(issubclass(xla._CppDeviceArray, jnp.ndarray))\n self.assertTrue(issubclass(pxla.ShardedDeviceArray, jnp.ndarray))\n self.assertTrue(issubclass(pxla._ShardedDeviceArray, jnp.ndarray))\n self.assertFalse(issubclass(np.ndarray, jnp.ndarray))\n self.assertFalse(issubclass(xla.DeviceArray, np.ndarray))\n self.assertFalse(issubclass(xla._CppDeviceArray, np.ndarray))\n self.assertFalse(issubclass(pxla.ShardedDeviceArray, np.ndarray))\n self.assertFalse(issubclass(pxla._ShardedDeviceArray, np.ndarray))\n\n def test_is_instance(self):\n def f(x):\n self.assertIsInstance(x, jnp.ndarray)\n self.assertNotIsInstance(x, np.ndarray)\n return x + 2\n jit(f)(3)\n jax.vmap(f)(np.arange(3))\n\n def test_device_put_and_get(self):\n x = np.arange(12.).reshape((3, 4)).astype(\"float32\")\n dx = api.device_put(x)\n self.assertIsInstance(dx, xla.DeviceArray)\n self.assertIsInstance(dx, jnp.ndarray)\n self.assertNotIsInstance(dx, np.ndarray)\n x2 = api.device_get(dx)\n self.assertNotIsInstance(x2, jnp.ndarray)\n self.assertIsInstance(x2, np.ndarray)\n assert np.all(x == x2)\n\n y = [x, (2 * x, 3 * x)]\n dy = api.device_put(y)\n y2 = api.device_get(dy)\n self.assertIsInstance(y2, list)\n self.assertIsInstance(y2[0], np.ndarray)\n assert np.all(y2[0] == x)\n self.assertIsInstance(y2[1], tuple)\n self.assertIsInstance(y2[1][0], np.ndarray)\n assert np.all(y2[1][0] == 2 * x)\n self.assertIsInstance(y2[1][1], np.ndarray)\n assert np.all(y2[1][1] == 3 * x)\n\n def test_device_get_scalar(self):\n x = np.arange(12.).reshape((3, 4)).astype(\"float32\")\n x = api.device_put(x)\n self.assertIsInstance(x, xla.DeviceArray)\n y = [x, 2]\n y2 = api.device_get(y)\n self.assertIsInstance(y2, list)\n self.assertIsInstance(y2[0], np.ndarray)\n assert np.all(y2[0] == x)\n self.assertIsInstance(y2[1], int)\n self.assertEqual(y2[1], 2)\n\n @parameterized.parameters([(3,)], [(2, 0)])\n def test_device_put_across_devices(self, shape):\n if len(api.local_devices()) < 2:\n raise unittest.SkipTest(\"this test requires multiple devices\")\n d1, d2 = api.local_devices()[:2]\n data = np.random.randn(*shape).astype(np.float32)\n x = api.device_put(data, device=d1)\n self.assertEqual(x.device_buffer.device(), d1)\n y = api.device_put(x, device=d2)\n self.assertEqual(y.device_buffer.device(), d2)\n np.testing.assert_array_equal(data, np.array(y))\n # Make sure these don't crash\n api.device_put(x)\n api.device_put(y)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_device_put_across_platforms(self):\n default_device = jax.devices()[0]\n cpu_device = jax.devices(\"cpu\")[0]\n\n np_arr = np.array([1,2,3])\n scalar = 1\n device_arr = jnp.array([1,2,3])\n assert device_arr.device_buffer.device() is default_device\n\n for val in [np_arr, device_arr, scalar]:\n x = api.device_put(val, device=cpu_device)\n self.assertEqual(x.device_buffer.device(), cpu_device)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_jacobian(self):\n R = np.random.RandomState(0).randn\n A = R(4, 3)\n x = R(3)\n\n f = lambda x: jnp.dot(A, x)\n assert np.allclose(jacfwd(f)(x), A)\n assert np.allclose(jacrev(f)(x), A)\n\n f = lambda x: jnp.tanh(jnp.dot(A, x))\n assert np.allclose(jacfwd(f)(x), jacrev(f)(x))\n\n @jtu.skip_on_devices(\"tpu\")\n def test_hessian(self):\n R = np.random.RandomState(0).randn\n A = R(4, 4)\n x = R(4)\n\n f = lambda x: jnp.dot(x, jnp.dot(A, x))\n assert np.allclose(hessian(f)(x), A + A.T)\n\n def test_std_basis(self):\n basis = api._std_basis(jnp.zeros(3))\n assert getattr(basis, \"shape\", None) == (3, 3)\n assert np.allclose(basis, np.eye(3))\n\n basis = api._std_basis(jnp.zeros((3, 3)))\n assert getattr(basis, \"shape\", None) == (9, 3, 3)\n assert np.allclose(basis, np.eye(9).reshape(9, 3, 3))\n\n basis = api._std_basis([0., (jnp.zeros(3), jnp.zeros((3, 4)))])\n assert isinstance(basis, list) and len(basis) == 2\n assert getattr(basis[0], \"shape\", None) == (16,)\n assert isinstance(basis[1], tuple) and len(basis[1]) == 2\n assert getattr(basis[1][0], \"shape\", None) == (16, 3)\n assert getattr(basis[1][1], \"shape\", None) == (16, 3, 4)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_jacobian_on_pytrees(self):\n for jacfun in [jacfwd, jacrev]:\n ans = jacfun(lambda x, y: (x, y))(0., 1.)\n expected = (1., 0.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x, y: (x, y), 1)(0., 1.)\n expected = (0., 1.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x, y: (x, y), (0, 1))(0., 1.)\n expected = ((1., 0.),\n (0., 1.),)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x: x[:2])((1., 2., 3.))\n expected = ((1., 0., 0.),\n (0., 1., 0.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n R = np.random.RandomState(0).randn\n x = R(2)\n y = R(3)\n ans = jacfun(lambda x, y: {'x': x, 'xy': jnp.outer(x, y)})(x, y)\n expected = {'x': np.eye(2),\n 'xy': np.kron(np.eye(2), y[:, None]).reshape(2, 3, 2)}\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_hessian_on_pytrees(self):\n ans = hessian(lambda x: jnp.array(x)**2)((1., 2.))\n expected = ((np.array([2., 0.]), np.array([0., 0.])),\n (np.array([0., 0.]), np.array([0., 2.])))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_issue1372(self):\n def quad(x):\n return jnp.dot(x, x)\n\n def f(x, u):\n return quad(x) + quad(u)\n\n x, u = jnp.ones(5), jnp.ones(2)\n\n rev = jacrev\n fwd = jacfwd\n\n # Diagonal entries\n self.assertEqual(rev(rev(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(rev(fwd(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(fwd(rev(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(fwd(fwd(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(rev(rev(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(rev(fwd(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(fwd(rev(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(fwd(fwd(f, 1), 1)(x, u).shape, (2, 2))\n\n # Off-diagonal entries by reverse-mode on the outside\n self.assertEqual(rev(rev(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(rev(fwd(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(rev(rev(f, 0), 1)(x, u).shape, (5, 2))\n self.assertEqual(rev(fwd(f, 0), 1)(x, u).shape, (5, 2))\n\n # Off-diagonal entries by forward-mode on the outside\n self.assertEqual(fwd(rev(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(fwd(fwd(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(fwd(rev(f, 0), 1)(x, u).shape, (5, 2))\n self.assertEqual(fwd(fwd(f, 0), 1)(x, u).shape, (5, 2))\n\n\n def test_large_device_constant(self):\n ans = jit(lambda x: 2 * x)(jnp.ones(int(2e6))) # doesn't crash\n self.assertAllClose(ans, np.ones(int(2e6)) * 2., check_dtypes=False)\n\n def test_grad_and_aux_basic(self):\n g, aux = grad(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n self.assertAllClose(g, grad(lambda x: x**3)(3.))\n self.assertAllClose(aux, [9.], check_dtypes=False)\n\n def test_grad_and_aux_error(self):\n with self.assertRaisesRegex(TypeError, \"two-element tuple\"):\n grad(lambda x: (1, 2, 3), has_aux=True)(1.)\n\n with self.assertRaisesRegex(TypeError, \"two-element tuple\"):\n grad(lambda x: x, has_aux=True)(1.)\n\n with self.assertRaisesRegex(TypeError, \"two-element tuple\"):\n grad(lambda x: (x,), has_aux=True)(1.)\n\n def test_grad_and_aux_nested(self):\n def f(x):\n g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n return aux[0]\n\n f2 = lambda x: x**3\n\n self.assertEqual(grad(f)(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n\n def f(x):\n g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n return aux[0] * jnp.sin(x)\n\n f2 = lambda x: x**3 * jnp.sin(x)\n\n self.assertEqual(grad(f)(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n\n def test_grad_and_aux_constant(self):\n g, aux = grad(lambda x: (x**3, [4.]), has_aux=True)(4.)\n self.assertEqual(g, grad(lambda x: x**3)(4.))\n self.assertEqual(aux, [4.])\n\n g, aux = grad(lambda x: (x**3, [x**2, 4.]), has_aux=True)(4.)\n self.assertEqual(g, grad(lambda x: x**3)(4.))\n self.assertEqual(aux, [4.**2, 4.])\n\n def test_grad_and_aux_no_tracers(self):\n # see https://github.com/google/jax/issues/1950\n def f(x):\n aux = dict(identity=x, p1=x+1)\n return x ** 2, aux\n\n _, aux = jax.grad(f, has_aux=True)(3.)\n self.assertIsInstance(aux, dict)\n for val in aux.values():\n self.assertNotIsInstance(val, core.Tracer)\n\n def test_jvp_mismatched_arguments(self):\n self.assertRaisesRegex(\n TypeError,\n (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure\"),\n lambda: api.jvp(lambda x, y: x * y, (np.float32(2),), ()))\n # If primals and tangents must both be tuples or both lists\n self.assertRaisesRegex(\n TypeError,\n (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure\"),\n lambda: api.jvp(lambda x, y: x * y, (np.float32(2),), [np.float32(2)]))\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp do not match.\",\n lambda: api.jvp(lambda x: -x, (np.float16(2),), (np.float32(4),)))\n # If primals and tangents are not of the same shape then raise error\n fun = lambda x: x+1\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.array([1.,2.,3.,4.]),))\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.float32(10.),), (jnp.array([1.,2.,3.], dtype=jnp.float32),))\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.array([1.,2.,3.], dtype=jnp.float32),), (jnp.float32(20.),))\n with self.assertRaisesRegex(\n ValueError, \"jvp called with different primal and tangent shapes\"):\n api.jvp(fun, (jnp.array([1.,2.,3.]),), (20.,))\n\n def test_jvp_non_tuple_arguments(self):\n def f(x, y): return x + y\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp must be tuples or lists; found float and tuple.\",\n lambda: api.jvp(f, 0., (1.,)))\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp must be tuples or lists; found tuple and ndarray.\",\n lambda: api.jvp(f, (0.,), np.array([1., 2.])))\n\n def test_vjp_mismatched_arguments(self):\n _, pullback = api.vjp(lambda x, y: x * y, np.float32(3), np.float32(4))\n self.assertRaisesRegex(\n TypeError,\n \"Tree structure of cotangent input.*does not match\",\n lambda: pullback((np.float32(7), np.float32(100))))\n self.assertRaisesRegex(\n TypeError,\n \"Type of cotangent input to vjp pullback.*is not the expected tangent type\",\n lambda: pullback((np.float16(42))))\n\n def test_vjp_bad_cotangent_shape(self):\n x = np.ones((2, 5), dtype=np.float32)\n y = np.ones((5, 3), dtype=np.float32)\n def f_jax(x, y):\n return jnp.matmul(x, y)\n res, pullback = jax.vjp(f_jax, x, y)\n with self.assertRaisesRegex(\n ValueError,\n \"Shape of cotangent input to vjp pullback function .* must be the same as the shape of corresponding primal input .*\"):\n pullback(np.ones((2, 4), dtype=np.float32))\n\n def test_jvp_jit_cached(self):\n \"\"\"Bug in caching in presence of JVP and JIT.\"\"\"\n\n def func(x):\n def inner(y):\n return y * x\n\n # Must have two calls to the inner jit (the second one hits the cache)\n res1 = api.jit(inner)(4.)\n res2 = api.jit(inner)(5.)\n return res1 + res2\n\n self.assertAllClose((45., 9.), api.jvp(func, (5.,), (1.,)))\n\n def test_linear_transpose_abstract(self):\n x = types.SimpleNamespace(shape=(3,), dtype=np.dtype(np.float32))\n y = jnp.arange(3, dtype=np.float32)\n transpose_fun = api.linear_transpose(lambda x: 2 * x, x)\n z, = transpose_fun(y)\n self.assertArraysEqual(2 * y, z, check_dtypes=True)\n\n def test_linear_transpose_integer(self):\n f = lambda x: 2 * x\n transpose = api.linear_transpose(f, 1)\n actual, = transpose(3)\n expected = 6\n self.assertEqual(actual, expected)\n\n def test_linear_transpose_error(self):\n with self.assertRaisesRegex(\n TypeError, \"linear_transpose only supports\"):\n api.linear_transpose(lambda x: 2. * x, 1)\n transpose_fun = api.linear_transpose(lambda x: [x, x], 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent tree does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: jnp.stack([x, x]), 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: 1j * x, 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: x, 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1j)\n\n def test_linear_transpose_complex(self):\n f = lambda x: (1 + 2j) * x\n transpose = api.linear_transpose(f, 1j)\n actual, = transpose(3 + 4j)\n expected = -5 + 10j\n self.assertEqual(actual, expected)\n\n def test_linear_transpose_zeros(self):\n f = lambda x: x[0]\n transpose = api.linear_transpose(f, [1., 2.])\n actual, = transpose(3.)\n expected = [3., 0.]\n self.assertEqual(actual, expected)\n\n def test_complex_grad_raises_error(self):\n self.assertRaises(TypeError, lambda: grad(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_holomorphic_grad(self):\n out = grad(lambda x: jnp.sin(x), holomorphic=True)(1 + 2j)\n expected = 2.0327230070196656 - 3.0518977991518j\n self.assertAllClose(out, expected, check_dtypes=False)\n\n def test_nonholomorphic_grad(self):\n zs = 0.5j * np.arange(5) + np.arange(5)\n\n def f(z):\n return jnp.sum(jnp.cos(jnp.abs(z)))\n\n ans = grad(f)(zs)\n expected = np.array([ 0. + 0.j,\n -0.80430663 + 0.40215331j,\n -0.70368982 + 0.35184491j,\n 0.1886467 - 0.09432335j,\n 0.86873727 - 0.43436864j])\n self.assertAllClose(ans, expected, check_dtypes=False,\n atol=jtu.default_gradient_tolerance,\n rtol=jtu.default_gradient_tolerance)\n\n def test_complex_output_jacrev_raises_error(self):\n self.assertRaises(TypeError, lambda: jacrev(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_nonholomorphic_jacrev(self):\n # code based on https://github.com/google/jax/issues/603\n zs = 0.5j * np.arange(5) + np.arange(5)\n\n def f(z):\n return jnp.cos(jnp.linalg.norm(2 * z))\n\n ans = jacrev(f)(zs)\n expected = grad(f)(zs)\n self.assertAllClose(ans, expected)\n\n def test_complex_input_jacfwd_raises_error(self):\n self.assertRaises(TypeError, lambda: jacfwd(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_legacy_devicearray_repr(self):\n dx = device_put(3.)\n str(dx.item()) # doesn't crash\n\n def test_devicearray_repr(self):\n x = device_put(jnp.zeros(3))\n self.assertIsInstance(x, xla.DeviceArray)\n repr(x) # doesn't crash\n\n x = device_put(jnp.ones(3) + 1j * jnp.ones(3))\n self.assertIsInstance(x, xla.DeviceArray)\n repr(x) # doesn't crash\n\n def test_devicearray_delete(self):\n x = device_put(1.)\n x.delete()\n self.assertRaisesRegex(RuntimeError, \"DeviceArray has been deleted.\",\n lambda: repr(x))\n\n def test_devicearray_block_until_ready(self):\n x = device_put(1.)\n y = x.block_until_ready()\n # Tests mostly that block_until_ready() does not produce an error.\n self.assertTrue(y is x)\n\n def test_devicearray_weakref_friendly(self):\n x = device_put(1.)\n y = weakref.ref(x)\n self.assertEqual(y(), 1.)\n del x\n self.assertIsNone(y())\n\n def test_namedtuple_transparency(self):\n # See https://github.com/google/jax/issues/446\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n\n def f(pt):\n return jnp.sqrt(pt.x ** 2 + pt.y ** 2)\n\n pt = Point(1., 2.)\n\n f(pt) # doesn't crash\n g = api.grad(f)(pt)\n self.assertIsInstance(g, Point)\n\n f_jit = api.jit(f)\n self.assertAllClose(f(pt), f_jit(pt), check_dtypes=False)\n\n def test_namedtuple_subclass_transparency(self):\n # See https://github.com/google/jax/issues/806\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n\n class ZeroPoint(Point):\n def is_zero(self):\n return (self.x == 0) and (self.y == 0)\n\n pt = ZeroPoint(0., 0.)\n\n def f(pt):\n return 0. if pt.is_zero() else jnp.sqrt(pt.x ** 2 + pt.y ** 2)\n\n f(pt) # doesn't crash\n _ = api.grad(f)(pt)\n self.assertIsInstance(pt, ZeroPoint)\n\n @parameterized.parameters(1, 2, 3)\n def test_shape_dtype_struct(self, i):\n s = api.ShapeDtypeStruct(shape=(i, 2, 3), dtype=jnp.float32)\n self.assertEqual(s.shape, (i, 2, 3))\n self.assertEqual(s.dtype, jnp.float32)\n self.assertEqual(s.ndim, 3)\n self.assertEqual(s.size, i * 2 * 3)\n self.assertLen(s, i)\n for f in (str, repr):\n self.assertEqual(\n f(s), \"ShapeDtypeStruct(shape=({}, 2, 3), dtype=float32)\".format(i))\n\n def test_shape_dtype_struct_scalar(self):\n s = api.ShapeDtypeStruct(shape=(), dtype=jnp.float32)\n self.assertEmpty(s.shape)\n self.assertEqual(s.size, 1)\n self.assertEqual(s.ndim, 0)\n with self.assertRaisesRegex(TypeError, \"len[(][)] of unsized object\"):\n _ = len(s)\n\n def test_eval_shape(self):\n def fun(x, y):\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n x = jnp.ones((2, 3))\n y = jnp.ones((3, 4))\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2, 4))\n\n def test_eval_shape_constants(self):\n def fun():\n x = jnp.ones((2, 3))\n y = jnp.ones((3, 4))\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n out_shape = api.eval_shape(fun)\n\n self.assertEqual(out_shape.shape, (2, 4))\n\n def test_eval_shape_tuple_unpacking(self):\n def fun(x, y):\n a, b = x\n return a + b + y\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2,))\n\n def test_eval_shape_tuple_itemgetting(self):\n def fun(x, y):\n return x[0] + x[1] + y\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2,))\n\n def test_eval_shape_output_dict(self):\n def fun(x, y):\n return {'hi': x[0] + x[1] + y}\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n out_shape = tree_util.tree_map(np.shape, out_shape)\n\n self.assertEqual(out_shape, {'hi': (2,)})\n\n def test_eval_shape_shape_error(self):\n def fun(x, y):\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n x = jnp.ones((3, 3))\n y = jnp.ones((4, 4))\n\n self.assertRaises(TypeError, lambda: api.eval_shape(fun, x, y))\n\n def test_eval_shape_duck_typing(self):\n def fun(A, b, x):\n return jnp.dot(A, x) + b\n\n class MyArgArray(object):\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = np.dtype(dtype)\n\n A = MyArgArray((3, 4), jnp.float32)\n b = MyArgArray((5,), jnp.float32)\n x = MyArgArray((4, 5), jnp.float32)\n out_shape = api.eval_shape(fun, A, b, x)\n\n self.assertEqual(out_shape.shape, (3, 5))\n\n def test_eval_shape_duck_typing2(self):\n # https://github.com/google/jax/issues/5683\n class EasyDict(dict):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__dict__ = self\n\n x = EasyDict(shape=(3,), dtype=np.dtype('float32'))\n out_shape = api.eval_shape(lambda x: x, x) # doesn't crash\n self.assertEqual(out_shape.shape, (3,))\n\n def test_eval_shape_names(self):\n def fun(x, y):\n return lax.psum(x, 'i') + y\n\n class MyArgArray(object):\n def __init__(self, shape, dtype, named_shape):\n self.shape = shape\n self.dtype = jnp.dtype(dtype)\n self.named_shape = named_shape\n\n x = MyArgArray((3, 2), jnp.float32, {'i': 10})\n y = MyArgArray((3, 2), jnp.float32, {'j': 5})\n with core.extend_axis_env('i', 10, None):\n with core.extend_axis_env('j', 5, None):\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.named_shape, {'j': 5})\n\n def test_issue_871(self):\n T = jnp.array([[1., 2.], [3., 4.], [5., 6.]])\n x = jnp.array([1, 2, 3])\n msg = (\"linearized function called on tangent values inconsistent with \"\n \"the original primal values\")\n\n y, f_jvp = api.linearize(jnp.sum, x)\n with self.assertRaisesRegex(ValueError, msg):\n f_jvp(T)\n\n y, f_jvp = api.linearize(api.jit(jnp.sum), x)\n with self.assertRaisesRegex(ValueError, msg):\n f_jvp(T)\n\n def test_grad_of_int_errors(self):\n # Errors without allow_int=True\n dfn = grad(lambda x: x ** 2)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad requires real- or complex-valued inputs \\(input dtype that is a \"\n r\"sub-dtype of np.floating or np.complexfloating\\), but got int.*.\"),\n lambda: dfn(3))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_jvp_of_int_identity(self):\n primals = (1,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out = api.jvp(lambda x: x, primals, tangents)\n self.assertEqual(out, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_jvp_of_int_add(self):\n primals = (2,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out_tangent = api.jvp(lambda x: x+1, primals, tangents)\n self.assertEqual(out_tangent, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_jit_jvp_of_int(self):\n primals = (2,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out_tangent = api.jvp(jax.jit(lambda x: x+1), primals, tangents)\n self.assertEqual(out_tangent, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_vjp_of_int_index(self):\n primal, fn_vjp = api.vjp(lambda x, i: x[i], np.ones(2)*2, 1)\n tangent_x, tangent_i = fn_vjp(1.)\n self.assertEqual(primal, 2.)\n self.assertAllClose(tangent_x, jnp.array([0., 1.]))\n self.assertEqual(tangent_i, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_vjp_of_int_shapes(self):\n out, fn_vjp = api.vjp(lambda x: lax.reshape(x, (2, 2)), np.ones((4, 1),\n dtype=int))\n tangent, = fn_vjp(out)\n self.assertArraysEqual(tangent, np.zeros(shape=(4, 1), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_jit_vjp_of_int(self):\n primal, fn_vjp = api.vjp(lambda x, y: x+y, 2, 1)\n tangent_x, tangent_i = jax.jit(fn_vjp)(1)\n self.assertEqual(primal, 3)\n self.assertEqual(tangent_x, np.zeros(shape=(), dtype=float0))\n self.assertEqual(tangent_i, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_vjp_of_int_fulllike(self):\n # Regression test for tangent and cotangent mismatch in convert_element_type\n # transpose rule wrt a ConstVar\n f = lax.full_like\n out, vjp = api.vjp(f, np.zeros((2, 2)), 1)\n self.assertAllClose(out, jnp.ones((2, 2)))\n tangent_x, tangent_y = vjp(out)\n self.assertAllClose(tangent_x, jnp.zeros((2, 2)))\n self.assertEqual(tangent_y, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_grad_of_int(self):\n # Need real-valued output, but testing integer input.\n out = api.grad(lambda x: x+0., allow_int=True)(1)\n self.assertEqual(out, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_grad_of_bool(self):\n def cond(pred):\n return lax.cond(pred, lambda _: 1., lambda _: 2., 1.)\n value, grd = api.value_and_grad(cond, allow_int=True)(True)\n self.assertEqual(value, 1.)\n self.assertEqual(grd, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_grad_of_int_index(self):\n grad_x, grad_i = api.grad(lambda x, i: x[i], argnums=(0, 1),\n allow_int=True)(np.ones(2), 1)\n self.assertAllClose(grad_x, jnp.array([0., 1.]))\n self.assertEqual(grad_i, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_jit_grad_of_int(self):\n grad_f = api.grad(lambda x, i: x[i], argnums=(0, 1), allow_int=True)\n grad_x, grad_i = jax.jit(grad_f)(np.ones(2), 1)\n self.assertAllClose(grad_x, jnp.array([0., 1.]))\n self.assertEqual(grad_i, np.zeros(shape=(), dtype=float0))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_float0_reshape(self):\n # dtype-agnostic operations are supported\n float0_array = jax.grad(lambda x: jnp.sum(x+0.),\n allow_int=True)(np.ones((2, 4), dtype=int))\n\n self.assertArraysEqual(float0_array.reshape((4, 2)),\n np.zeros((4, 2), dtype=float0))\n self.assertArraysEqual(float0_array.transpose(),\n np.zeros((4, 2), dtype=float0))\n\n def test_float0_error(self):\n # float0 is incompatible with other dtypes\n float0_array = jax.grad(lambda x: x+0., allow_int=True)(1)\n error_text = \"float0s do not support any operations by design\"\n\n with self.assertRaisesRegex(TypeError, error_text):\n # dispatch via DeviceArray\n _ = float0_array + jnp.zeros(())\n\n with self.assertRaisesRegex(TypeError, error_text):\n # dispatch via lax\n _ = lax.add(float0_array, jnp.zeros(()))\n\n def test_grad_complex_result_errors(self):\n dfn = grad(lambda x: x ** 2 + 1j)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad requires real-valued outputs \\(output dtype that is a \"\n r\"sub-dtype of np.floating\\), but got complex.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_grad_of_float_errors(self):\n dfn = grad(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_jacrev_of_float_errors(self):\n dfn = jacrev(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacrev with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_jacfwd_of_float_errors(self):\n dfn = jacfwd(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacfwd with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_jacfwd_of_complex_errors(self):\n dfn = jacfwd(lambda x: x ** 2)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacfwd requires real-valued inputs \\(input dtype that is a \"\n r\"sub-dtype of np.floating\\), but got complex.*\"),\n lambda: dfn(3. + 1j))\n\n def test_xla_computation(self):\n # these tests basically check the examples in the xla_computation docstring\n\n def e(x):\n return jnp.sin(jnp.cos(x))\n c = api.xla_computation(e)(2.)\n self.assertIn('cosine', c.as_hlo_text())\n self.assertIn('sine', c.as_hlo_text())\n\n def f(x):\n return x - lax.psum(x, 'i')\n axis_env = [('i', 4)]\n c = api.xla_computation(f, axis_env=axis_env)(2)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1,2,3}}', c.as_hlo_text())\n\n def g(x):\n rowsum = lax.psum(x, 'i')\n colsum = lax.psum(x, 'j')\n allsum = lax.psum(x, ('i', 'j'))\n return rowsum, colsum, allsum\n axis_env = [('i', 4), ('j', 2)]\n c = api.xla_computation(g, axis_env=axis_env)(5.)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,2,4,6},{1,3,5,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1},{2,3},{4,5},{6,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1,2,3,4,5,6,7}}', c.as_hlo_text())\n\n def h(x):\n rowsum = lax.psum(x, 'i', axis_index_groups=[[0, 1], [2, 3]])\n colsum = lax.psum(x, 'j')\n return rowsum, colsum\n axis_env = [('i', 4), ('j', 2)]\n c = api.xla_computation(h, axis_env=axis_env)(5.)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,2},{4,6},{1,3},{5,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1},{2,3},{4,5},{6,7}}', c.as_hlo_text())\n\n def test_xla_computation_args(self):\n def foo(x, y, z):\n return x + y + z\n\n c = api.xla_computation(foo)(1., 2., 3.)\n self.assertEqual(len(c.program_shape().parameter_shapes()), 3)\n\n c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n param_shapes = c.program_shape().parameter_shapes()\n self.assertEqual(len(param_shapes), 1)\n self.assertEqual(param_shapes[0].xla_element_type(),\n xla_client.PrimitiveType.TUPLE)\n\n def test_xla_computation_duck_typing(self):\n def foo(x, y, z):\n return x + y + z\n\n x = jax.ShapeDtypeStruct((), np.float32)\n y = jax.ShapeDtypeStruct((), np.float32)\n z = jax.ShapeDtypeStruct((), np.float32)\n\n c = api.xla_computation(foo)(x, y, z)\n self.assertEqual(len(c.program_shape().parameter_shapes()), 3)\n\n c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n param_shapes = c.program_shape().parameter_shapes()\n self.assertEqual(len(param_shapes), 1)\n self.assertEqual(param_shapes[0].xla_element_type(),\n xla_client.PrimitiveType.TUPLE)\n\n def test_staging_out_multi_replica(self):\n def f(x):\n return api.pmap(jnp.mean)(x)\n xla_comp = api.xla_computation(f)\n xla_comp(jnp.arange(8)).as_hlo_text() # doesn't crash\n\n def test_xla_computation_instantiate_constant_outputs(self):\n def f():\n return jnp.zeros((3, 4))\n\n xla_comp = api.xla_computation(f)()\n out_shape, = xla_comp.program_shape().result_shape().tuple_shapes()\n self.assertEqual(out_shape.dimensions(), (3, 4))\n\n def test_xla_computation_static_argnums(self):\n def f(x, y):\n return x + y\n\n xla_comp = api.xla_computation(f, static_argnums=(1,))(2, 3)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn(\"constant(3)\", hlo_text)\n # The static arguments should be removed from the function being compiled,\n # thus the function should have only a single argument.\n self.assertIn(\"parameter.1\", hlo_text)\n self.assertNotIn(\"parameter.2\", hlo_text)\n\n def test_xla_computation_return_shape(self):\n _, shape_tree = api.xla_computation(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n return_shape=True)(np.int32(1))\n expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n self.assertEqual(shape_tree, expected)\n\n def test_xla_computation_partitioned(self):\n def f(x, y):\n return jnp.dot(x, y) + 1\n\n x = jax.ShapeDtypeStruct((8, 8), np.float32)\n y = jax.ShapeDtypeStruct((8, 16), np.float32)\n xla_comp = api.xla_computation(f, in_parts=(P(2, 2), None),\n out_parts=P(4, 1))(x, y)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn('sharding={devices=[2,2]0,1,2,3}', hlo_text)\n self.assertIn('sharding={replicated}', hlo_text)\n self.assertIn('sharding={{devices=[4,1]0,1,2,3}}', hlo_text)\n\n def test_xla_computation_replicated_and_partitioned(self):\n def f(x, y):\n return jnp.dot(x, y), lax.psum(x, 'i')\n\n x = jax.ShapeDtypeStruct((8, 8), np.float32)\n y = jax.ShapeDtypeStruct((8, 16), np.float32)\n axis_env = [('i', 4)]\n xla_comp = api.xla_computation(f, axis_env=axis_env,\n in_parts=(P(2, 2), None),\n out_parts=(P(4, 1), None))(x, y)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn('all-reduce', hlo_text)\n self.assertIn('replica_groups={{0,1,2,3}}', hlo_text)\n self.assertIn('sharding={devices=[2,2]0,1,2,3}', hlo_text)\n self.assertIn('sharding={replicated}', hlo_text)\n self.assertIn('sharding={{devices=[4,1]0,1,2,3}, {replicated}}', hlo_text)\n\n def test_xla_computation_psum_constant(self):\n f = lambda: jax.lax.psum(1, \"i\")\n api.xla_computation(f, axis_env=[(\"i\", 2)])() # doesn't crash\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n @jtu.ignore_warning(message=\"Some donated buffers were not usable\")\n def test_xla_computation_donate_argnums(self):\n api.xla_computation(lambda x: None, donate_argnums=(0,))(3) # doesn't crash\n\n def test_xla_computation_lower_fun_axis_env(self):\n axis_name = 'i'\n def fn(x):\n y = lax.all_gather(\n x, axis_name=axis_name)\n return y * lax.axis_index(axis_name).astype(jnp.float32)\n\n input_x = jnp.ones((5,6,4))\n axis_env = [(axis_name, api.local_device_count())]\n _ = api.xla_computation(fn, axis_env=axis_env, backend='cpu')(input_x)\n\n def test_xla_computation_axis_env(self):\n def fn(x):\n z = x * jax.lax.axis_index('i').astype(jnp.float32)\n def inner_fn(carry, a):\n return carry + a, ()\n return jax.lax.scan(inner_fn, jnp.zeros_like(z[0]), z)\n\n x = jnp.ones((5, 6, 4))\n _ = jax.xla_computation(fn, axis_env=(('i', 8),), backend='cpu')(x)\n\n def test_concurrent_device_get_and_put(self):\n def f(x):\n for _ in range(100):\n y = jax.device_put(x)\n x = jax.device_get(y)\n return x\n\n xs = [np.random.randn(i) for i in range(10)]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [executor.submit(partial(f, x)) for x in xs]\n ys = [f.result() for f in futures]\n for x, y in zip(xs, ys):\n self.assertAllClose(x, y)\n\n def test_dtype_warning(self):\n # cf. issue #1230\n if config.x64_enabled:\n raise unittest.SkipTest(\"test only applies when x64 is disabled\")\n\n def check_warning(warn, nowarn):\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n\n nowarn() # get rid of extra startup warning\n\n prev_len = len(w)\n nowarn()\n assert len(w) == prev_len\n\n warn()\n assert len(w) > 0\n msg = str(w[-1].message)\n expected_prefix = \"Explicitly requested dtype \"\n self.assertEqual(expected_prefix, msg[:len(expected_prefix)])\n\n prev_len = len(w)\n nowarn()\n assert len(w) == prev_len\n\n check_warning(lambda: jnp.array([1, 2, 3], dtype=\"float64\"),\n lambda: jnp.array([1, 2, 3], dtype=\"float32\"))\n check_warning(lambda: jnp.array([1, 2, 3], dtype=\"float64\"),\n lambda: jnp.array([1, 2, 3], dtype=float))\n check_warning(lambda: jnp.ones(3, dtype=np.float64),\n lambda: jnp.ones(3))\n check_warning(lambda: jnp.ones(3, dtype=np.float64),\n lambda: jnp.ones(3, dtype=float))\n check_warning(lambda: jnp.ones_like(3, dtype=np.int64),\n lambda: jnp.ones_like(3, dtype=np.int32))\n check_warning(lambda: jnp.zeros(3, dtype=\"int64\"),\n lambda: jnp.zeros(3, dtype=\"int32\"))\n check_warning(lambda: jnp.zeros_like(3, dtype=\"float64\"),\n lambda: jnp.zeros_like(3, dtype=\"float32\"))\n check_warning(lambda: jnp.full((2, 3), 1, dtype=\"int64\"),\n lambda: jnp.full((2, 3), 1))\n check_warning(lambda: jnp.ones(3).astype(\"float64\"),\n lambda: jnp.ones(3).astype(\"float32\"))\n check_warning(lambda: jnp.eye(3, dtype=np.float64),\n lambda: jnp.eye(3))\n check_warning(lambda: jnp.arange(3, dtype=np.float64),\n lambda: jnp.arange(3, dtype=np.float32))\n check_warning(lambda: jnp.linspace(0, 3, dtype=np.float64),\n lambda: jnp.linspace(0, 3, dtype=np.float32))\n check_warning(lambda: jnp.tri(2, dtype=\"float64\"),\n lambda: jnp.tri(2, dtype=\"float32\"))\n check_warning(lambda: jnp.arange(1).astype(\"float64\"),\n lambda: jnp.arange(1).astype(float))\n check_warning(lambda: jnp.arange(1.0).astype(\"int64\"),\n lambda: jnp.arange(1.0).astype(int))\n\n def test_error_for_invalid_dtype(self):\n with self.assertRaisesRegex(TypeError, \".*not a valid JAX array type.*\"):\n lax.add(jnp.array(7), np.array(\"hello\"))\n\n def test_vmap_preserves_docstr(self):\n def superfun(a):\n \"\"\"Does things with stuff.\"\"\"\n pass\n\n self.assertRegex(api.vmap(superfun).__doc__, \"\\n\".join([\n \"Vectorized version of superfun.*\",\n \"\",\n \"Original documentation:\",\n \"\",\n superfun.__doc__,\n ]))\n\n def test_vmap_in_axes_list(self):\n # https://github.com/google/jax/issues/2367\n dictionary = {'a': 5., 'b': jnp.ones(2)}\n x = jnp.zeros(3)\n y = jnp.arange(3.)\n\n\n def f(dct, x, y):\n return dct['a'] + dct['b'] + x + y\n\n out1 = api.vmap(f, (None, 0, 0))(dictionary, x, y)\n out2 = api.vmap(f, [None, 0, 0])(dictionary, x, y)\n self.assertAllClose(out1, out2)\n\n def test_vmap_in_axes_tree_prefix_error(self):\n # https://github.com/google/jax/issues/795\n value_tree = jnp.ones(3)\n self.assertRaisesRegex(\n ValueError,\n \"vmap in_axes specification must be a tree prefix of the corresponding \"\n r\"value, got specification \\(0, 0\\) for value tree \"\n + re.escape(f\"{tree_util.tree_structure((value_tree,))}.\"),\n lambda: api.vmap(lambda x: x, in_axes=(0, 0))(value_tree)\n )\n\n def test_vmap_in_axes_leaf_types(self):\n with self.assertRaisesRegex(\n TypeError, r\"vmap in_axes must be an int, None, or .*\"):\n api.vmap(lambda x: x, in_axes=(jnp.array([1., 2.]),))(jnp.array([1., 2.]))\n\n def test_vmap_out_axes_leaf_types(self):\n with self.assertRaisesRegex(\n TypeError, r\"vmap out_axes must be an int, None, or .*\"):\n api.vmap(lambda x: x, out_axes=(jnp.array([1., 2.]),))(jnp.array([1., 2.]))\n\n def test_vmap_unbatched_object_passthrough_issue_183(self):\n # https://github.com/google/jax/issues/183\n fun = lambda f, x: f(x)\n vfun = api.vmap(fun, (None, 0))\n ans = vfun(lambda x: x + 1, jnp.arange(3))\n self.assertAllClose(ans, np.arange(1, 4), check_dtypes=False)\n\n def test_vmap_mismatched_axis_sizes_error_message_issue_705(self):\n # https://github.com/google/jax/issues/705\n def h(a, b):\n return jnp.sum(a) + jnp.sum(b)\n\n X = np.random.randn(10, 4)\n U = np.random.randn(10, 2)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n \"so\\n\"\n \"arg 0 has an axis to be mapped of size 10\\n\"\n \"arg 1 has an axis to be mapped of size 2\"):\n api.vmap(h, in_axes=(0, 1))(X, U)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n r\"arg 2 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n \"so\\n\"\n \"args 0, 2 have axes to be mapped of size 10\\n\"\n \"arg 1 has an axis to be mapped of size 2\"):\n api.vmap(lambda x, y, z: None, in_axes=(0, 1, 0))(X, U, X)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n \"the tree of axis sizes is:\\n\"\n r\"\\(10, \\[2, 2\\]\\)\"):\n api.vmap(h, in_axes=(0, 1))(X, [U, U])\n\n error = (r\"vmap was requested to map its argument along axis 0, which \"\n r\"implies that its rank should be at least 1, but is only 0 \"\n r\"\\(its shape is \\(\\)\\)\")\n with self.assertRaisesRegex(ValueError, error):\n # The mapped inputs cannot be scalars\n api.vmap(lambda x: x)(1.)\n\n with self.assertRaisesRegex(\n ValueError, \"vmap must have at least one non-None value in in_axes\"):\n # If the output is mapped, there must be a non-None in_axes\n api.vmap(lambda x: x, in_axes=None)(jnp.array([1., 2.]))\n\n error = (r\"vmap was requested to map its argument along axis 1, which \"\n r\"implies that its rank should be at least 2, but is only 1 \"\n r\"\\(its shape is \\(2,\\)\\)\")\n with self.assertRaisesRegex(ValueError, error):\n api.vmap(lambda x: x, in_axes=1)(jnp.array([1., 2.]))\n\n # Error is: TypeError: only integer scalar arrays can be converted to a scalar index\n with self.assertRaisesRegex(\n ValueError,\n \"vmap out_axes specification must be a tree prefix of the \"\n \"corresponding value.*\"):\n api.vmap(lambda x: x, in_axes=0, out_axes=(2, 3))(jnp.array([1., 2.]))\n\n with self.assertRaisesRegex(\n ValueError,\n r\"vmap has mapped output \\(axis_name=foo\\) but out_axes is None\"):\n # If the output is mapped (user-named axis), then there must be some\n # out_axes specified.\n api.vmap(lambda x: x, out_axes=None, axis_name=\"foo\")(jnp.array([1., 2.]))\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap has mapped output but out_axes is None\"):\n # If the output is mapped (unnamed axis), then there must be some out_axes\n # specified.\n api.vmap(lambda x: x, out_axes=None)(jnp.array([1., 2.]))\n\n def test_vmap_structured_in_axes(self):\n\n A, B, C, D = 2, 3, 4, 5\n K = 6 # batch size\n x = np.ones((K, A, B)) # batch axis in different locations\n y = np.ones((B, K, C))\n z = np.ones((C, D, K))\n\n def foo(tree_arg):\n x, (y, z) = tree_arg\n return jnp.dot(x, jnp.dot(y, z))\n\n tree = (x, (y, z))\n vfoo = api.vmap(foo, in_axes=((0, (1, 2)),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n tree = (x, Point(y, z))\n vfoo = api.vmap(foo, in_axes=((0, Point(1, 2)),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n def foo(tree_arg):\n x, dct = tree_arg\n y, z = dct['a'], dct['b']\n return jnp.dot(x, jnp.dot(y, z))\n\n tree = (x, {'a': y, 'b': z})\n vfoo = api.vmap(foo, in_axes=((0, {'a': 1, 'b': 2}),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n tree = (x, collections.OrderedDict([('a', y), ('b', z)]))\n vfoo = api.vmap(\n foo, in_axes=((0, collections.OrderedDict([('a', 1), ('b', 2)])),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n def test_vmap_in_axes_bool_error(self):\n # https://github.com/google/jax/issues/6372\n with self.assertRaisesRegex(TypeError, \"must be an int\"):\n api.vmap(lambda x: x, in_axes=False)(jnp.zeros(3))\n\n def test_pmap_in_axes_bool_error(self):\n # https://github.com/google/jax/issues/6372\n with self.assertRaisesRegex(TypeError, \"must be an int\"):\n api.pmap(lambda x: x, in_axes=False)(jnp.zeros(1))\n\n def test_pmap_global_cache(self):\n def f(x, y):\n return x, y\n\n x = np.ones((1, 1, 1))\n\n # All defaults\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f)(x, x)\n\n # With axis name\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f, 'i')(x, x)\n\n # With in_axes and out_axes\n for x_in, y_in, x_out, y_out in it.product(*((0, 1, 2) for _ in range(4))):\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f, 'i', in_axes=(x_in, y_in), out_axes=(x_out, y_out))(x, x)\n\n # Forward-mode AD on the outside\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.jvp(api.pmap(f), (x, x), (x, x))\n\n # Reverse-mode AD on the outside. One compilation for forward, one for backward.\n with jtu.assert_num_jit_and_pmap_compilations(2):\n for _ in range(2):\n api.vjp(api.pmap(f), x, x)[1]((x, x))\n\n def test_device_array_repr(self):\n rep = jnp.ones(()) + 1.\n self.assertStartsWith(repr(rep), \"DeviceArray\")\n\n def test_device_array_hash(self):\n rep = jnp.ones(()) + 1.\n self.assertIsInstance(rep, jax.interpreters.xla.DeviceArray)\n self.assertNotIsInstance(rep, collections.abc.Hashable)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(rep)\n\n def test_grad_without_enough_args_error_message(self):\n # https://github.com/google/jax/issues/1696\n def f(x, y): return x + y\n df = api.grad(f, argnums=0)\n self.assertRaisesRegex(\n TypeError,\n \"differentiating with respect to argnums=0 requires at least 1 \"\n \"positional arguments to be passed by the caller, but got only 0 \"\n \"positional arguments.\",\n lambda: partial(df, x=0.)(y=1.))\n\n def test_grad_of_jit_compilation_caching(self):\n if not hasattr(self, \"assertLogs\"):\n raise unittest.SkipTest(\"test requires assertLogs (python 3)\")\n\n lax.add(1, 2) # make sure some initial warnings are already printed\n\n sin = api.jit(jnp.sin)\n\n prev_level = logging.get_verbosity()\n try:\n logging.set_verbosity('DEBUG')\n with self.assertLogs(level=logging.DEBUG) as l:\n ans1 = api.grad(sin)(2.)\n ans2 = api.grad(sin)(3.)\n finally:\n logging.set_verbosity(prev_level)\n self.assertLen(l.output, 2)\n\n self.assertAllClose(ans1, np.cos(2.), check_dtypes=False)\n self.assertAllClose(ans2, np.cos(3.), check_dtypes=False)\n\n def test_grad_does_not_unflatten_tree_with_none(self):\n # https://github.com/google/jax/issues/7546\n class CustomNode(list):\n pass\n\n def unflatten(unused_aux_data, children):\n self.assertIsNotNone(children[0])\n return CustomNode(children)\n\n tree_util.register_pytree_node(CustomNode, lambda x: (x, None), unflatten)\n grad(lambda x: x[0])(CustomNode([0.]))\n\n def test_trivial_computations(self):\n x = jnp.array([1, 2, 3])\n y = api.jit(lambda x: x)(x)\n self.assertIs(x, y)\n\n z1, z2 = api.jit(lambda x: (x, x))(x)\n self.assertIs(z1, z2)\n\n x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])\n z1, z2, z3 = api.jit(lambda x, y: (y, 1, x))(x1, x2)\n self.assertIs(z1, x2)\n self.assertIs(z3, x1)\n self.assertEqual(z2, 1)\n\n def test_nested_jit_hoisting(self):\n @api.jit\n def f(x, y):\n z = 2 * x\n return y + z, 3\n\n @api.jit\n def g(x):\n return f(2, x)\n\n jaxpr_subcomp = xla.jaxpr_subcomp\n\n jaxprs = []\n def jaxpr_subcomp_and_collect(c, jaxpr, *args, **kwargs):\n jaxprs.append(jaxpr)\n return jaxpr_subcomp(c, jaxpr, *args, **kwargs)\n\n try:\n xla.jaxpr_subcomp = jaxpr_subcomp_and_collect\n ans = g(3)\n finally:\n xla.jaxpr_subcomp = jaxpr_subcomp\n\n self.assertEqual(ans, (7, 3))\n self.assertLen(jaxprs, 2)\n outer_jaxpr, inner_jaxpr = jaxprs\n\n self.assertLen(outer_jaxpr.eqns, 1)\n self.assertEqual(outer_jaxpr.eqns[0].primitive.name, 'xla_call')\n subjaxpr_1 = outer_jaxpr.eqns[0].params[\"call_jaxpr\"]\n self.assertEqual(str(subjaxpr_1), str(inner_jaxpr))\n self.assertLen(inner_jaxpr.eqns, 2)\n self.assertEqual(inner_jaxpr.eqns[-2].primitive.name, 'mul')\n self.assertEqual(inner_jaxpr.eqns[-1].primitive.name, 'add')\n\n def test_primitive_compilation_cache(self):\n with jtu.count_primitive_compiles() as count:\n lax.add(1, 2)\n lax.add(2, 3)\n self.assertEqual(count[0], 1)\n\n def test_arange_jit(self):\n # see https://github.com/google/jax/issues/553\n def fun(x):\n r = jnp.arange(x.shape[0])[x]\n return r\n\n jit(fun)(jnp.array([0, 1, 2], dtype=jnp.int32)) # doesn't crash\n\n def helper_save_tracer(self, x):\n self._saved_tracer = x\n return x\n\n def test_escaped_tracers_different_top_level_traces(self):\n api.jit(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n UnexpectedTracerError, \"Encountered an unexpected tracer\"):\n api.jit(lambda x: self._saved_tracer)(0.)\n\n def test_escaped_tracers_cant_lift_sublevels(self):\n api.jit(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer\",\n re.DOTALL)):\n api.jit(lambda x: x)(self._saved_tracer)\n\n def test_escaped_tracers_tracer_from_higher_level(self):\n api.grad(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer.*Tracer from a higher level\",\n re.DOTALL)):\n api.grad(lambda x: x)(self._saved_tracer)\n\n def test_escaped_tracers_incompatible_sublevel(self):\n def func1(x):\n api.jit(self.helper_save_tracer)(0.)\n # Use the tracer\n return x + self._saved_tracer\n with self.assertRaisesRegex(\n UnexpectedTracerError,\n re.compile(\"Encountered an unexpected tracer\",\n re.DOTALL)):\n api.jit(func1)(2.)\n\n def test_escaped_tracers_cant_lift(self):\n def func1(x):\n api.grad(self.helper_save_tracer)(0.)\n return x + self._saved_tracer\n with self.assertRaisesRegex(\n UnexpectedTracerError,\n re.compile(\"Encountered an unexpected tracer.*Can't lift\",\n re.DOTALL)):\n api.grad(func1)(2.)\n\n def test_escaped_tracers_not_among_input_tracers(self):\n def func1(x):\n api.grad(self.helper_save_tracer)(x)\n # Use the tracer\n return x + self._saved_tracer\n\n with self.assertRaisesRegex(\n UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer.*Tracer not among input tracers\",\n re.DOTALL)):\n api.jit(func1)(2.)\n\n def test_escaped_tracer_omnistaging(self):\n count = 1\n\n @jit\n def f():\n nonlocal count\n count = jnp.add(count, 1)\n f() # leaked a tracer! but currently undetected\n\n def f(x, c):\n jnp.add(count, 1)\n return None, None\n\n @jit\n def g():\n lax.scan(f, None, None, length=2)\n\n with self.assertRaisesRegex(UnexpectedTracerError,\n \"was created on line\"):\n g()\n\n def test_escaped_tracer_omnistaging_top_trace(self):\n count = 1\n\n def f(_, __):\n nonlocal count\n count = jnp.add(count, 1)\n return None, None\n\n lax.scan(f, None, None, length=2) # leaked a tracer! (of level 1!)\n\n with self.assertRaisesRegex(UnexpectedTracerError,\n \"was created on line\"):\n # The following call will try and raise the ones array to the count tracer\n # level, which is no longer live.\n jax.jit(jnp.add)(jnp.ones(()), count)\n\n def test_escaped_tracer_transform_name(self):\n with self.assertRaisesRegex(UnexpectedTracerError,\n \"for jit\"):\n jax.jit(self.helper_save_tracer)(1)\n _ = self._saved_tracer+1\n\n with self.assertRaisesRegex(UnexpectedTracerError,\n \"for pmap\"):\n jax.pmap(self.helper_save_tracer)(jnp.ones((1, 2)))\n _ = self._saved_tracer+1\n\n with self.assertRaisesRegex(UnexpectedTracerError,\n \"for eval_shape\"):\n jax.eval_shape(self.helper_save_tracer, 1)\n _ = self._saved_tracer+1\n\n def test_escaped_tracer_shape_dtype(self):\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n r\"shape \\(4, 3\\) and dtype int32\"):\n jax.jit(self.helper_save_tracer)(jnp.ones((4, 3), dtype=jnp.int32))\n _ = self._saved_tracer+1\n\n def test_pmap_static_kwarg_error_message(self):\n # https://github.com/google/jax/issues/3007\n def f(a, b):\n return a + b\n\n g = jax.pmap(f, static_broadcasted_argnums=(1,))\n\n msg = (r\"pmapped function has static_broadcasted_argnums=\\(1,\\) but was \"\n r\"called with only 1 positional argument. All static broadcasted \"\n r\"arguments must be passed positionally.\")\n with self.assertRaisesRegex(ValueError, msg):\n g(jnp.ones((1, 1)), b=1)\n\n def test_vmap_unmapped_last(self):\n @partial(jax.vmap, out_axes=-1)\n def f(x):\n return np.zeros((2,))\n f(np.zeros((5,)))\n\n # TODO(jakevdp): re-enable this if possible.\n @unittest.skipIf(True, \"broken by convert_element_type change.\")\n def test_xla_constant_dedup(self):\n y = np.array([7, 14], dtype=np.float32)\n def f(x):\n return x + y + y\n\n x = np.array([1, 2], dtype=np.float32)\n hlo_lines = jax.xla_computation(f)(x).as_hlo_text().split('\\n')\n hlo_lines = set([s.strip() for s in hlo_lines])\n self.assertIn('constant.1 = f32[2]{0} constant({7, 14})', hlo_lines)\n self.assertNotIn('constant.2 = f32[2]{0} constant({7, 14})', hlo_lines)\n\n def test_eval_context(self):\n @jit\n def f():\n with core.eval_context():\n assert jnp.add(1, 1) == 2\n\n f() # doesn't crash\n\n def test_concrete_error_because_arg_unary(self):\n @jax.jit\n def f(x):\n if x > 0:\n return x\n else:\n return 0\n\n msg = r\"on the value of the argument 'x'\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1)\n\n def test_concrete_error_because_arg_binary(self):\n @jax.jit\n def f(x, y):\n if x > y:\n return x\n else:\n return y\n\n msg = r\"on the values of the arguments 'x' and 'y'\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, 2)\n\n def test_concrete_error_because_arg_ternary(self):\n @jax.jit\n def f(x, y, z):\n if x > z:\n return x\n else:\n return y\n\n msg = r\"on the values of the arguments 'x' and 'z'\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, 2, 3)\n\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, 2, z=3)\n\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, y=2, z=3)\n\n def test_concrete_error_because_arg_varargs(self):\n @jax.jit\n def f(*args):\n x, y, z = args\n if x > z:\n return x\n else:\n return y\n\n msg = r\"on the values of the argument 'args'\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, 2, 3)\n\n def test_concrete_error_because_arg_kwargs(self):\n @jax.jit\n def f(**kwargs):\n x, y, z = kwargs['x'], kwargs['y'], kwargs['z']\n if x > z:\n return x\n else:\n return y\n\n msg = r\"on the values of the argument 'kwargs'\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(x=1, y=2, z=3)\n\n def test_concrete_error_because_arg_pytree(self):\n @jax.jit\n def f(xy, z):\n x, y = xy\n if x > 0:\n return x\n else:\n return y\n\n msg = r\"on the value of the argument 'xy'\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f((1, 2), z=3)\n\n def test_concrete_error_because_const(self):\n @jax.jit\n def f():\n assert jnp.add(1, 1) > 0\n\n msg = \"on these lines\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f()\n\n def test_xla_computation_zeros_doesnt_device_put(self):\n with jtu.count_device_put() as count:\n api.xla_computation(lambda: jnp.zeros(3))()\n self.assertEqual(count[0], 0)\n\n def test_join_concrete_arrays_with_omnistaging(self):\n # https://github.com/google/jax/issues/4622\n x = jnp.array([1., 2., 3.])\n y = jnp.array([1., 2., 4.])\n\n @jit\n def f():\n core.lattice_join(core.ConcreteArray(x), core.ConcreteArray(y))\n\n f() # doesn't crash\n\n def test_linearize_aval_error(self):\n # https://github.com/google/jax/issues/4622\n f = lambda x: x\n\n # these should not error\n _, f_jvp = api.linearize(f, 1.)\n f_jvp(1.)\n _, f_jvp = api.linearize(f, np.ones(2, np.int32))\n f_jvp(np.zeros(2, float0))\n\n # these should error\n _, f_jvp = api.linearize(f, 1.)\n with self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\n f_jvp(1)\n _, f_jvp = api.linearize(f, np.ones(2, np.int32))\n with self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\n f_jvp(np.ones(2, np.int32))\n\n def test_grad_of_token_consuming_primitive(self):\n # https://github.com/google/jax/issues/5463\n tokentest_p = core.Primitive(\"tokentest\")\n tokentest_p.def_impl(partial(xla.apply_primitive, tokentest_p))\n tokentest_p.def_abstract_eval(lambda x, y: x)\n xla.translations[tokentest_p] = lambda c, x, y: x\n ad.defjvp(tokentest_p, (lambda g, x, token: x), None)\n\n token = jax.lax.create_token(123)\n arr = jnp.ones((3, 2))\n res, vjp_fun = jax.vjp(lambda x: tokentest_p.bind(x, token), arr)\n # Should not crash.\n vjp_fun(arr)\n\n def test_jit_returning_token(self):\n x = jax.jit(jax.lax.create_token)(1.0)\n self.assertIsInstance(x, jax.interpreters.xla.Token)\n\n def test_leak_checker_catches_a_jit_leak(self):\n with jax.checking_leaks():\n lst = []\n\n @jit\n def f(x):\n lst.append(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked\"):\n f(3)\n\n def test_leak_checker_catches_a_pmap_leak(self):\n with jax.checking_leaks():\n lst = []\n\n @api.pmap\n def f(x):\n lst.append(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked\"):\n f(np.ones(1))\n\n def test_leak_checker_catches_a_grad_leak(self):\n with jax.checking_leaks():\n lst = []\n\n def f(x):\n lst.append(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n api.grad(f)(3.)\n\n def test_leak_checker_avoids_false_positives(self):\n with jax.checking_leaks():\n @jit\n def f(x):\n return x\n f(3) # doesn't crash\n api.vmap(f)(np.arange(3)) # doesn't crash\n api.grad(f)(3.) # doesn't crash\n\n @api.pmap\n def f(x):\n return x\n f(np.ones(1)) # doesn't crash\n api.vmap(f)(np.ones((1, 1))) # doesn't crash\n\n def test_leak_checker_catches_a_scan_leak(self):\n with jax.checking_leaks():\n lst = []\n\n to_scan = lambda c, x: (lst.append(c) or jnp.sin(c), None)\n\n with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n lax.scan(to_scan, 1., np.arange(3.))\n\n def test_leak_checker_avoids_false_positives_scan(self):\n with jax.checking_leaks():\n to_scan = lambda c, x: (jnp.sin(c), None)\n lax.scan(to_scan, 1., np.arange(3.)) # doesn't crash\n\n def test_leak_checker_avoids_false_positives_scan_jvp(self):\n with jax.checking_leaks():\n to_scan = lambda c, x: (c, None)\n\n def f(x):\n lax.scan(to_scan, x, None, length=1)\n api.jvp(f, (3.,), (1.,)) # doesn't crash\n\n def test_leak_checker_avoids_false_positives_scan_vmap(self):\n with jax.checking_leaks():\n to_scan = lambda c, _: (1., None)\n\n @api.vmap\n def f(x):\n lax.scan(to_scan, x, None, length=1)\n f(np.arange(5.)) # doesn't crash\n\n def test_leak_checker_avoids_false_positives_scan_vmap_2(self):\n with jax.checking_leaks():\n to_scan = lambda c, _: (c, None)\n\n @api.vmap\n def f(x):\n lax.scan(to_scan, x, None, length=1)\n f(np.arange(5.)) # doesn't crash\n\n def test_leak_checker_catches_a_sublevel_leak(self):\n with jax.checking_leaks():\n @jit\n def f(x):\n lst = []\n @jit\n def g(x):\n lst.append(x)\n return x\n\n x = g(x)\n return x\n\n with self.assertRaisesRegex(Exception, r\"Leaked sublevel\"):\n f(3)\n\n def test_leak_checker_avoids_false_positive_custom_jvp(self):\n # see https://github.com/google/jax/issues/5636\n with jax.checking_leaks():\n @api.custom_jvp\n def t(y):\n return y\n\n def t_jvp(p, t):\n pass\n\n t.defjvp(t_jvp)\n\n @jit\n def s(y):\n return t(y)\n s(3) # doesn't crash\n\n def test_default_backend(self):\n first_local_device = api.local_devices()[0]\n self.assertEqual(first_local_device.platform, api.default_backend())\n\n def test_dunder_jax_array(self):\n # https://github.com/google/jax/pull/4725\n\n class AlexArray:\n def __init__(self, jax_val):\n self.jax_val = jax_val\n def __jax_array__(self):\n return self.jax_val\n dtype = property(lambda self: self.jax_val.dtype)\n shape = property(lambda self: self.jax_val.shape)\n\n x = AlexArray(jnp.array([1., 2., 3.]))\n y = jnp.sin(x)\n self.assertAllClose(y, jnp.sin(jnp.array([1., 2., 3.])))\n y = api.grad(api.jit(lambda x: jnp.sin(x).sum()))(x)\n self.assertAllClose(y, jnp.cos(jnp.array([1., 2., 3.])))\n\n x = AlexArray(jnp.array([[1., 2., 3.]]))\n y = api.pmap(jnp.sin)(x)\n self.assertAllClose(y, jnp.sin(jnp.array([[1., 2., 3.]])))\n\n x = jnp.array(1)\n a = AlexArray(x)\n for f in [jnp.isscalar, jnp.size, jnp.shape, jnp.dtype]:\n self.assertEqual(f(x), f(a))\n\n def test_constant_handler_mro(self):\n # https://github.com/google/jax/issues/6129\n\n class Foo(enum.IntEnum):\n bar = 1\n\n @api.pmap\n def f(_):\n return Foo.bar\n\n ans = f(jnp.arange(1)) # doesn't crash\n expected = jnp.arange(1) + 1\n self.assertAllClose(ans, expected)\n\n def test_large_python_ints(self):\n with self.assertRaises(OverflowError):\n jnp.multiply(2 ** 100, 3.)\n\n out = lax.convert_element_type(2 ** 100, jnp.float32) # doesn't crash\n self.assertArraysEqual(out, np.float32(2 ** 100))\n\n def test_dot_precision_context_manager(self):\n x = jnp.zeros((2, 2))\n\n with jax.default_matmul_precision(None):\n jnp.dot(x, x) # doesn't crash\n jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n self.assertIn('precision=None', str(jaxpr))\n\n with jax.default_matmul_precision(\"bfloat16\"):\n x @ x # doesn't crash\n jaxpr = jax.make_jaxpr(op.matmul)(x, x)\n self.assertIn('Precision.DEFAULT', str(jaxpr))\n\n with jax.default_matmul_precision(\"tensorfloat32\"):\n jnp.dot(x, x) # doesn't crash\n jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n self.assertIn('Precision.HIGH', str(jaxpr))\n\n with jax.default_matmul_precision(\"float32\"):\n jnp.dot(x, x) # doesn't crash\n jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n self.assertIn('Precision.HIGHEST', str(jaxpr))\n\n dot = partial(jnp.dot, precision=lax.Precision.HIGHEST)\n with jax.default_matmul_precision(\"tensorfloat32\"):\n dot(x, x) # doesn't crash\n jaxpr = jax.make_jaxpr(dot)(x, x)\n self.assertIn('Precision.HIGHEST', str(jaxpr))\n\n def test_dot_precision_flag(self):\n x = jnp.zeros((2, 2))\n\n prev_val = config._read(\"jax_default_matmul_precision\")\n try:\n config.FLAGS.jax_default_matmul_precision = \"tensorfloat32\"\n jnp.dot(x, x) # doesn't crash\n jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n finally:\n config.FLAGS.jax_default_matmul_precision = prev_val\n self.assertIn('Precision.HIGH', str(jaxpr))\n self.assertEqual(prev_val, config._read(\"jax_default_matmul_precision\"))\n\n prev_val = config._read(\"jax_default_matmul_precision\")\n try:\n config.update('jax_default_matmul_precision','tensorfloat32')\n jnp.dot(x, x) # doesn't crash\n jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n finally:\n config.update('jax_default_matmul_precision', prev_val)\n self.assertIn('Precision.HIGH', str(jaxpr))\n self.assertEqual(prev_val, config._read(\"jax_default_matmul_precision\"))\n\n def test_dot_precision_forces_retrace(self):\n num_traces = 0\n\n def g(x):\n nonlocal num_traces\n num_traces += 1\n return jnp.dot(x, x)\n def f_cond(x):\n return lax.cond(True, g, g, x)\n\n @jax.jit\n def f_jit(x):\n nonlocal num_traces\n num_traces += 1\n return jnp.dot(x, x)\n\n for f in [f_jit, f_cond]:\n precision = config.jax_default_matmul_precision\n try:\n num_traces = 0\n x = jnp.zeros((2, 2))\n f(x)\n self.assertEqual(num_traces, 1)\n f(x)\n self.assertEqual(num_traces, 1)\n with jax.default_matmul_precision(\"tensorfloat32\"):\n f(x)\n self.assertEqual(num_traces, 2)\n FLAGS.jax_default_matmul_precision = \"float32\"\n f(x)\n self.assertGreaterEqual(num_traces, 2)\n nt = num_traces\n f(x)\n self.assertEqual(num_traces, nt + 1)\n f(x)\n self.assertEqual(num_traces, nt + 1)\n finally:\n FLAGS.jax_default_matmul_precision = precision\n\n def test_rank_promotion_forces_retrace(self):\n num_traces = 0\n\n def g(x):\n nonlocal num_traces\n num_traces += 1\n return x + x\n def f_cond(x):\n return lax.cond(True, g, g, x)\n\n @jax.jit\n def f_jit(x):\n nonlocal num_traces\n num_traces += 1\n return x + x\n\n for f in [f_jit, f_cond]:\n allow_promotion = config.jax_numpy_rank_promotion\n try:\n num_traces = 0\n @jax.jit\n def f(x):\n nonlocal num_traces\n num_traces += 1\n return x + x\n x = jnp.zeros((2, 2))\n f(x)\n self.assertEqual(num_traces, 1)\n f(x)\n self.assertEqual(num_traces, 1)\n with jax.numpy_rank_promotion(\"warn\"):\n f(x)\n self.assertEqual(num_traces, 2)\n FLAGS.jax_numpy_rank_promotion = \"raise\"\n f(x)\n self.assertGreaterEqual(num_traces, 2)\n nt = num_traces\n f(x)\n self.assertEqual(num_traces, nt + 1)\n f(x)\n self.assertEqual(num_traces, nt + 1)\n finally:\n FLAGS.jax_numpy_rank_promotion = allow_promotion\n\n def test_backward_pass_ref_dropping(self):\n refs = []\n\n @api.custom_vjp\n def f(x):\n return x\n def f_fwd(x):\n return x, None\n def f_rev(_, g):\n assert len(refs) != 2 or refs[0]() is None\n zero = np.zeros(())\n refs.append(weakref.ref(zero))\n return (zero,)\n f.defvjp(f_fwd, f_rev)\n\n api.grad(lambda x: f(f(f(x))))(1.)\n\n def test_custom_vjp_scan_batching_edge_case(self):\n # https://github.com/google/jax/issues/5832\n @jax.custom_vjp\n def mul(x, coeff): return x * coeff\n def mul_fwd(x, coeff): return mul(x, coeff), (x, coeff)\n def mul_bwd(res, g):\n x, coeff = res\n g_x = g * coeff\n g_coeff = (x * g).sum()\n return g_x, g_coeff\n mul.defvjp(mul_fwd, mul_bwd)\n\n def scan_over_mul(x, coeff):\n def f_(x, t):\n return mul(x, coeff), None\n y, _ = jax.lax.scan(f_, x, jnp.arange(3))\n return y\n\n key = jax.random.PRNGKey(0)\n key1, key2 = jax.random.split(key, 2)\n x_batch = jax.random.normal(key1, (3, 2))\n covector_batch = jax.random.normal(key2, (3, 2))\n coeff = jnp.array(1.)\n\n batched_scan_over_mul = jax.vmap(scan_over_mul, in_axes=(0, None), out_axes=0)\n res, vjp_fun = jax.vjp(batched_scan_over_mul, x_batch, coeff)\n vjp_fun(covector_batch) # doesn't crash\n\n jtu.check_grads(batched_scan_over_mul, (x_batch, coeff), order=2,\n modes=['rev'])\n\n def test_jit_inline(self):\n @partial(api.jit, inline=False)\n def f(x):\n return x * 2\n\n jaxpr = api.make_jaxpr(f)(3)\n self.assertIn('xla_call', str(jaxpr))\n\n @partial(api.jit, inline=True)\n def f(x):\n return x * 2\n\n jaxpr = api.make_jaxpr(f)(3)\n self.assertNotIn('xla_call', str(jaxpr))\n\n # Repro for https://github.com/google/jax/issues/7229.\n def test_compute_with_large_transfer(self):\n def f(x, delta):\n return x + jnp.asarray(delta, x.dtype)\n\n # A large and potentially unaligned array to trigger non-zero-copy and\n # async device array copy.\n xs = np.random.uniform(0., 1., size=(10, 131, 111, 3)).astype(np.float32)\n for x in xs:\n delta = np.random.uniform(-0.5, 0.5, size=())\n jitted_f = api.jit(f)\n np.testing.assert_allclose(jitted_f(x, delta), f(x, delta))\n\n def test_vjp_fun_jit(self):\n # test that the function returned by vjp can be returned\n # from and passed to jitted functions\n f = lambda x: 2. * x\n\n @partial(jit, static_argnums=0)\n def linearize_vjp(f, x):\n _, vjp_fun = api.vjp(f, x)\n return vjp_fun\n\n linearized = linearize_vjp(f, 1.)\n actual = jit(lambda f, x: f(x))(linearized, 3.)\n expected = (6.,)\n self.assertEqual(actual, expected)\n\n def test_linearize_fun_jit(self):\n # test that the function returned by linearize can be returned\n # from and passed to jitted functions\n f = lambda x: 2. * x\n\n @partial(jit, static_argnums=0)\n def linearize(f, x):\n _, jvp_fun = api.linearize(f, x)\n return jvp_fun\n\n linearized = linearize(f, 1.)\n actual = jit(lambda f, x: f(x))(linearized, 3.)\n expected = 6.\n self.assertEqual(actual, expected)\n\n def test_linear_transpose_fun_jit(self):\n # test that the function returned by linear_transpose can be returned\n # from and passed to jitted functions\n f = lambda x: 2. * x\n\n @partial(jit, static_argnums=0)\n def transpose(f, x):\n return api.linear_transpose(f, x)\n\n transposed = transpose(f, 1.)\n actual = jit(lambda f, x: f(x))(transposed, 3.)\n expected = (6.,)\n self.assertEqual(actual, expected)\n\n def test_leaked_tracer_issue_7613(self):\n # from https://github.com/google/jax/issues/7613\n import numpy.random as npr\n\n def sigmoid(x):\n return 1. / (1. + jnp.exp(-x))\n\n x = jnp.ones((50,))\n A = jnp.array(npr.randn(50, 50))\n\n @jax.jit\n def loss(A, x):\n h = jax.nn.sigmoid(A * x)\n return jnp.sum((h - x)**2)\n\n with jax.checking_leaks():\n _ = jax.grad(loss)(A, x) # doesn't crash\n\n def test_vmap_caching(self):\n # https://github.com/google/jax/issues/7621\n\n f = lambda x: jnp.square(x).mean()\n jf = jax.jit(f)\n x = jax.random.uniform(jax.random.PRNGKey(0), shape=(8, 4))\n\n with jtu.count_jit_and_pmap_compiles() as count: # noqa: F841\n for _ in range(5):\n jax.hessian(jf)(x).block_until_ready()\n\n n = count[0]\n # The exact number of compilations may vary depending on the number of\n # jit decorators in the function above, but it should not grow after an\n # initial warmup phase.\n for _ in range(5):\n jax.hessian(jf)(x).block_until_ready()\n\n self.assertEqual(count[0], n)\n\n def test_jnp_array_doesnt_device_put(self):\n with jtu.count_device_put() as count:\n api.make_jaxpr(lambda: jnp.array(3))()\n self.assertEqual(count[0], 0)\n\n\nclass RematTest(jtu.JaxTestCase):\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_basic(self, remat):\n @remat\n def g(x):\n return lax.sin(lax.sin(x)), 3.\n\n def f(x):\n x, _ = g(x)\n return x\n\n ans = f(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans, f_lin = api.linearize(f, 2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = f_lin(3.)\n expected = np.cos(np.sin(2.)) * np.cos(2.) * 3.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n sin_calls = []\n cos_calls = []\n sin_impl = lax.sin_p.impl\n cos_impl = lax.cos_p.impl\n try:\n lax.sin_p.def_impl(lambda x: sin_calls.append(1) or sin_impl(x))\n lax.cos_p.def_impl(lambda x: cos_calls.append(1) or cos_impl(x))\n f_lin(3.)\n finally:\n lax.sin_p.def_impl(sin_impl)\n lax.cos_p.def_impl(cos_impl)\n self.assertEqual(len(sin_calls), 1)\n self.assertEqual(len(cos_calls), 2)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_freevars(self, remat):\n def f1(x):\n y = 2 * jnp.sin(x)\n z = jnp.cos(x) * jnp.sin(y)\n return z\n\n def f2(x):\n y = 2 * jnp.sin(x)\n z = remat(lambda x: jnp.cos(x) * jnp.sin(y))(x)\n return z\n\n ans, f_lin = api.linearize(f2, 2.)\n expected, f_lin_expected = api.linearize(f1, 2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = f_lin(3.)\n expected = f_lin_expected(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_grad_python_control_flow(self):\n @partial(api.remat, concrete=True)\n def g(x):\n if x > 0:\n return lax.sin(x), 3.\n else:\n return lax.cos(x), 4.\n\n def f(x):\n x, _ = g(x)\n return x\n\n ans = f(2.)\n expected = np.sin(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f)(2.)\n expected = np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_jit(self, remat):\n @remat\n def g(x):\n return lax.sin(lax.sin(x))\n\n def f_(x):\n return g(x)\n f = api.jit(f_)\n\n ans = f(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f)(2.)\n expected = np.cos(np.sin(2.)) * np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(f_))(2.)\n expected = np.cos(np.sin(2.)) * np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_vmap(self, remat):\n @remat\n def g(x):\n return lax.sin(lax.sin(x))\n\n x = np.arange(3.)\n\n ans = api.vmap(g)(x)\n expected = np.sin(np.sin(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jacfwd(g)(x)\n expected = np.diag(np.cos(np.sin(x)) * np.cos(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jacrev(g)(x)\n expected = np.diag(np.cos(np.sin(x)) * np.cos(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_higher_order_autodiff(self, remat):\n def f(x):\n return lax.cos(lax.sin(x))\n g = remat(f)\n\n ans = api.grad(api.grad(g))(3.)\n expected = api.grad(api.grad(f))(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_scan(self):\n to_scan = lambda c, x: (jnp.sin(c), None)\n\n def f_noremat(x):\n y, _ = lax.scan(to_scan, x, np.arange(3.))\n return y\n\n def f_yesremat(x):\n y, _ = lax.scan(api.remat(to_scan), x, np.arange(3.))\n return y\n\n ans = f_yesremat(4.)\n expected = f_noremat(4.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f_yesremat)(4.)\n expected = api.grad(f_noremat)(4.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n jaxpr = api.make_jaxpr(api.linearize(f_yesremat, 4.)[1])(1.)\n scan_eqn, = jaxpr.jaxpr.eqns\n self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\n\n jaxpr = api.make_jaxpr(api.vjp(f_yesremat, 4.)[1])(1.)\n scan_eqn, = jaxpr.jaxpr.eqns\n self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_no_redundant_flops(self, remat):\n # see https://github.com/google/jax/pull/1749#issuecomment-558267584\n\n @api.jit\n def g(x):\n return f(2., x)\n\n @remat\n def f(x, y):\n return jnp.sin(x) * y\n\n # We swap out sin_p's impl rule to count how many times it's invoked\n called = []\n sin_impl = lax.sin_p.impl\n try:\n lax.sin_p.def_impl(lambda x: called.append(1) or sin_impl(x))\n api.grad(g)(3.)\n finally:\n lax.sin_p.def_impl(sin_impl)\n num_calls = len(called)\n self.assertLessEqual(num_calls, 1)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_binomial_checkpointing(self, remat):\n def binom_checkpoint(funs):\n if len(funs) == 1:\n return funs[0]\n else:\n f1 = binom_checkpoint(funs[:len(funs)//2])\n f2 = binom_checkpoint(funs[len(funs)//2:])\n return remat(lambda x: f1(f2(x)))\n\n f1 = binom_checkpoint([jnp.sin, jnp.sin, jnp.sin, jnp.sin])\n f2 = lambda x: jnp.sin(jnp.sin(jnp.sin(jnp.sin(x))))\n x = 4.\n self.assertAllClose(f1(x), f2(x), check_dtypes=False)\n self.assertAllClose(api.grad(f1)(x), api.grad(f2)(x), check_dtypes=False)\n\n def test_remat_symbolic_zeros(self):\n # code from https://github.com/google/jax/issues/1907\n\n key = jax.random.PRNGKey(0)\n key, split = jax.random.split(key)\n n = 5\n\n def func(D0):\n def shift(R, dR, **unused_kwargs):\n return R + dR\n\n def apply_fn(R):\n return D0 * R\n\n Rinit = jax.random.uniform(split, (n,3), minval=0.0, maxval=5.0,\n dtype=jnp.float32)\n\n def move(R,i):\n F = apply_fn(R)\n return shift(R, 0.001 * F), jnp.array([0.])\n\n move = api.remat(move)\n R, temp = lax.scan(move, Rinit, jnp.arange(2))\n return R[0, 0]\n\n api.grad(func)(5.0) # doesn't crash\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_jit2(self, remat):\n @api.jit\n def f(x):\n y = 2 * x\n\n @remat\n def g():\n return y\n\n return g()\n\n self.assertAllClose(f(3), 6, check_dtypes=False)\n\n def test_remat_nontrivial_env(self):\n # simplified from https://github.com/google/jax/issues/2030\n\n @api.remat\n def foo(state, dt=0.5, c=1):\n u, u_t = state\n u_tt = c**2 * u\n u_t = u_t + u_tt * dt\n return (u, u_t)\n\n @partial(api.jit, static_argnums=(1,))\n def _multi_step(state, count, dt, c):\n f = lambda s, _: (foo(s, dt, c), _)\n return lax.scan(f, state, None, count)\n\n def multi_step(state, count, dt=1/jnp.sqrt(2), c=1):\n return _multi_step(state, count, dt, c)\n\n def loss(u0, target, steps, dt=1/jnp.sqrt(2), c=1):\n init = (u0, jnp.zeros_like(u0))\n (uf, _), _ = multi_step(init, steps, dt, c)\n return ((uf - target) ** 2).mean()\n\n target = jnp.zeros((128, 128))\n u0 = jnp.ones_like(target)\n loss(u0, target, 10) # doesn't crash\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_jit3(self, remat):\n # https://github.com/google/jax/issues/2180\n def f(w, x):\n a = jnp.dot(x, w)\n b = jnp.einsum(\"btd,bTd->btT\", a, a)\n c = jnp.einsum(\"btT,btd->btd\", b, a)\n return jnp.sum(c)\n\n w = jnp.ones([1, 1])\n x = jnp.ones([1, 1, 1])\n f = remat(f)\n api.grad(f)(w, x) # doesn't crash\n\n @api.jit\n def mul(a, b):\n return a * b\n\n def f(w, x):\n a = mul(w, x)\n b = mul(a, a)\n return b\n\n w = 1.\n x = 1.\n f = remat(f)\n api.grad(f)(w, x) # doesn't crash\n\n def test_remat_scan2(self):\n # https://github.com/google/jax/issues/1963\n\n def scan_bug(x0):\n f = lambda x, _: (x + 1, None)\n def scanned_f(x, _):\n return lax.scan(f, x, xs=None, length=1)[0], None\n x, _ = jax.remat(scanned_f)(x0, None)\n return x\n\n jax.grad(scan_bug)(1.0) # doesn't crash\n\n def test_remat_jit_static_argnum_omnistaging(self):\n # https://github.com/google/jax/issues/2833\n # NOTE(mattjj): after #3370, this test doesn't actually call remat...\n def named_call(f):\n def named_f(*args):\n f_ = lu.wrap_init(lambda: (f(*args),))\n out, = core.call_p.bind(f_)\n return out\n return named_f\n\n def f(a_bool, y):\n if a_bool:\n return y + 1\n else:\n return y\n\n api.jit(named_call(f), static_argnums=0)(True, 1) # no crash\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_remat_eval_counter(self, remat):\n # https://github.com/google/jax/issues/2737\n add_one_p = Primitive('add_one')\n add_one = add_one_p.bind\n\n num_evals = 0\n\n @contextmanager\n def assertEvals(n):\n start = num_evals\n yield\n assert num_evals - start == n\n\n def add_one_impl(x):\n nonlocal num_evals\n num_evals += 1\n return x + 1\n add_one_p.def_impl(add_one_impl)\n\n def add_one_jvp(pin, tin):\n pout = add_one(pin[0])\n return pout, pout * tin[0]\n ad.primitive_jvps[add_one_p] = add_one_jvp\n\n add_one_p.def_abstract_eval(lambda x: x)\n\n v = np.zeros((1,))\n\n f = remat(add_one)\n g = remat(lambda x: add_one(f(x)))\n\n # 2 calls needed to evaluate g\n with assertEvals(2):\n _, vjp = jax.vjp(g, v)\n # 2 calls made while transposing g, 1 call made while transposing f\n with assertEvals(3):\n vjp(v)\n\n @jax._src.util.curry\n def call(f, *args):\n return jax.core.call(\n jax.linear_util.wrap_init(lambda *args: [f(*args)]),\n *args, name='foo')[0]\n\n f = call(add_one)\n g = remat(lambda x: add_one(f(x)))\n\n # 2 calls needed to evaluate g\n with assertEvals(2):\n _, vjp = jax.vjp(g, v)\n # 2 calls made while transposing g, no reevaluation for transposition of f\n with assertEvals(2):\n vjp(v)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_escaped_tracer_remat(self, remat):\n # b/169779185\n def f():\n seq = [jnp.zeros([])]\n def g():\n seq[0] += 1 # this is line 7 btw\n return seq[0]\n\n remat(g)()\n remat(g)()\n\n with self.assertRaisesRegex(UnexpectedTracerError, \"global state\"):\n api.jit(f)()\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"{suffix}\", \"remat\": remat}\n for suffix, remat in [\n ('', api.remat),\n ('_policy', partial(api.remat, policy=lambda *_, **__: False))\n ])\n def test_no_cse_widget_on_primals(self, remat):\n @remat\n def g(x):\n return lax.sin(lax.sin(x)), 3.\n\n def f(x):\n x, _ = g(x)\n return x\n\n c = api.xla_computation(f)(2.)\n self.assertNotIn('while', c.as_hlo_text())\n self.assertNotIn('conditional', c.as_hlo_text())\n\n c = api.xla_computation(grad(f))(2.)\n text = c.as_hlo_text()\n self.assertTrue('while' in text or 'conditional' in text)\n\n def test_no_cse_widget_with_prevent_cse_false(self):\n @partial(api.remat, prevent_cse=False)\n def g(x):\n return lax.sin(lax.sin(x)), 3.\n\n def f(x):\n x, _ = g(x)\n return x\n\n c = api.xla_computation(f)(2.)\n self.assertNotIn('while', c.as_hlo_text())\n self.assertNotIn('conditional', c.as_hlo_text())\n\n c = api.xla_computation(grad(f))(2.)\n self.assertNotIn('while', c.as_hlo_text())\n self.assertNotIn('conditional', c.as_hlo_text())\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{policy_name}\", \"policy\": policy,\n \"in_jaxpr2\": in_jaxpr2, \"not_in_jaxpr2\": not_in_jaxpr2}\n for policy_name, policy, in_jaxpr2, not_in_jaxpr2 in [\n ('save_anything', lambda *_, **__: True, [], [' sin ', ' cos ']),\n ('save_nothing', lambda *_, **__: False, [' sin ', ' cos '], []),\n ('save_sin', lambda p, *_, **__: str(p) == 'sin', [' cos '], [' sin ']),\n ])\n def test_remat_custom_policy(self, policy, in_jaxpr2, not_in_jaxpr2):\n for square in [lambda x: x * x, api.jit(lambda x: x * x)]:\n f = api.remat(lambda x: jnp.sin(square(jnp.sin(x))),\n policy=policy)\n y, f_lin = api.linearize(f, 1.)\n ydot = f_lin(2.)\n jaxpr_text = str(f_lin.func.args[0])\n for substr in in_jaxpr2:\n self.assertIn(substr, jaxpr_text)\n for substr in not_in_jaxpr2:\n self.assertNotIn(substr, jaxpr_text)\n y_expected, ydot_expected = api.jvp(lambda x: jnp.sin(square(jnp.sin(x))),\n [1.], [2.])\n self.assertAllClose(y, y_expected)\n self.assertAllClose(ydot, ydot_expected)\n jtu.check_grads(f, (3.,), order=2, modes=['fwd', 'rev'])\n\n def test_remat_custom_policy_save_cos(self):\n save_cos = lambda prim, *_, **__: str(prim) == 'cos'\n f = api.remat(lambda x: jnp.sin(jnp.sin(x)), # different function\n policy=save_cos)\n _, f_lin = api.linearize(f, 1.)\n jaxpr_text = str(f_lin.func.args[0])\n self.assertNotIn(' sin ', jaxpr_text)\n self.assertNotIn(' cos ', jaxpr_text)\n jtu.check_grads(f, (3.,), order=2, modes=['fwd', 'rev'])\n\n def test_remat_checkpoint_dots(self):\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def f(x):\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = jnp.sin(x)\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = jnp.sin(x)\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = jnp.sin(x)\n return x\n\n _, f_lin = api.linearize(f, jnp.ones((2, 2)))\n jaxpr_text = str(f_lin.func.args[0])\n self.assertEqual(jaxpr_text.count(' sin '), 2)\n self.assertEqual(jaxpr_text.count(' dot_'), 6)\n jtu.check_grads(f, (jnp.ones((2, 2)),), order=2, modes=['fwd', 'rev'])\n\n def test_remat_checkpoint_dots_jit(self):\n @api.jit\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def f(x):\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = jnp.sin(x * 1e-3)\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = jnp.sin(x * 1e-3)\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = jnp.sin(x * 1e-3)\n return x\n\n _, f_lin = api.linearize(f, jnp.ones((2, 2)))\n jaxpr_text = str(f_lin.func.args[0])\n self.assertEqual(jaxpr_text.count(' sin '), 2)\n self.assertEqual(jaxpr_text.count(' dot_'), 6)\n jtu.check_grads(f, (jnp.ones((2, 2)),), order=2, modes=['fwd', 'rev'])\n\n def test_remat_checkpoint_dots_inside_scan(self):\n x = jnp.ones((5,))\n\n def f(W):\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def f(x):\n x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n x = jnp.sin(jnp.dot(x, W, precision=lax.Precision.HIGHEST))\n return x\n\n def body(x, _): return f(x), None\n return lax.scan(body, x, None, length=2)[0]\n\n _, f_vjp = api.vjp(f, jnp.ones((5, 5)))\n jaxpr_text = str(f_vjp.args[0].func.args[1])\n\n # Two sine calls in the backward pass because while we don't save sines\n # within the (rematted) body function, we can save the scan carry, which\n # effectively saves one sine. Three cosines for the Jacoian coefficients.\n self.assertEqual(jaxpr_text.count(' sin '), 2)\n self.assertEqual(jaxpr_text.count(' cos '), 3)\n # Six calls to dot_general in the backward pass because we save the primal\n # matmuls and only compure the backward pass ones (two for each primal one).\n self.assertEqual(jaxpr_text.count(' dot_'), 6)\n\n jtu.check_grads(api.jit(f), (jnp.ones((5, 5)),), order=2,\n modes=['fwd', 'rev'])\n\n def test_remat_custom_jvp_policy(self):\n @api.custom_jvp\n def sin(x):\n return jnp.sin(x)\n def sin_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return sin(x), jnp.cos(x) * g\n sin.defjvp(sin_jvp)\n\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def f(x):\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = sin(x * 1e-3)\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = sin(x * 1e-3)\n x = jnp.dot(x, x, precision=lax.Precision.HIGHEST)\n x = sin(x * 1e-3)\n return x\n\n jtu.check_grads(f, (3.,), order=2, modes=['fwd', 'rev'])\n\n def g(x):\n return lax.scan(lambda x, _: (f(x), None), x, None, length=2)[0]\n jtu.check_grads(g, (3.,), order=2, modes=['fwd', 'rev'])\n\n def test_remat_custom_vjp_policy(self):\n @api.custom_vjp\n def sin(x):\n return jnp.sin(x)\n def sin_fwd(x):\n return sin(x), x\n def sin_bwd(x, y_bar):\n return (jnp.cos(x) * y_bar,)\n sin.defvjp(sin_fwd, sin_bwd)\n\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def f(x):\n @partial(api.named_call, name=\"dot\")\n def dot2(y, z):\n return jnp.dot(x, jnp.dot(y, z, precision=lax.Precision.HIGHEST),\n precision=lax.Precision.HIGHEST)\n\n x = dot2(x, x)\n x = sin(x * 1e-3)\n x = dot2(x, x)\n x = sin(x * 1e-3)\n x = dot2(x, x)\n x = sin(x * 1e-3)\n return x\n\n jtu.check_grads(f, (3.,), order=2, modes=['rev'])\n\n def g(x):\n return lax.scan(lambda x, _: (f(x), None), x, None, length=2)[0]\n jtu.check_grads(g, (3.,), order=2, modes=['rev'])\n\n def test_remat_dropvar_policy(self):\n def f(x):\n return x, x\n\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def g(x):\n x = api.grad(lambda x: f(x)[0])(x)\n return x\n\n api.grad(g)(3.)\n\n def test_remat_custom_jvp_linear_policy(self):\n @api.custom_jvp\n def sum(x):\n return jnp.sum(x, axis=0)\n @sum.defjvp\n def sum_jvp(primals, tangents):\n (x,), (xdot,) = primals, tangents\n return sum(x), sum(xdot)\n\n @partial(api.remat, policy=jax.checkpoint_policies.checkpoint_dots)\n def f(x):\n return sum(x)\n jtu.check_grads(f, (jnp.ones(3),), order=2, modes=['fwd', 'rev'])\n\n def g(x):\n return lax.scan(lambda _, x: (None, f(x)), None, x)[1]\n jtu.check_grads(g, (jnp.ones((2, 3)),), order=2, modes=['fwd', 'rev'])\n\n\nclass JaxprTest(jtu.JaxTestCase):\n\n def test_scalar_literals(self):\n jaxpr = api.make_jaxpr(lambda x: x + 2)(42)\n self.assertLen(jaxpr.jaxpr.constvars, 0)\n\n def test_abstract_inputs(self):\n jaxpr = api.make_jaxpr(lambda x: x + 2.)(\n types.SimpleNamespace(shape=(), dtype=np.dtype(np.float32)))\n self.assertEqual(jaxpr.in_avals[0].shape, ())\n self.assertEqual(jaxpr.in_avals[0].dtype, np.float32)\n\n def test_const(self):\n def fun(x):\n return (x, 1., np.zeros(1, dtype=jnp.float32))\n\n expected = \"{ lambda a:f32[1]; b:f32[]. let in (b, 1.0, a) }\"\n jaxpr = api.make_jaxpr(fun)(jnp.float32(0.))\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n def test_cond(self):\n def f(x):\n return lax.cond(x >= 0.,\n x + 1.,\n lambda xt: xt + x,\n x + 2.,\n lambda xf: xf - x)\n expected = \"\"\"{ lambda ; a:f32[]. let\n b:bool[] = ge a 0.0\n c:f32[] = add a 1.0\n d:f32[] = add a 2.0\n e:i32[] = convert_element_type[new_dtype=int32 weak_type=False] b\n f:f32[] = cond[\n branches=(\n { lambda ; g_:f32[] h:f32[] i:f32[] j:f32[]. let\n k:f32[] = sub j h\n in (k,) }\n { lambda ; l:f32[] m_:f32[] n:f32[] o:f32[]. let\n p:f32[] = add n l\n in (p,) }\n )\n linear=(False, False, False, False)\n ] e a a c d\n in (f,) }\"\"\"\n jaxpr = api.make_jaxpr(f)(jnp.float32(3.))\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n def test_make_jaxpr_static_argnums(self):\n def f(x, y):\n return x + y\n\n jaxpr = api.make_jaxpr(f, static_argnums=(1,))(2, 3)\n self.assertIn('3', str(jaxpr))\n\n def test_make_jaxpr_return_shape(self):\n _, shape_tree = api.make_jaxpr(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n return_shape=True)(np.int32(1))\n expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n self.assertEqual(shape_tree, expected)\n\n def test_make_jaxpr_axis_env(self):\n def f(x):\n return x - lax.psum(x, 'i')\n jaxpr = api.make_jaxpr(f, axis_env=[('i', 4)])(2)\n self.assertIn('psum', str(jaxpr))\n\n def test_make_jaxpr_named(self):\n def f(x):\n return x - lax.psum(x, 'i')\n\n x = api.ShapeDtypeStruct(\n shape=(2, 3), dtype=jnp.dtype(jnp.float32), named_shape={'i': 10})\n jaxpr = api.make_jaxpr(f, axis_env=[('i', 10)])(x)\n named_shapes = [v.aval.named_shape for v in jaxpr.jaxpr.eqns[1].invars]\n self.assertEqual(named_shapes, [{'i': 10}, {}])\n\n @parameterized.parameters(True, False)\n def test_vjp_reduce_axes_jaxpr(self, gy_batched):\n def f(w, x):\n return jnp.sin(jnp.dot(x, w))\n\n w = api.ShapeDtypeStruct(\n shape=(3, 4), dtype=jnp.float32, named_shape={})\n x = api.ShapeDtypeStruct(\n shape=(3,), dtype=jnp.float32, named_shape={'batch': 2})\n gy = api.ShapeDtypeStruct(\n shape=(4,), dtype=jnp.float32,\n named_shape={'batch': 2} if gy_batched else {})\n\n # per-example\n jaxpr, shapes = api.make_jaxpr(\n lambda w, x, gy: api.vjp(f, w, x)[1](gy), axis_env=[('batch', 2)],\n return_shape=True)(w, x, gy)\n expected = (api.ShapeDtypeStruct(\n shape=(3, 4), dtype=jnp.float32, named_shape={'batch': 2}), x)\n self.assertEqual(shapes, expected)\n self.assertNotIn('psum', str(jaxpr))\n\n # reduced\n jaxpr, shapes = api.make_jaxpr(\n lambda w, x, gy: api.vjp(f, w, x, reduce_axes=('batch',))[1](gy),\n axis_env=[('batch', 2)],\n return_shape=True)(w, x, gy)\n expected = (w, x)\n self.assertEqual(shapes, expected)\n self.assertIn('psum', str(jaxpr))\n\n\nclass CustomJVPTest(jtu.JaxTestCase):\n\n def test_basic(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = 3.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(api.jvp(f, (x,), (1.,)),\n (jnp.sin(x), 2 * jnp.cos(x)))\n self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))\n\n def test_invariance(self):\n @api.custom_jvp\n def f(x):\n return jnp.cos(2 * x) / 2.\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return (f(x), 3 * g)\n f.defjvp(f_jvp)\n def f2(x):\n y, _ = api.jvp(f, (x,), (x,))\n return y\n def f3(x):\n y, _ = api.jvp(f2, (x,), (x,))\n return y\n x = 1.\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n api.jvp(f2, (x,), (x,)),\n check_dtypes=False)\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n api.jvp(f3, (x,), (x,)),\n check_dtypes=False)\n\n def test_python_control_flow(self):\n @api.custom_jvp\n def f(x):\n if x > 0:\n return jnp.sin(x)\n else:\n return jnp.cos(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n if x > 0:\n return f(x), 2 * g\n else:\n return f(x), 3 * g\n f.defjvp(f_jvp)\n x = 2.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(f(-x), jnp.cos(-x))\n self.assertAllClose(api.jvp(f, (x,), (1.,)),\n (jnp.sin(x), 2.),\n check_dtypes=False)\n self.assertAllClose(api.jvp(f, (-x,), (1.,)),\n (jnp.cos(-x), 3.),\n check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), 2., check_dtypes=False)\n self.assertAllClose(api.grad(f)(-x), 3., check_dtypes=False)\n\n def test_vmap(self):\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n assert jnp.ndim(x) == jnp.ndim(g) == 0\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = jnp.arange(3.)\n xx = jnp.arange(6.).reshape(2, 3)\n\n # vmap of f\n self.assertAllClose(api.vmap(f)(x), jnp.sin(x))\n self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))\n\n # vmap of jvp of f\n self.assertAllClose(api.vmap(lambda x: api.jvp(f, (x,), (x,)))(x),\n (jnp.sin(x), 2 * jnp.cos(x) * x))\n self.assertAllClose(api.vmap(api.vmap(lambda x: api.jvp(f, (x,), (x,))))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n # jvp of vmap of f\n self.assertAllClose(api.jvp(api.vmap(f), (x,), (x,)),\n (jnp.sin(x), 2 * jnp.cos(x) * x))\n self.assertAllClose(api.jvp(api.vmap(api.vmap(f)), (xx,), (xx,)),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n # vmap of jvp of vmap of f\n self.assertAllClose(api.vmap(lambda x: api.jvp(api.vmap(f), (x,), (x,)))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n def test_jit(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = 3.\n\n # jit\n self.assertAllClose(api.jit(f)(x), jnp.sin(x))\n self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))\n\n # jit of jvp\n self.assertAllClose(api.jit(lambda x: api.jvp(f, (x,), (x,)))(x),\n (jnp.sin(x), 2 * jnp.cos(x) * x),\n check_dtypes=False)\n\n # jvp of jit\n self.assertAllClose(api.jvp(api.jit(f), (x,), (x,)),\n (jnp.sin(x), 2 * jnp.cos(x) * x),\n check_dtypes=False)\n\n def test_pytrees(self):\n @api.custom_jvp\n def f(x):\n return {'b': jnp.sin(x['a'])}\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), {'b': 2 * jnp.cos(x['a']) * g['a']}\n f.defjvp(f_jvp)\n x = {'a': 3.}\n self.assertAllClose(f(x)['b'], jnp.sin(x['a']))\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n ({'b': jnp.sin(x['a'])},\n {'b': 2 * jnp.cos(x['a']) * x['a']}),\n check_dtypes=False)\n\n def test_kwargs(self):\n # from https://github.com/google/jax/issues/1938\n @api.custom_jvp\n def my_fun(x, y, c=1.):\n return c * (x + y)\n def my_jvp(primals, tangents):\n x, y, c = primals\n t_x, t_y, t_c = tangents\n return my_fun(x, y, c), t_c\n my_fun.defjvp(my_jvp)\n f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()\n f(10., 5.) # doesn't crash\n api.jvp(f, (10., 5.), (1., 1.)) # doesn't crash\n\n def test_initial_style(self):\n @api.custom_jvp\n def f(x):\n return 3 * x\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(foo))(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(foo))(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(foo))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.jit(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(api.grad(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(api.grad(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap(self):\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.vmap(api.jit(foo))(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.vmap(foo))(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap_with_collective(self):\n\n @api.custom_jvp\n def f(x):\n return lax.psum(x, 'foo')\n\n @f.defjvp\n def f_jvp(xs, ts):\n x, = xs\n t, = ts\n return lax.psum(x, 'foo'), t\n\n def g(x):\n jaxpr = api.make_jaxpr(f)(x)\n return core.eval_jaxpr(jaxpr.jaxpr, [], x)[0]\n\n v = api.vmap(lambda _, x: g(x), axis_name='foo', in_axes=(0, None),\n out_axes=None)(jnp.arange(4.), 2.)\n self.assertAllClose(v, 8.)\n\n def test_closed_over_tracers_error_message(self):\n def f(x):\n @api.custom_jvp\n def g(y):\n return x + y\n def g_jvp(primals, tangents):\n return g(x), 2 * primals[0]\n g.defjvp(g_jvp)\n return g(1.)\n\n self.assertRaises(ad.CustomJVPException, lambda: api.jvp(f, (3.,), (1.,)))\n self.assertRaises(ad.CustomJVPException, lambda: api.grad(f)(3.))\n\n def test_nondiff_arg(self):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def app(f, x):\n return f(x)\n def app_jvp(f, primals, tangents):\n (x,), (t,) = primals, tangents\n return app(f, x), 3 * t\n app.defjvp(app_jvp)\n\n ans = app(lambda x: 2 * x, 1)\n expected = 2\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jvp(lambda x: app(lambda y: 2 * y, x), (1.,), (1.,))\n expected = (2., 3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_jit_tracer(self):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_jvp(x, primals, tangents):\n (y,), (t_y,) = primals, tangents\n return f(x, y), 5 * t_y\n f.defjvp(f_jvp)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n ans = api.jvp(lambda y: g(2., y), (3.,), (1.,))\n expected = (6., 5.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_hiding_jvp_tracer(self):\n def f(x):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def g(h, x):\n return h(x)\n @g.defjvp\n def g_jvp(h, primals, tangents):\n x, = primals\n t, = tangents\n return g(h, x), 2. * t\n h = lambda y: x + y # capture x\n return g(h, x)\n\n with self.assertRaisesRegex(ad.CustomJVPException, \"Detected differentiation\"):\n api.jvp(f, (2.,), (1.,))\n\n def test_vmap_axes(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_pmap(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_missing_jvp_rule_error_message(self):\n @api.custom_jvp\n def foo(x):\n return x ** 2\n\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: foo(2))\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: api.jvp(foo, (2.,), (1.,)))\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: api.grad(foo)(2.))\n\n def test_jvp_rule_inconsistent_pytree_structures_error_message(self):\n @api.custom_jvp\n def f(x):\n return (x**2,)\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), [2 * x * t, x]\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce primal and tangent outputs \"\n \"with equal container (pytree) structures, but got \"\n \"{} and {} respectively.\".format(\n tree_util.tree_structure((1,)),\n tree_util.tree_structure([1, 2]))\n ),\n lambda: api.jvp(f, (2.,), (1.,)))\n\n def test_primal_tangent_aval_disagreement_error_message(self):\n @api.custom_jvp\n def f(x):\n return x ** 2\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), jnp.reshape(t, (1,))\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce primal and tangent outputs \"\n \"with equal shapes and dtypes, but got float32[] and float32[1] \"\n \"respectively.\"),\n lambda: api.jvp(f, (jnp.float32(2.),), (jnp.float32(1.),)))\n\n def test_jvp_rule_doesnt_return_pair_error_message(self):\n # https://github.com/google/jax/issues/2516\n\n @api.custom_jvp\n def f(x):\n return x ** 2\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return t\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce a pair (list or tuple of length two) \"\n \"representing primal and tangent outputs, got 1.0\"),\n lambda: api.jvp(f, (2.,), (1.,)))\n\n def test_multiple_rule_invocations(self):\n @jax.custom_jvp\n def expit(x):\n return 1 / (1 + lax.exp(-x))\n\n @expit.defjvp\n def _expit_jvp(primals, tangents):\n (x,), (t,) = primals, tangents\n ans = expit(x)\n t_out = t * ans * (1 - ans)\n return ans, t_out\n\n def scanned_fun(c, _):\n return [expit(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n\n def foo(x):\n c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n return c[-1]\n\n # just make sure these don't crash\n foo(3.)\n grad(foo)(3.)\n grad(lambda x: jax.vmap(foo)(x).sum())(jnp.arange(3.))\n\n def test_hard_stuff(self):\n arr = jnp.ones((5, 2, 2))\n api.jit(jax.vmap(jnp.linalg.det))(arr) # doesn't crash\n\n def test_hard_stuff2(self):\n @jax.custom_jvp\n def f(x):\n return lax.tie_in(x, np.zeros(x.shape, x.dtype))\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), t\n\n # don't crash\n jax.jit(jax.vmap(f))(jnp.arange(3.))\n jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))\n jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))\n jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))\n jax.jvp(jax.vmap(f), (jnp.arange(3.),), (jnp.ones(3),))\n\n def test_hard_stuff3(self):\n @jax.custom_jvp\n def relu(x):\n return jnp.maximum(x, 0)\n\n @relu.defjvp\n def _relu_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return relu(x), lax.select(x > 0, t, lax.full_like(t, 0))\n\n def scanned_fun(c, _):\n return [relu(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n\n def f(x):\n c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n return c[-1]\n\n # don't crash\n jax.jit(jax.vmap(f))(jnp.arange(3.))\n jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))\n jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))\n jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))\n jax.jvp(jax.jit(jax.vmap(f)), (jnp.arange(3.),), (jnp.ones(3),))\n\n def test_eval_shape(self):\n @jax.custom_jvp\n def expit(x):\n return 1 / (1 + lax.exp(-x))\n\n @expit.defjvp\n def _expit_jvp(primals, tangents):\n (x,), (t,) = primals, tangents\n ans = expit(x)\n t_out = t * ans * (1 - ans)\n return ans, t_out\n\n # don't crash\n api.eval_shape(expit, jnp.ones((2, 3)))\n api.eval_shape(api.grad(lambda x: expit(x).sum()), jnp.ones((2, 3)))\n\n def test_jaxpr_zeros(self):\n # from https://github.com/google/jax/issues/2657\n @api.custom_jvp\n def f(A, b):\n return A @ b\n\n def f_jvp(primals, tangents):\n A, b = primals\n dA, db = tangents\n z = f(A, b)\n dz = A @ db + dA @ b\n return z, dz\n\n f.defjvp(f_jvp)\n\n def experiment(theta):\n def step(q, _):\n z = f(jnp.eye(3), jnp.ones(3) * theta)\n q += z[0]\n return q, q\n\n q = 0.\n q, _ = lax.scan(step, q, None, 4)\n return q\n\n grad(experiment)(1.) # doesn't crash\n\n def test_linear_in_scan(self):\n @api.custom_jvp\n def f(x):\n return -x\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n x_dot, = tangents\n return f(x), f(x_dot)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = -1.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_jvps_first_rule_is_none(self):\n # https://github.com/google/jax/issues/3389\n @api.custom_jvp\n def f(x, y):\n return x ** 2 * y\n\n f.defjvps(None, lambda x_dot, primal_out, x, y: 2 * x * y * x_dot)\n ans = grad(f, 1)(2., 3.) # doesn't crash\n expected = 12.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_concurrent_initial_style(self):\n # https://github.com/google/jax/issues/3843\n def unroll(param, sequence):\n def scan_f(prev_state, inputs):\n return prev_state, jax.nn.sigmoid(param * inputs)\n return jnp.sum(jax.lax.scan(scan_f, None, sequence)[1])\n\n def run():\n return jax.grad(unroll)(jnp.array(1.0), jnp.array([1.0]))\n\n expected = run()\n\n # we just don't want this to crash\n n_workers = 2\n with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as e:\n futures = []\n for _ in range(n_workers):\n futures.append(e.submit(run))\n results = [f.result() for f in futures]\n for ans in results:\n self.assertAllClose(ans, expected)\n\n def test_nondiff_argnums_vmap_tracer(self):\n # https://github.com/google/jax/issues/3964\n @partial(jax.custom_jvp, nondiff_argnums=(0, 2))\n def sample(shape, param, seed):\n return jax.random.uniform(key=seed, shape=shape, minval=param)\n\n @sample.defjvp\n def sample_jvp(shape, seed, primals, tangents):\n param, = primals\n dparam, = tangents\n dparam = jnp.broadcast_to(dparam, shape)\n samples = sample(shape, param, seed)\n return samples, samples * dparam # dummy jvp for proof of concept\n\n # check these don't crash\n jax.vmap(lambda seed: sample((2,3), 1., seed))(\n jax.random.split(jax.random.PRNGKey(1), 10))\n jax.jvp(lambda x: sample((2, 3), x, jax.random.PRNGKey(1)),\n (1.,), (1.,))\n\n def test_fun_with_nested_calls_2(self):\n def call(f, *args):\n f = api.custom_jvp(f)\n f.defjvp(lambda primals, tangents: (f(*primals), sum(tangents)))\n return f(*args)\n\n def fun_with_nested_calls_2(x):\n def bar(y):\n def baz(w):\n q = call(lambda x: y, x)\n q = q + call(lambda: y)\n q = q + call(lambda y: w + y, y)\n q = call(lambda w: call(jnp.sin, x) * y, 1.0) + q\n return q\n return api.jit(baz)(x)\n return call(bar, x)\n\n # test these don't crash\n self.assertAllClose(api.jit(fun_with_nested_calls_2)(3.),\n fun_with_nested_calls_2(3.))\n api.vmap(fun_with_nested_calls_2)(jnp.arange(3.))\n\n def test_closure_with_vmap(self):\n # https://github.com/google/jax/issues/3822\n alpha = np.float32(2.)\n\n def sample(seed):\n @api.custom_jvp\n def f(alpha):\n return jax.random.gamma(seed, alpha, shape=[])\n\n @f.defjvp\n def f_jvp(primal, tangent):\n alpha = primal\n dalpha = tangent\n sample = f(alpha)\n partial_alpha = lax.random_gamma_grad(alpha, sample)\n return sample, partial_alpha * dalpha\n return f(alpha)\n\n api.vmap(sample)(jax.random.split(jax.random.PRNGKey(1), 3)) # don't crash\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_float0(self):\n @api.custom_jvp\n def f(x, y):\n return x, y\n def f_jvp(primals, _):\n # we need a defined (non-float0) tangent to trigger the rule\n return primals, (2., 1)\n f.defjvp(f_jvp)\n\n primals = (2., 3)\n tangents = (np.ones(()), np.zeros((), float0),)\n expected_tangents = (2., np.zeros((), float0))\n self.assertArraysEqual(api.jvp(f, primals, tangents),\n (primals, expected_tangents))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_float0_initial_style(self):\n @api.custom_jvp\n def f(x, y):\n return x, y\n def f_jvp(primals, _):\n x, y = primals\n return (x, y), (2., 1)\n f.defjvp(f_jvp)\n\n def foo(x, y):\n out, _ = lax.scan(lambda c, _: (f(*c), None), (x, y), None, length=1)\n return out\n\n primals = (2., 3)\n tangents = (np.ones(()), np.zeros((), float0),)\n expected_tangents = (2., np.zeros((), float0))\n self.assertArraysEqual(api.jvp(foo, primals, tangents),\n (primals, expected_tangents))\n\n def test_remat(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n @api.remat\n def g(x):\n return f(f(x))\n\n ans = g(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g)(2.)\n expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n def g(x):\n return f(f(x))\n\n ans = api.grad(api.grad(api.remat(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.remat(api.grad(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n expected = api.grad(api.grad(api.grad(g)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap_2(self):\n # This is like test_initial_style_vmap except the primal function closes\n # over an array constant.\n y = jnp.array([1., 2., 3.])\n\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x * jnp.sum(y)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_jvp_vmap_broadcasting_interaction(self):\n # https://github.com/google/jax/issues/6452\n def f2(y, z):\n v1 = z\n v2 = jnp.sum(y) + z\n return jnp.logaddexp(v1, v2)\n\n def f1(y, z):\n v = api.vmap(lambda _y: f2(_y, z))(y)\n return jnp.sum(v)\n\n y = jnp.ones((3, 2))\n f = lambda z: f1(y, z)\n z = 0.1\n val, g = api.value_and_grad(f)(z)\n self.assertEqual(val.shape, ())\n self.assertEqual(g.shape, ())\n\n def test_custom_jvp_vmap_broadcasting_interaction_2(self):\n # https://github.com/google/jax/issues/5849\n @api.custom_jvp\n def transform(box, R):\n if jnp.isscalar(box) or box.size == 1:\n return R * box\n elif box.ndim == 2:\n return jnp.einsum('ij,j->i', box, R)\n raise ValueError()\n\n @transform.defjvp\n def transform_jvp(primals, tangents):\n box, R = primals\n dbox, dR = tangents\n return (transform(box, R), dR + transform(dbox, R))\n\n def periodic_general(box):\n def displacement_fn(Ra, Rb, **kwargs):\n _box = kwargs.get('box', box)\n return transform(_box, Ra - Rb)\n\n return displacement_fn\n\n N = 250\n\n scalar_box = 1.0\n displacement = periodic_general(scalar_box)\n\n key = jax.random.PRNGKey(0)\n R = jax.random.uniform(key, (N, 2))\n\n def energy_fn(box):\n d = partial(displacement, box=box)\n d = api.vmap(api.vmap(d, (None, 0)), (0, None))\n return jnp.sum(d(R, R) ** 2)\n\n self.assertEqual(grad(energy_fn)(scalar_box).shape, ())\n\n def test_custom_jvp_implicit_broadcasting(self):\n # https://github.com/google/jax/issues/6357\n if config.x64_enabled:\n raise unittest.SkipTest(\"test only applies when x64 is disabled\")\n\n @jax.custom_jvp\n def projection_unit_simplex(x: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Projection onto the unit simplex.\"\"\"\n s = 1.0\n n_features = x.shape[0]\n u = jnp.sort(x)[::-1]\n cssv = jnp.cumsum(u) - s\n ind = jnp.arange(n_features) + 1\n cond = u - cssv / ind > 0\n idx = jnp.count_nonzero(cond)\n threshold = cssv[idx - 1] / idx.astype(x.dtype)\n return jax.nn.relu(x - threshold)\n\n\n @projection_unit_simplex.defjvp\n def projection_unit_simplex_jvp(primals, tangents):\n x, = primals\n x_dot, = tangents\n primal_out = projection_unit_simplex(x)\n supp = primal_out > 0\n card = jnp.count_nonzero(supp)\n tangent_out = supp * x_dot - (jnp.dot(supp, x_dot) / card) * supp\n return primal_out, tangent_out\n\n rng = np.random.RandomState(0)\n x = rng.rand(5).astype(np.float32)\n\n J_rev = jax.jacrev(projection_unit_simplex)(x)\n J_fwd = jax.jacfwd(projection_unit_simplex)(x)\n\n p = projection_unit_simplex(x)\n support = (p > 0).astype(jnp.int32)\n cardinality = jnp.count_nonzero(support)\n J_true = jnp.diag(support) - jnp.outer(support, support) / cardinality\n self.assertAllClose(J_true, J_fwd)\n self.assertAllClose(J_true, J_rev)\n\n proj = jax.vmap(projection_unit_simplex)\n\n def fun(X):\n return jnp.sum(proj(X) ** 2)\n\n rng = np.random.RandomState(0)\n X = rng.rand(4, 5).astype(np.float32)\n U = rng.rand(4, 5)\n U /= np.sqrt(np.sum(U ** 2))\n U = U.astype(np.float32)\n\n eps = 1e-3\n dir_deriv_num = (fun(X + eps * U) - fun(X - eps * U)) / (2 * eps)\n dir_deriv = jnp.vdot(jax.grad(fun)(X), U)\n self.assertAllClose(dir_deriv, dir_deriv_num, atol=1e-3)\n\n def test_vmap_inside_defjvp(self):\n # https://github.com/google/jax/issues/3201\n seed = 47\n key = jax.random.PRNGKey(seed)\n mat = jax.random.normal(key, (2, 3))\n\n @jax.custom_jvp\n def f(mat, aux):\n num_rows, num_cols = mat.shape\n return jnp.ones((num_rows, 1)) / num_cols\n\n @f.defjvp\n def f_jvp(primals, tangents):\n mat, aux = primals\n vec, _ = tangents\n output = f(*primals)\n num_rows, num_cols = mat.shape\n size = num_rows * num_cols\n # -----\n bd_mat = mat.reshape(1, 1, num_rows, num_cols)\n bd_mat = jnp.tile(bd_mat, reps=(num_rows, num_cols))\n bd_mat = bd_mat.reshape(size, num_rows, num_cols)\n # -----\n rowsum = jnp.sum(mat, axis=1, keepdims=True)\n colsum = jnp.sum(mat, axis=0, keepdims=True)\n bd_rowsum = jnp.tile(rowsum, reps=(1, num_rows))\n bd_colsum = jnp.tile(colsum, reps=(num_cols, 1))\n # -----\n bd_vec = vec.reshape(size, 1)\n # -----\n def operate(mx, val):\n buf = 0\n for i in range(2):\n buf = buf + jnp.matmul(mx, bd_colsum) / jnp.power(aux, i)\n buf = jnp.matmul(bd_rowsum, buf)\n return buf * val\n # -----\n # Vertorizing will raise shape error\n bd_buf = jax.vmap(operate, in_axes=(0, 0), out_axes=0)(bd_mat, bd_vec)\n # -----\n bd_buf = bd_buf / aux\n jvp = jnp.sum(bd_buf, axis=0)\n jvp = jnp.mean(jvp, axis=1, keepdims=True)\n # -----\n # JVP ends successfully, but still raise an error\n return (output, jvp)\n\n jax.grad(lambda mat, aux: jnp.sum(f(mat, aux)))(mat, 0.5) # doesn't crash\n\n def test_custom_jvp_unbroadcasting(self):\n # https://github.com/google/jax/issues/3056\n a = jnp.array([1., 1.])\n\n @jax.custom_jvp\n def f(x):\n return a * x\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n dx, = tangents\n return a * x, a * dx\n\n shape = grad(lambda x: jnp.sum(f(x)))(jnp.array(1.)).shape\n self.assertEqual(shape, ())\n\n\nclass CustomVJPTest(jtu.JaxTestCase):\n\n def test_basic(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = 3.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))\n self.assertAllClose(api.value_and_grad(f)(x),\n (jnp.sin(x), 2 * jnp.cos(x)))\n\n def test_invariance(self):\n @api.custom_vjp\n def f(x):\n return jnp.cos(2 * x) / 2.\n def f_fwd(x):\n return (f(x), x)\n def f_rev(x, g):\n return (g * 3,)\n f.defvjp(f_fwd, f_rev)\n def f2(x):\n y, _ = api.value_and_grad(f)(x)\n return y\n def f3(x):\n y, _ = api.value_and_grad(f2)(x)\n return y\n x = 1.\n self.assertAllClose(f(x), f2(x), check_dtypes=False)\n self.assertAllClose(f(x), f3(x), check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), api.grad(f2)(x),\n check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), api.grad(f3)(x),\n check_dtypes=False)\n\n def test_python_control_flow(self):\n @api.custom_vjp\n def f(x):\n if x > 0:\n return jnp.sin(x)\n else:\n return jnp.cos(x)\n def f_fwd(x):\n if x > 0:\n return f(x), x\n else:\n return f(x), x\n def f_rev(x, g):\n if x > 0:\n return (2 * g,)\n else:\n return (3 * g,)\n f.defvjp(f_fwd, f_rev)\n x = 2.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(f(-x), jnp.cos(-x))\n self.assertAllClose(api.value_and_grad(f)(x), (jnp.sin(x), 2.),\n check_dtypes=False)\n self.assertAllClose(api.value_and_grad(f)(-x), (jnp.cos(-x), 3.),\n check_dtypes=False)\n\n def test_vmap(self):\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return jnp.sin(x)\n def f_fwd(x):\n assert jnp.ndim(x) == 0\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = jnp.arange(3.)\n xx = jnp.arange(6.).reshape(2, 3)\n\n # vmap of f\n self.assertAllClose(api.vmap(f)(x), jnp.sin(x))\n self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))\n\n # vmap of grad of f\n self.assertAllClose(api.vmap(api.grad(f))(x), 2 * jnp.cos(x))\n self.assertAllClose(api.vmap(api.value_and_grad(f))(x),\n (jnp.sin(x), 2 * jnp.cos(x)))\n self.assertAllClose(api.vmap(api.vmap(api.grad(f)))(xx), 2 * jnp.cos(xx))\n self.assertAllClose(api.vmap(api.vmap(api.value_and_grad(f)))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx)))\n\n # grad of vmap of f\n self.assertAllClose(api.grad(lambda x: api.vmap(f)(x).sum())(x),\n 2 * jnp.cos(x))\n self.assertAllClose(api.grad(lambda x: api.vmap(api.vmap(f))(x).sum())(xx),\n 2 * jnp.cos(xx))\n\n # vmap of grad of vmap of f\n self.assertAllClose(api.vmap(api.grad(lambda x: api.vmap(f)(x).sum()))(xx),\n 2 * jnp.cos(xx))\n\n def test_jit(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = 3.\n\n # jit\n self.assertAllClose(api.jit(f)(x), jnp.sin(x))\n self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))\n\n # jit of grad\n self.assertAllClose(api.jit(api.grad(f))(x), 2 * jnp.cos(x),\n check_dtypes=False)\n\n # grad of jit\n self.assertAllClose(api.grad(api.jit(f))(x), 2 * jnp.cos(x),\n check_dtypes=False)\n\n def test_pytrees(self):\n @api.custom_vjp\n def f(x):\n return {'b': jnp.sin(x['a'])}\n def f_fwd(x):\n return f(x), {'r': jnp.cos(x['a'])}\n def f_bwd(res, g):\n cos_x = res['r']\n return ({'a': 2 * cos_x * g['b']},)\n f.defvjp(f_fwd, f_bwd)\n x = {'a': 3.}\n self.assertAllClose(f(x)['b'], jnp.sin(x['a']))\n self.assertAllClose(api.grad(lambda x: f(x)['b'])(x),\n {'a': 2 * jnp.cos(x['a'])})\n\n def test_jvp_error(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(f, (3.,), (1.,)))\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(api.vmap(f), (jnp.arange(3.),), (jnp.ones(3),)))\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(jit(f), (3.,), (1.,)))\n\n def test_kwargs(self):\n # from https://github.com/google/jax/issues/1938\n @api.custom_vjp\n def my_fun(x, y, c=1.):\n return c * (x + y)\n my_fun.defvjp(lambda x, y, c=1.: (my_fun(c, y, c), None),\n lambda _, g: (g, g, g))\n f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()\n f(10., 5.) # doesn't crash\n api.grad(f)(10., 5.) # doesn't crash\n\n def test_initial_style(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = 2. * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(foo))(3.)\n expected = -2. * jnp.sin(3.)\n self.assertAllClose(ans, expected)\n\n def test_initial_style_vmap(self):\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.arange(3.))\n expected = 3. * jnp.arange(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))\n expected = 2. * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg(self):\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def app(f, x):\n return f(x)\n def app_fwd(f, x):\n return app(f, x), jnp.cos(x)\n def app_rev(f, cos_x, g):\n return (cos_x * g,)\n app.defvjp(app_fwd, app_rev)\n\n ans = app(lambda x: 2 * x, 1)\n expected = 2\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.value_and_grad(lambda x: app(lambda y: 2 * y, x))(1.)\n expected = (2., jnp.cos(1.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer(self):\n # This test is similar to test_nondiff_arg_tracer except it uses lexical\n # closure rather than the nondiff_argnums mechanism. We decided to disallow\n # tracers in nondiff_argnums to greatly simplify bookkeeping while still\n # supporting the cases for which it is necessary.\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), jnp.cos(y)\n def f_rev(cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n return f\n\n @jit\n def g(x, y):\n return outer(x)(y)\n\n ans = g(2, 3.)\n expected = 6.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g, 1)(2., 3.)\n expected = jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer2(self):\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), jnp.cos(y)\n def f_rev(cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n return f\n\n @api.vmap\n def g(x):\n return outer(x)(3.)\n\n ans = g(np.arange(3.))\n expected = np.arange(3.) * 3\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer3(self):\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), (x, jnp.cos(y))\n def f_rev(res, g):\n x, cos_y = res\n return (cos_y * g * x,)\n f.defvjp(f_fwd, f_rev)\n return api.grad(f)\n\n @api.vmap\n def g(x):\n return outer(x)(3.)\n\n ans = g(np.arange(3.))\n expected = np.cos(3.) * np.arange(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_tracer_error(self):\n # This is similar to the old (now skipped) test_nondiff_arg_tracer, except\n # we're testing for the error message that that usage pattern now raises.\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(x, cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n with self.assertRaisesRegex(UnexpectedTracerError, \"custom_vjp\"):\n _ = g(2, 3.)\n with self.assertRaisesRegex(UnexpectedTracerError, \"custom_vjp\"):\n _ = api.grad(g, 1)(2., 3.)\n\n def test_vmap_axes(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_pmap(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_missing_vjp_rule_error(self):\n @api.custom_vjp\n def foo(x):\n return x ** 2\n\n self.assertRaisesRegex(\n AttributeError,\n r\"No VJP defined for custom_vjp function foo using defvjp.\",\n lambda: foo(2))\n self.assertRaisesRegex(\n AttributeError,\n r\"No VJP defined for custom_vjp function foo using defvjp.\",\n lambda: api.grad(foo)(2.))\n\n def test_vjp_rule_inconsistent_pytree_structures_error(self):\n @api.custom_vjp\n def f(x):\n return x\n\n def foo_fwd(x):\n return x, None\n\n def foo_bwd(_, g):\n return (g, g)\n\n f.defvjp(foo_fwd, foo_bwd)\n\n f(2) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom VJP rule must produce an output with the same container \"\n \"(pytree) structure as the args tuple of the primal function, \"\n \"and in particular must produce a tuple of length equal to the \"\n \"number of arguments to the primal function, but got VJP output \"\n \"structure {} for primal input structure {}.\".format(\n tree_util.tree_structure((1, 1)),\n tree_util.tree_structure((1,)))\n ),\n lambda: api.grad(f)(2.))\n\n def test_vjp_bwd_returns_non_tuple_error(self):\n @api.custom_vjp\n def f(x):\n return x\n\n def foo_fwd(x):\n return x, None\n\n def foo_bwd(_, g):\n return 2. * g # Should be a tuple\n\n f.defvjp(foo_fwd, foo_bwd)\n with self.assertRaisesRegex(TypeError, \"Custom VJP rule .* must produce a tuple\"):\n api.grad(f)(3.)\n\n def test_issue2511(self):\n arr = jnp.ones((5, 2, 2))\n foo = lambda x: api.vmap(jnp.linalg.det, (0,))(x)\n api.jit(foo)(arr) # doesn't crash\n\n def test_lowering_out_of_traces(self):\n # https://github.com/google/jax/issues/2578\n\n class F(collections.namedtuple(\"F\", [\"a\"])):\n def __call__(self, x):\n return jax.nn.relu(self.a) * x\n\n @jax.jit\n def g(f, x):\n return f(x)\n\n jax.grad(g, argnums=(1,))(F(2.0), 0.) # doesn't crash\n\n def test_clip_gradient(self):\n # https://github.com/google/jax/issues/2784\n @api.custom_vjp\n def _clip_gradient(lo, hi, x):\n return x # identity function when not differentiating\n\n def clip_gradient_fwd(lo, hi, x):\n return x, (lo, hi,)\n\n def clip_gradient_bwd(res, g):\n lo, hi = res\n return (None, None, jnp.clip(g, lo, hi),)\n\n _clip_gradient.defvjp(clip_gradient_fwd, clip_gradient_bwd)\n\n def clip_gradient(x):\n lo = -0.1\n hi = x + 0.1\n return _clip_gradient(lo, hi, x)\n\n g = jax.grad(clip_gradient)(0.1) # doesn't crash\n self.assertAllClose(g, jnp.array(0.2))\n\n def test_nestable_vjp(self):\n # Verify that https://github.com/google/jax/issues/3667 is resolved.\n def f(x):\n return x ** 2\n\n @api.custom_vjp\n def g(x):\n return f(x)\n\n def g_fwd(x):\n y, f_vjp = api.vjp(f, x)\n return y, f_vjp\n\n def g_bwd(f_vjp, y_bar):\n return f_vjp(y_bar)\n\n g.defvjp(g_fwd, g_bwd)\n\n # Check that VJP can be nested in simple situations. For this to pass,\n # vjp has to return a PyTree.\n _, g_vjp = api.vjp(g, 1.0)\n y, = g_vjp(1.0)\n self.assertAllClose(y, jnp.array(2.0))\n\n # Check that VJP can be nested in complex situations. For this to pass,\n # vjp can't treat the closed-over tracer x as a static argument.\n @jit\n def z(x):\n _, g_vjp = api.vjp(g, x)\n return g_vjp\n y, = z(1.0)(3.0)\n self.assertAllClose(y, jnp.array(6.0))\n\n def test_initial_style_vmap_2(self):\n # https://github.com/google/jax/issues/4173\n x = jnp.ones((10, 3))\n\n # Create the custom function\n @api.custom_vjp\n def custom_fun(x):\n return x.sum()\n\n def forward(x):\n return x.sum(), (jnp.ones_like(x),)\n\n def backward(res, g):\n return g * res[0],\n\n custom_fun.defvjp(forward, backward)\n\n def train_fun(x):\n\n def summed_fun(x):\n return api.vmap(custom_fun)(x).sum()\n\n return api.grad(summed_fun)(x)\n\n def scan_body(carry, inputs):\n x = carry\n return carry, train_fun(x)\n\n scan_range = jnp.arange(4)\n lax.scan(scan_body, x, scan_range) # don't crash\n\n def test_initial_style_vmap_3(self):\n # This is like test_initial_style_vmap except the primal function closes\n # over an array constant.\n y = jnp.array([1., 2., 3.])\n\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x * jnp.sum(y)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.arange(3.))\n expected = 3. * jnp.arange(3.) * 6\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))\n expected = 2. * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap_with_collective(self):\n\n @api.custom_vjp\n def f(x):\n return lax.psum(x, 'foo')\n\n def f_fwd(x):\n return lax.psum(x, 'foo'), None\n\n def f_bwd(res, dx):\n return dx\n f.defvjp(f_fwd, f_bwd)\n\n def g(x):\n jaxpr = api.make_jaxpr(f)(x)\n return core.eval_jaxpr(jaxpr.jaxpr, [], x)[0]\n\n out = api.vmap(lambda _, x: g(x), axis_name='foo', in_axes=(0, None),\n out_axes=None)(jnp.arange(4.), 2.)\n self.assertAllClose(out, 8.)\n\n def test_bwd_closes_over_tracer(self):\n def f(y):\n @jax.custom_vjp\n def f(x):\n return 2. * jnp.sin(x)\n\n def fwd(x):\n return f(x), ()\n\n def bwd(_, g):\n return (2. * jnp.cos(y) * g,) # capture!\n\n f.defvjp(fwd, bwd)\n\n return jax.grad(f)(1.)\n\n ans = jax.jit(f)(2.)\n self.assertAllClose(ans, 2. * jnp.cos(2.))\n\n ans = jax.vmap(f)(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.jit(jax.vmap(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.vmap(jax.jit(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.grad(f)(4.)\n self.assertAllClose(ans, -2. * jnp.sin(4.))\n\n def test_fwd_closes_over_tracer(self):\n def f(y):\n @jax.custom_vjp\n def f(x):\n return 2. * jnp.sin(x)\n\n def fwd(x):\n return f(x), y\n\n def bwd(y, g):\n return (2. * jnp.cos(y) * g,) # capture!\n\n f.defvjp(fwd, bwd)\n\n return jax.grad(f)(1.)\n\n ans = jax.jit(f)(2.)\n self.assertAllClose(ans, 2. * jnp.cos(2.))\n\n ans = jax.vmap(f)(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.jit(jax.vmap(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.vmap(jax.jit(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.grad(f)(4.)\n self.assertAllClose(ans, -2. * jnp.sin(4.))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_float0(self):\n @api.custom_vjp\n def f(x, _):\n return x\n def f_fwd(x, _):\n # we need a defined (non-float0) tangent to trigger the rule\n return x, (2., 1)\n def f_rev(*_):\n return (2., 1)\n f.defvjp(f_fwd, f_rev)\n\n x = 2.\n y = 3\n self.assertEqual(api.grad(f, allow_int=True, argnums=(0, 1))(x, y),\n (2., np.zeros(shape=(), dtype=float0)))\n\n @unittest.skipIf(numpy_version == (1, 21, 0),\n \"https://github.com/numpy/numpy/issues/19305\")\n def test_float0_initial_style(self):\n @api.custom_vjp\n def f(x):\n return x\n def f_fwd(x):\n return x, (2., x)\n def f_rev(*_):\n return ((2., 1),)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x, y):\n out, _ = lax.scan(lambda c, _: (f(c), None), (x, y), None, length=1)\n return out[0]\n\n x = 2.\n y = 3\n self.assertEqual(api.grad(foo, allow_int=True, argnums=(0, 1))(x, y),\n (2., np.zeros(shape=(), dtype=float0)))\n\n def test_remat(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n @api.remat\n def g(x):\n return f(f(x))\n\n ans = g(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g)(2.)\n expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def g(x):\n return f(f(x))\n\n ans = api.grad(api.grad(api.remat(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.remat(api.grad(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n expected = api.grad(api.grad(api.grad(g)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones(self):\n @api.custom_vjp\n def f(x, y):\n return x * jnp.sin(y)\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: f(x, x))(3.)\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones_vmap(self):\n @api.custom_vjp\n def f(x, y):\n return x * jnp.sin(y)\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: api.vmap(f)(x, x).sum())(jnp.arange(3.))\n expected = 2 * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones_pytree(self):\n @api.custom_vjp\n def f(xs, y):\n x1, x2 = xs\n return x1 * x2 * jnp.sin(y)\n def f_fwd(xs, y):\n return f(xs, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: f((x, x), x))(3.)\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_vjp_closure_4521(self):\n # https://github.com/google/jax/issues/4521\n @api.custom_vjp\n def g(x, y):\n return None\n def g_fwd(x, y):\n return None, y\n def g_bwd(residuals, z_bar):\n assert False\n\n g.defvjp(g_fwd, g_bwd)\n\n def f(xs, y):\n v_g = api.vmap(g, in_axes=(0, None), out_axes=None)\n v_g(xs, y)\n\n def scan_body(xs, _):\n y = jnp.zeros(1)\n _, vjp_f = api.vjp(f, xs, y)\n vjp_f(None)\n return xs, None\n\n lax.scan(scan_body, jnp.ones(5), None, 100) # doesn't crash\n\n def test_float0_bwd_none(self):\n @api.custom_vjp\n def f(i, x):\n return jnp.sin(x)\n def f_fwd(i, x):\n return f(i, x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (None, 2 * cos_x * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(f, 1)(jnp.array([1, 2]), 3.) # doesn't crash\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_gradient(self):\n @api.custom_gradient\n def f(x):\n return x ** 2, lambda g: (g * x,)\n\n self.assertAllClose(f(3.), 9., check_dtypes=False)\n self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)\n self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)\n\n def test_custom_gradient_2(self):\n @api.custom_gradient\n def f(x, y):\n return x * y, lambda g: (y, x)\n\n self.assertAllClose(f(3., 4.), 12., check_dtypes=False)\n self.assertAllClose(api.grad(f, argnums=(0, 1))(3., 4.), (4., 3.),\n check_dtypes=False)\n\n def test_custom_gradient_3(self):\n @api.custom_gradient\n def f(x):\n vjp = lambda g: (jnp.cos(x) * jnp.array([3., 4., 5.]),)\n return jnp.sum(jnp.sin(x)), vjp\n\n self.assertAllClose(f(jnp.arange(3)), jnp.sum(jnp.sin(jnp.arange(3.))),\n check_dtypes=False)\n self.assertAllClose(\n api.grad(f)(jnp.arange(3.)),\n api.grad(lambda x: jnp.sum(jnp.sin(x)))(jnp.arange(3.)) * jnp.array([3., 4., 5.]),\n check_dtypes=False)\n\n def test_custom_gradient_can_return_singleton_value_in_vjp(self):\n @api.custom_gradient\n def f(x):\n return x ** 2, lambda g: g * x\n\n self.assertAllClose(f(3.), 9., check_dtypes=False)\n self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)\n self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)\n\n def test_closure_convert(self):\n def cos_after(fn, x):\n converted_fn, aux_args = api.closure_convert(fn, x)\n self.assertLessEqual(len(aux_args), 1)\n return _cos_after(converted_fn, x, *aux_args)\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def _cos_after(fn, x, *args):\n return jnp.cos(fn(x, *args))\n\n def fwd(fn, x, *args):\n y = _cos_after(fn, x, *args)\n return y, (x, args)\n\n def rev(fn, res, g):\n x, args = res\n x_bar = 17. * x\n args_bars = [42. * a for a in args]\n return (x_bar, *args_bars)\n\n _cos_after.defvjp(fwd, rev)\n\n def dist(c, x):\n return jnp.sum((x - c) ** 2.)\n\n def solve(c, x):\n def closure(x):\n return dist(c, x)\n return cos_after(closure, x)\n\n c, x = 2. * jnp.ones(2), jnp.ones(2)\n expected = jnp.cos(dist(c, x))\n self.assertAllClose(solve(c, x), expected, check_dtypes=False)\n g_c, g_x = api.grad(solve, argnums=(0, 1))(c, x)\n self.assertAllClose(g_c, 42. * c, check_dtypes=False)\n self.assertAllClose(g_x, 17. * x, check_dtypes=False)\n\n def test_closure_convert_mixed_consts(self):\n # Like test_closure_convert, but close over values that\n # participate in AD as well as values that do not.\n # See https://github.com/google/jax/issues/6415\n\n def cos_after(fn, x):\n converted_fn, aux_args = api.closure_convert(fn, x)\n self.assertLessEqual(len(aux_args), 1)\n return _cos_after(converted_fn, x, *aux_args)\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def _cos_after(fn, x, *args):\n return jnp.cos(fn(x, *args))\n\n def fwd(fn, x, *args):\n y = _cos_after(fn, x, *args)\n return y, (x, args)\n\n def rev(fn, res, g):\n x, args = res\n x_bar = 17. * x\n args_bars = [42. * a for a in args]\n return (x_bar, *args_bars)\n\n _cos_after.defvjp(fwd, rev)\n\n def dist(c, s, x):\n return jnp.sum(s * (x - c) ** 2.)\n\n def solve(c, s, x):\n def closure(x):\n return dist(c, s, x)\n return cos_after(closure, x)\n\n c, s, x = 2. * jnp.ones(2), 3. * jnp.ones(2), jnp.ones(2)\n expected = jnp.cos(dist(c, s, x))\n self.assertAllClose(solve(c, s, x), expected, check_dtypes=False)\n g_c, g_x = api.grad(solve, argnums=(0, 2))(c, s, x)\n self.assertAllClose(g_c, 42. * c, check_dtypes=False)\n self.assertAllClose(g_x, 17. * x, check_dtypes=False)\n\n def test_float0_cotangents_automatically_handled(self):\n @jax.custom_vjp\n def f(x, y):\n return x\n\n def f_fwd(x, y):\n return x, None\n\n def f_bwd(_, zbar):\n return (0., 1)\n\n f.defvjp(f_fwd, f_bwd)\n\n jax.jit(lambda x: jax.vjp(f, 0., x)[1](1.))(1) # doesn't crash\n\n\nclass CustomTransposeTest(jtu.JaxTestCase):\n\n def transpose(self, f, x_example):\n def transposed(y):\n x, = api.linear_transpose(f, x_example)(y)\n return x\n return transposed\n\n def test_linear_call(self):\n def f(x, y):\n def fn(r, x): return x / r\n def tp(r, t): return t / r\n return x + api.linear_call(fn, tp, y, x)\n\n def f_ref(x, y):\n return x + x / y\n\n x = jnp.ones(2) * 6.\n y = jnp.ones(2) * 3.\n self.assertAllClose(f(x, y), f_ref(x, y))\n\n f1 = lambda x: f(x, y)\n f1_ref = lambda x: f_ref(x, y)\n self.assertAllClose(self.transpose(f1, x)(x),\n self.transpose(f1_ref, x)(x))\n\n def test_linear_call_incorrect_transpose(self):\n def f(x, y):\n def fn(r, x): return x / r\n def tp(r, t): return t / (2. * r) # nb: not the true transpose\n return x + api.linear_call(fn, tp, y, x)\n\n def f_ref(x, y):\n return x + x / y\n\n x = jnp.ones(2) * 6.\n y = jnp.ones(2) * 3.\n self.assertAllClose(f(x, y), f_ref(x, y))\n\n f1 = lambda x: f(x, y)\n f1_ref = lambda x: f_ref(x, 2. * y) # nb: double the reference divisor\n self.assertAllClose(self.transpose(f1, x)(x),\n self.transpose(f1_ref, x)(x))\n\n def test_linear_call_transpose_transpose_transpose(self):\n def fn(r, x): return x / r\n def tp(r, t): return t / (2. * r) # nb: untrue transpose\n def f_(x, y):\n return x + api.linear_call(fn, tp, y, x)\n\n x = jnp.ones(2) * 6.\n y = jnp.ones(2) * 3.\n f = lambda x: f_(x, y)\n ft = self.transpose(f, x)\n ftt = self.transpose(ft, x)\n fttt = self.transpose(ftt, x)\n self.assertAllClose(ft(x), x + tp(y, x))\n self.assertAllClose(f(x), ftt(x))\n self.assertAllClose(ft(x), fttt(x))\n\n def test_linear_call_scalar_to_vector(self):\n def f(c, x):\n def fn(_, x):\n return [x, x]\n\n def tp(_, t):\n t1, t2 = t\n return t1 + t2\n\n return api.linear_call(fn, tp, (), c * x)\n\n def f_ref(c, x):\n return [c * x, c * x]\n\n c, x = 2., 3.\n t = [4., 5.]\n self.assertAllClose(f(c, x), f_ref(c, x))\n self.assertAllClose(self.transpose(partial(f, c), x)(t),\n self.transpose(partial(f_ref, c), x)(t))\n\n def test_linear_call_nested(self):\n # identity function with an untrue transpose of 0\n def id_(x):\n def f(_, x): return x\n def t(_, t): return 0.\n return api.linear_call(f, t, (), x)\n\n # identity function with an untrue transpose of 7, and where both\n # forward and transpose have custom transpositions that should\n # never end up invoked.\n def f(x):\n def f_(_, x): return id_(x)\n def t_(_, t): return id_(7.)\n return api.linear_call(f_, t_, (), x)\n\n x = 5.\n id_t = self.transpose(id_, x)\n id_tt = self.transpose(id_t, x)\n ft = self.transpose(f, x)\n ftt = self.transpose(ft, x)\n fttt = self.transpose(ftt, x)\n\n self.assertAllClose(id_(x), x)\n self.assertAllClose(id_t(x), 0.)\n self.assertAllClose(id_tt(x), x)\n\n self.assertAllClose(f(x), x)\n self.assertAllClose(ft(x), 7.)\n self.assertAllClose(ftt(x), x)\n self.assertAllClose(fttt(x), 7.)\n\n def test_linear_call_jit(self):\n def f(x, y):\n def fn(r, x): return x / r\n def tp(r, t): return t / r\n return x + api.linear_call(fn, tp, y, x)\n\n x = jnp.ones(2) * 6.\n y = jnp.ones(2) * 3.\n self.assertAllClose(f(x, y), jax.jit(f)(x, y))\n\n f1 = lambda x: f(x, y)\n self.assertAllClose(self.transpose(f1, x)(x),\n jax.jit(self.transpose(f1, x))(x))\n\n\nclass InvertibleADTest(jtu.JaxTestCase):\n\n @jtu.ignore_warning(message=\"Values that an @invertible function closes\")\n def test_invertible_basic(self):\n def f(x):\n return lax.mul(lax.mul(lax.exp(x), 4.), x)\n\n finv = jax.invertible(f)\n x = jnp.ones((5,))\n\n jaxpr = jax.make_jaxpr(lambda p, ct: jax.vjp(finv, p)[1](ct))(x, x)\n\n # expected = \"\"\"\n # { lambda ; a b.\n # let c = exp a\n # d = mul c 4.0\n # e = mul d a\n # f = mul b a\n # g = div e a\n # h = mul b g\n # i = mul f 4.0\n # j = div g 4.0\n # k = mul f j\n # _ = reduce_sum[ axes=(0,) ] k\n # _ = log j\n # l = mul i j\n # m = add_any h l\n # in (m,) }\n # \"\"\"\n # self.assertMultiLineStrippedEqual(expected, str(jaxpr)) # no jaxpr test\n\n self.assertIn('div', str(jaxpr))\n self.assertIn('log', str(jaxpr)) # assumes no DCE\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x)))(x),\n jax.value_and_grad(lambda x: np.sum(finv(x)))(x),\n check_dtypes=True)\n\n def test_invertible_blocks(self):\n # NB: This is the reversible ResNet block\n def mk_reversible_block(f, g):\n @jax.custom_ivjp\n def rev_block(x1, x2):\n y1 = f(x2) + x1\n y2 = g(y1) + x2\n return y1, y2\n\n @rev_block.defivjp\n def rev_block_ivjp(xs, ys, dys):\n (y1, y2) = ys\n (dy1, dy2) = dys\n\n dgo, dx2 = dy2, dy2\n go, gvjp = jax.vjp(g, y1)\n dy1 += gvjp(dgo)[0]\n del gvjp\n x2 = y2 - go\n\n dfo, dx1 = dy1, dy1\n fo, fvjp = jax.vjp(f, x2)\n dx2 += fvjp(dfo)[0]\n del fvjp\n x1 = y1 - fo\n\n return (x1, x2), (dx1, dx2)\n\n return rev_block\n\n rev_block = mk_reversible_block(jnp.sin, jnp.cos)\n\n def g(x1, x2):\n for i in range(2):\n x1, x2 = rev_block(x1, x2)\n return x1, x2\n\n def reduce(f, x1, x2):\n y1, y2 = f(x1, x2)\n return np.sum(y1) + np.sum(y2)\n\n x = np.ones((1,))\n # FIXME: This breaks when argnums is left as default (i.e. 0), because JVP prunes\n # zero tangents from call primitives.\n self.assertAllClose(jax.value_and_grad(partial(reduce, jax.invertible(g)), argnums=(0, 1))(x, x + 2),\n jax.value_and_grad(partial(reduce, g), argnums=(0, 1))(x, x + 2),\n check_dtypes=True)\n\n def test_invertible_partial_diff(self):\n # Check that we don't have to differentiate with respect to inputs\n # of the invertible function.\n def f(x, y):\n return lax.mul(lax.mul(lax.exp(x), 4.), x), lax.add(y, 4.)\n\n finv = jax.invertible(f)\n o = np.ones((5,))\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x, o)[0]))(o),\n jax.value_and_grad(lambda x: np.sum(finv(x, o)[0]))(o),\n check_dtypes=True)\n\n def test_invertible_pytree(self):\n def f(x, y):\n return lax.add(lax.mul(lax.exp(x[0]), x[1]), y)\n\n finv = jax.invertible(f)\n o = np.ones((5,))\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f((x, x), x)[0]))(o),\n jax.value_and_grad(lambda x: np.sum(finv((x, x), x)[0]))(o),\n check_dtypes=True)\n\n\nclass BufferDonationTest(jtu.BufferDonationTestCase):\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_pmap_donate_argnums_invalidates_input(self):\n move = api.pmap(lambda x: x + x - x, donate_argnums=0)\n n = jax.local_device_count()\n x = api.pmap(lambda x: x)(jnp.ones([n]))\n y = move(x)\n self.assertDeleted(x)\n np.testing.assert_allclose(y, [1.] * n)\n\n def test_pmap_nested_donate_ignored(self):\n pmap_fun = jit(lambda x: api.pmap(lambda y: y ** 2, donate_argnums=0)(x))\n a = api.pmap(lambda x: x)(jnp.array([1]))\n\n # NOTE(mattjj): stopped raising error here and instead just ignored\n # with self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\n # pmap_fun(a)\n\n pmap_fun(a) # doesn't crash\n\n\nclass NamedCallTest(jtu.JaxTestCase):\n\n def test_default_name(self):\n\n @api.named_call\n def my_test_function(x):\n return x**2\n\n @jax.jit\n def f(x):\n return my_test_function(x)\n\n c = jax.xla_computation(f)(2)\n self.assertIn(\"my_test_function\", c.as_hlo_text())\n\n def test_non_jaxtype_arg(self):\n # For the test to fail without the invalid JaxType filter we need to pass\n # in a valid JaxType that forces the invalid Jaxtype to be raised to an\n # abstract value.\n def f(not_a_jaxtype, a_jaxtype):\n # then Jax needs to try and evaluate the abstractified non-JaxType\n if not_a_jaxtype:\n return a_jaxtype\n return 0\n\n f = api.named_call(f, name=\"test\")\n out = jax.jit(f, static_argnums=(0,))(\"not a Jaxtype\", 1)\n self.assertEqual(out, 1)\n\n @parameterized.parameters(jax.jit, jax.grad, jax.vmap, jax.remat)\n def test_jax_transforms(self, transform):\n f = jnp.sum\n x = jnp.array([1.])\n\n unnamed_out = transform(f)(x)\n named_out = transform(api.named_call(f, name=\"test\"))(x)\n\n self.assertEqual(unnamed_out, named_out)\n\n def test_static_argnums(self):\n f = api.named_call(lambda x, y: y if x else None, name=\"test\")\n f = jax.jit(f, static_argnums=(0,))\n out = f(True, 5)\n self.assertEqual(out, 5)\n\n def test_partial_eval(self):\n f = api.named_call(lambda x, y: y if x else None, name=\"test\")\n f = jax.jit(functools.partial(f, True))\n out = f(5)\n self.assertEqual(out, 5)\n\n @parameterized.named_parameters(jtu.cases_from_list(\n {\"testcase_name\": \"_jit_type={}_func={}\".format(jit_type, func),\n \"jit_type\": jit_type, \"func\": func}\n for func in ['identity', 'asarray', 'device_put']\n for jit_type in [None, \"python\", \"cpp\"]\n if not (jit_type is None and func == 'identity')))\n def test_integer_overflow(self, jit_type, func):\n funcdict = {\n 'identity': lambda x: x,\n 'asarray': jnp.asarray,\n 'device_put': api.device_put,\n }\n jit = {\n 'python': api._python_jit,\n 'cpp': api._cpp_jit,\n None: lambda x: x,\n }\n f = jit[jit_type](funcdict[func])\n\n int_dtype = dtypes.canonicalize_dtype(jnp.int_)\n int_max = np.iinfo(int_dtype).max\n int_min = np.iinfo(int_dtype).min\n\n self.assertEqual(f(int_max).dtype, int_dtype)\n self.assertEqual(f(int_min).dtype, int_dtype)\n self.assertRaises(OverflowError, f, int_max + 1)\n self.assertRaises(OverflowError, f, int_min - 1)\n\n\nclass BackendsTest(jtu.JaxTestCase):\n\n @unittest.skipIf(not sys.executable, \"test requires sys.executable\")\n @jtu.skip_on_devices(\"gpu\", \"tpu\")\n def test_cpu_warning_suppression(self):\n warning_expected = (\n \"import jax; \"\n \"jax.numpy.arange(10)\")\n warning_not_expected = (\n \"import jax; \"\n \"jax.config.update('jax_platform_name', 'cpu'); \"\n \"jax.numpy.arange(10)\")\n\n result = subprocess.run([sys.executable, '-c', warning_expected],\n check=True, capture_output=True)\n assert \"No GPU/TPU found\" in result.stderr.decode()\n\n result = subprocess.run([sys.executable, '-c', warning_not_expected],\n check=True, capture_output=True)\n assert \"No GPU/TPU found\" not in result.stderr.decode()\n\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n"
] |
[
[
"numpy.__version__.split",
"numpy.asarray",
"numpy.dtype",
"numpy.all",
"numpy.random.randn",
"numpy.iinfo",
"numpy.exp",
"numpy.arange",
"numpy.eye",
"numpy.float16",
"numpy.sin",
"numpy.float32",
"numpy.zeros",
"numpy.random.rand",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.random.RandomState",
"numpy.sum",
"numpy.int32",
"numpy.cos",
"numpy.ones",
"numpy.random.uniform"
]
] |
Ozgay/MockingBird
|
[
"b46e7a78667732114c22d4f5774c8481d6b75683"
] |
[
"toolbox/__init__.py"
] |
[
"from toolbox.ui import UI\nfrom encoder import inference as encoder\nfrom synthesizer.inference import Synthesizer\nfrom vocoder.wavernn import inference as rnn_vocoder\nfrom vocoder.hifigan import inference as gan_vocoder\nfrom pathlib import Path\nfrom time import perf_counter as timer\nfrom toolbox.utterance import Utterance\nimport numpy as np\nimport traceback\nimport sys\nimport torch\nimport librosa\nimport re\nfrom audioread.exceptions import NoBackendError\n\n# 默认使用wavernn\nvocoder = rnn_vocoder\n\n# Use this directory structure for your datasets, or modify it to fit your needs\nrecognized_datasets = [\n \"LibriSpeech/dev-clean\",\n \"LibriSpeech/dev-other\",\n \"LibriSpeech/test-clean\",\n \"LibriSpeech/test-other\",\n \"LibriSpeech/train-clean-100\",\n \"LibriSpeech/train-clean-360\",\n \"LibriSpeech/train-other-500\",\n \"LibriTTS/dev-clean\",\n \"LibriTTS/dev-other\",\n \"LibriTTS/test-clean\",\n \"LibriTTS/test-other\",\n \"LibriTTS/train-clean-100\",\n \"LibriTTS/train-clean-360\",\n \"LibriTTS/train-other-500\",\n \"LJSpeech-1.1\",\n \"VoxCeleb1/wav\",\n \"VoxCeleb1/test_wav\",\n \"VoxCeleb2/dev/aac\",\n \"VoxCeleb2/test/aac\",\n \"VCTK-Corpus/wav48\",\n \"aidatatang_200zh/corpus/dev\",\n \"aidatatang_200zh/corpus/test\",\n \"aishell3/test/wav\",\n \"magicdata/train\",\n]\n\n#Maximum of generated wavs to keep on memory\nMAX_WAVES = 15\n\nclass Toolbox:\n def __init__(self, datasets_root, enc_models_dir, syn_models_dir, voc_models_dir, seed, no_mp3_support):\n self.no_mp3_support = no_mp3_support\n sys.excepthook = self.excepthook\n self.datasets_root = datasets_root\n self.utterances = set()\n self.current_generated = (None, None, None, None) # speaker_name, spec, breaks, wav\n \n self.synthesizer = None # type: Synthesizer\n self.current_wav = None\n self.waves_list = []\n self.waves_count = 0\n self.waves_namelist = []\n\n # Check for webrtcvad (enables removal of silences in vocoder output)\n try:\n import webrtcvad\n self.trim_silences = True\n except:\n self.trim_silences = False\n\n # Initialize the events and the interface\n self.ui = UI()\n self.reset_ui(enc_models_dir, syn_models_dir, voc_models_dir, seed)\n self.setup_events()\n self.ui.start()\n\n def excepthook(self, exc_type, exc_value, exc_tb):\n traceback.print_exception(exc_type, exc_value, exc_tb)\n self.ui.log(\"Exception: %s\" % exc_value)\n \n def setup_events(self):\n # Dataset, speaker and utterance selection\n self.ui.browser_load_button.clicked.connect(lambda: self.load_from_browser())\n random_func = lambda level: lambda: self.ui.populate_browser(self.datasets_root,\n recognized_datasets,\n level)\n self.ui.random_dataset_button.clicked.connect(random_func(0))\n self.ui.random_speaker_button.clicked.connect(random_func(1))\n self.ui.random_utterance_button.clicked.connect(random_func(2))\n self.ui.dataset_box.currentIndexChanged.connect(random_func(1))\n self.ui.speaker_box.currentIndexChanged.connect(random_func(2))\n \n # Model selection\n self.ui.encoder_box.currentIndexChanged.connect(self.init_encoder)\n def func(): \n self.synthesizer = None\n self.ui.synthesizer_box.currentIndexChanged.connect(func)\n self.ui.vocoder_box.currentIndexChanged.connect(self.init_vocoder)\n \n # Utterance selection\n func = lambda: self.load_from_browser(self.ui.browse_file())\n self.ui.browser_browse_button.clicked.connect(func)\n func = lambda: self.ui.draw_utterance(self.ui.selected_utterance, \"current\")\n self.ui.utterance_history.currentIndexChanged.connect(func)\n func = lambda: self.ui.play(self.ui.selected_utterance.wav, Synthesizer.sample_rate)\n self.ui.play_button.clicked.connect(func)\n self.ui.stop_button.clicked.connect(self.ui.stop)\n self.ui.record_button.clicked.connect(self.record)\n\n #Audio\n self.ui.setup_audio_devices(Synthesizer.sample_rate)\n\n #Wav playback & save\n func = lambda: self.replay_last_wav()\n self.ui.replay_wav_button.clicked.connect(func)\n func = lambda: self.export_current_wave()\n self.ui.export_wav_button.clicked.connect(func)\n self.ui.waves_cb.currentIndexChanged.connect(self.set_current_wav)\n\n # Generation\n func = lambda: self.synthesize() or self.vocode()\n self.ui.generate_button.clicked.connect(func)\n self.ui.synthesize_button.clicked.connect(self.synthesize)\n self.ui.vocode_button.clicked.connect(self.vocode)\n self.ui.random_seed_checkbox.clicked.connect(self.update_seed_textbox)\n\n # UMAP legend\n self.ui.clear_button.clicked.connect(self.clear_utterances)\n\n def set_current_wav(self, index):\n self.current_wav = self.waves_list[index]\n\n def export_current_wave(self):\n self.ui.save_audio_file(self.current_wav, Synthesizer.sample_rate)\n\n def replay_last_wav(self):\n self.ui.play(self.current_wav, Synthesizer.sample_rate)\n\n def reset_ui(self, encoder_models_dir, synthesizer_models_dir, vocoder_models_dir, seed):\n self.ui.populate_browser(self.datasets_root, recognized_datasets, 0, True)\n self.ui.populate_models(encoder_models_dir, synthesizer_models_dir, vocoder_models_dir)\n self.ui.populate_gen_options(seed, self.trim_silences)\n \n def load_from_browser(self, fpath=None):\n if fpath is None:\n fpath = Path(self.datasets_root,\n self.ui.current_dataset_name,\n self.ui.current_speaker_name,\n self.ui.current_utterance_name)\n name = str(fpath.relative_to(self.datasets_root))\n speaker_name = self.ui.current_dataset_name + '_' + self.ui.current_speaker_name\n \n # Select the next utterance\n if self.ui.auto_next_checkbox.isChecked():\n self.ui.browser_select_next()\n elif fpath == \"\":\n return \n else:\n name = fpath.name\n speaker_name = fpath.parent.name\n\n if fpath.suffix.lower() == \".mp3\" and self.no_mp3_support:\n self.ui.log(\"Error: No mp3 file argument was passed but an mp3 file was used\")\n return\n\n # Get the wav from the disk. We take the wav with the vocoder/synthesizer format for\n # playback, so as to have a fair comparison with the generated audio\n wav = Synthesizer.load_preprocess_wav(fpath)\n self.ui.log(\"Loaded %s\" % name)\n\n self.add_real_utterance(wav, name, speaker_name)\n \n def record(self):\n wav = self.ui.record_one(encoder.sampling_rate, 5)\n if wav is None:\n return \n self.ui.play(wav, encoder.sampling_rate)\n\n speaker_name = \"user01\"\n name = speaker_name + \"_rec_%05d\" % np.random.randint(100000)\n self.add_real_utterance(wav, name, speaker_name)\n \n def add_real_utterance(self, wav, name, speaker_name):\n # Compute the mel spectrogram\n spec = Synthesizer.make_spectrogram(wav)\n self.ui.draw_spec(spec, \"current\")\n\n # Compute the embedding\n if not encoder.is_loaded():\n self.init_encoder()\n encoder_wav = encoder.preprocess_wav(wav)\n embed, partial_embeds, _ = encoder.embed_utterance(encoder_wav, return_partials=True)\n\n # Add the utterance\n utterance = Utterance(name, speaker_name, wav, spec, embed, partial_embeds, False)\n self.utterances.add(utterance)\n self.ui.register_utterance(utterance)\n\n # Plot it\n self.ui.draw_embed(embed, name, \"current\")\n self.ui.draw_umap_projections(self.utterances)\n \n def clear_utterances(self):\n self.utterances.clear()\n self.ui.draw_umap_projections(self.utterances)\n \n def synthesize(self):\n self.ui.log(\"Generating the mel spectrogram...\")\n self.ui.set_loading(1)\n \n # Update the synthesizer random seed\n if self.ui.random_seed_checkbox.isChecked():\n seed = int(self.ui.seed_textbox.text())\n self.ui.populate_gen_options(seed, self.trim_silences)\n else:\n seed = None\n\n if seed is not None:\n torch.manual_seed(seed)\n\n # Synthesize the spectrogram\n if self.synthesizer is None or seed is not None:\n self.init_synthesizer()\n\n texts = self.ui.text_prompt.toPlainText().split(\"\\n\")\n punctuation = '!,。、,' # punctuate and split/clean text\n processed_texts = []\n for text in texts:\n for processed_text in re.sub(r'[{}]+'.format(punctuation), '\\n', text).split('\\n'):\n if processed_text:\n processed_texts.append(processed_text.strip())\n texts = processed_texts\n embed = self.ui.selected_utterance.embed\n embeds = [embed] * len(texts)\n specs = self.synthesizer.synthesize_spectrograms(texts, embeds)\n breaks = [spec.shape[1] for spec in specs]\n spec = np.concatenate(specs, axis=1)\n \n self.ui.draw_spec(spec, \"generated\")\n self.current_generated = (self.ui.selected_utterance.speaker_name, spec, breaks, None)\n self.ui.set_loading(0)\n\n def vocode(self):\n speaker_name, spec, breaks, _ = self.current_generated\n assert spec is not None\n\n # Initialize the vocoder model and make it determinstic, if user provides a seed\n if self.ui.random_seed_checkbox.isChecked():\n seed = int(self.ui.seed_textbox.text())\n self.ui.populate_gen_options(seed, self.trim_silences)\n else:\n seed = None\n\n if seed is not None:\n torch.manual_seed(seed)\n\n # Synthesize the waveform\n if not vocoder.is_loaded() or seed is not None:\n self.init_vocoder()\n\n def vocoder_progress(i, seq_len, b_size, gen_rate):\n real_time_factor = (gen_rate / Synthesizer.sample_rate) * 1000\n line = \"Waveform generation: %d/%d (batch size: %d, rate: %.1fkHz - %.2fx real time)\" \\\n % (i * b_size, seq_len * b_size, b_size, gen_rate, real_time_factor)\n self.ui.log(line, \"overwrite\")\n self.ui.set_loading(i, seq_len)\n if self.ui.current_vocoder_fpath is not None:\n self.ui.log(\"\")\n wav = vocoder.infer_waveform(spec, progress_callback=vocoder_progress)\n else:\n self.ui.log(\"Waveform generation with Griffin-Lim... \")\n wav = Synthesizer.griffin_lim(spec)\n self.ui.set_loading(0)\n self.ui.log(\" Done!\", \"append\")\n \n # Add breaks\n b_ends = np.cumsum(np.array(breaks) * Synthesizer.hparams.hop_size)\n b_starts = np.concatenate(([0], b_ends[:-1]))\n wavs = [wav[start:end] for start, end, in zip(b_starts, b_ends)]\n breaks = [np.zeros(int(0.15 * Synthesizer.sample_rate))] * len(breaks)\n wav = np.concatenate([i for w, b in zip(wavs, breaks) for i in (w, b)])\n\n # Trim excessive silences\n if self.ui.trim_silences_checkbox.isChecked():\n wav = encoder.preprocess_wav(wav)\n\n # Play it\n wav = wav / np.abs(wav).max() * 0.97\n self.ui.play(wav, Synthesizer.sample_rate)\n\n # Name it (history displayed in combobox)\n # TODO better naming for the combobox items?\n wav_name = str(self.waves_count + 1)\n\n #Update waves combobox\n self.waves_count += 1\n if self.waves_count > MAX_WAVES:\n self.waves_list.pop()\n self.waves_namelist.pop()\n self.waves_list.insert(0, wav)\n self.waves_namelist.insert(0, wav_name)\n\n self.ui.waves_cb.disconnect()\n self.ui.waves_cb_model.setStringList(self.waves_namelist)\n self.ui.waves_cb.setCurrentIndex(0)\n self.ui.waves_cb.currentIndexChanged.connect(self.set_current_wav)\n\n # Update current wav\n self.set_current_wav(0)\n \n #Enable replay and save buttons:\n self.ui.replay_wav_button.setDisabled(False)\n self.ui.export_wav_button.setDisabled(False)\n\n # Compute the embedding\n # TODO: this is problematic with different sampling rates, gotta fix it\n if not encoder.is_loaded():\n self.init_encoder()\n encoder_wav = encoder.preprocess_wav(wav)\n embed, partial_embeds, _ = encoder.embed_utterance(encoder_wav, return_partials=True)\n \n # Add the utterance\n name = speaker_name + \"_gen_%05d\" % np.random.randint(100000)\n utterance = Utterance(name, speaker_name, wav, spec, embed, partial_embeds, True)\n self.utterances.add(utterance)\n \n # Plot it\n self.ui.draw_embed(embed, name, \"generated\")\n self.ui.draw_umap_projections(self.utterances)\n \n def init_encoder(self):\n model_fpath = self.ui.current_encoder_fpath\n \n self.ui.log(\"Loading the encoder %s... \" % model_fpath)\n self.ui.set_loading(1)\n start = timer()\n encoder.load_model(model_fpath)\n self.ui.log(\"Done (%dms).\" % int(1000 * (timer() - start)), \"append\")\n self.ui.set_loading(0)\n\n def init_synthesizer(self):\n model_fpath = self.ui.current_synthesizer_fpath\n\n self.ui.log(\"Loading the synthesizer %s... \" % model_fpath)\n self.ui.set_loading(1)\n start = timer()\n self.synthesizer = Synthesizer(model_fpath)\n self.ui.log(\"Done (%dms).\" % int(1000 * (timer() - start)), \"append\")\n self.ui.set_loading(0)\n \n def init_vocoder(self):\n\n global vocoder\n model_fpath = self.ui.current_vocoder_fpath\n # Case of Griffin-lim\n if model_fpath is None:\n return \n \n\n # Sekect vocoder based on model name\n if model_fpath.name[0] == \"g\":\n vocoder = gan_vocoder\n self.ui.log(\"set hifigan as vocoder\")\n else:\n vocoder = rnn_vocoder\n self.ui.log(\"set wavernn as vocoder\")\n \n self.ui.log(\"Loading the vocoder %s... \" % model_fpath)\n self.ui.set_loading(1)\n start = timer()\n vocoder.load_model(model_fpath)\n self.ui.log(\"Done (%dms).\" % int(1000 * (timer() - start)), \"append\")\n self.ui.set_loading(0)\n\n def update_seed_textbox(self):\n self.ui.update_seed_textbox() \n"
] |
[
[
"numpy.abs",
"torch.manual_seed",
"numpy.concatenate",
"numpy.array",
"numpy.random.randint"
]
] |
slocke716/airflow
|
[
"d5ad0761fd0b33cb89258ff6924c608c3e086680"
] |
[
"tests/hooks/test_hive_hook.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\nimport datetime\nimport itertools\nimport os\nimport random\nimport unittest\nfrom collections import OrderedDict\n\nfrom unittest import mock\nimport pandas as pd\nfrom hmsclient import HMSClient\n\nfrom airflow import DAG, configuration\nfrom airflow.exceptions import AirflowException\nfrom airflow.hooks.hive_hooks import HiveCliHook, HiveMetastoreHook, HiveServer2Hook\nfrom airflow.models.connection import Connection\nfrom airflow.operators.hive_operator import HiveOperator\nfrom airflow.utils import timezone\nfrom airflow.utils.operator_helpers import AIRFLOW_VAR_NAME_FORMAT_MAPPING\nfrom airflow.utils.tests import assertEqualIgnoreMultipleSpaces\n\nconfiguration.load_test_config()\n\nDEFAULT_DATE = timezone.datetime(2015, 1, 1)\nDEFAULT_DATE_ISO = DEFAULT_DATE.isoformat()\nDEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10]\n\n\nclass HiveEnvironmentTest(unittest.TestCase):\n\n def setUp(self):\n configuration.load_test_config()\n args = {'owner': 'airflow', 'start_date': DEFAULT_DATE}\n self.dag = DAG('test_dag_id', default_args=args)\n self.next_day = (DEFAULT_DATE +\n datetime.timedelta(days=1)).isoformat()[:10]\n self.database = 'airflow'\n self.partition_by = 'ds'\n self.table = 'static_babynames_partitioned'\n self.hql = \"\"\"\n CREATE DATABASE IF NOT EXISTS {{ params.database }};\n USE {{ params.database }};\n DROP TABLE IF EXISTS {{ params.table }};\n CREATE TABLE IF NOT EXISTS {{ params.table }} (\n state string,\n year string,\n name string,\n gender string,\n num int)\n PARTITIONED BY ({{ params.partition_by }} string);\n ALTER TABLE {{ params.table }}\n ADD PARTITION({{ params.partition_by }}='{{ ds }}');\n \"\"\"\n self.hook = HiveMetastoreHook()\n t = HiveOperator(\n task_id='HiveHook_' + str(random.randint(1, 10000)),\n params={\n 'database': self.database,\n 'table': self.table,\n 'partition_by': self.partition_by\n },\n hive_cli_conn_id='hive_cli_default',\n hql=self.hql, dag=self.dag)\n t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,\n ignore_ti_state=True)\n\n def tearDown(self):\n hook = HiveMetastoreHook()\n with hook.get_conn() as metastore:\n metastore.drop_table(self.database, self.table, deleteData=True)\n\n\nclass TestHiveCliHook(unittest.TestCase):\n\n def test_run_cli(self):\n hook = HiveCliHook()\n hook.run_cli(\"SHOW DATABASES\")\n\n def test_run_cli_with_hive_conf(self):\n hql = \"set key;\\n\" \\\n \"set airflow.ctx.dag_id;\\nset airflow.ctx.dag_run_id;\\n\" \\\n \"set airflow.ctx.task_id;\\nset airflow.ctx.execution_date;\\n\"\n\n dag_id_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_DAG_ID']['env_var_format']\n task_id_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_TASK_ID']['env_var_format']\n execution_date_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_EXECUTION_DATE'][\n 'env_var_format']\n dag_run_id_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_DAG_RUN_ID'][\n 'env_var_format']\n os.environ[dag_id_ctx_var_name] = 'test_dag_id'\n os.environ[task_id_ctx_var_name] = 'test_task_id'\n os.environ[execution_date_ctx_var_name] = 'test_execution_date'\n os.environ[dag_run_id_ctx_var_name] = 'test_dag_run_id'\n\n hook = HiveCliHook()\n output = hook.run_cli(hql=hql, hive_conf={'key': 'value'})\n self.assertIn('value', output)\n self.assertIn('test_dag_id', output)\n self.assertIn('test_task_id', output)\n self.assertIn('test_execution_date', output)\n self.assertIn('test_dag_run_id', output)\n\n del os.environ[dag_id_ctx_var_name]\n del os.environ[task_id_ctx_var_name]\n del os.environ[execution_date_ctx_var_name]\n del os.environ[dag_run_id_ctx_var_name]\n\n @mock.patch('airflow.hooks.hive_hooks.HiveCliHook.run_cli')\n def test_load_file(self, mock_run_cli):\n filepath = \"/path/to/input/file\"\n table = \"output_table\"\n\n hook = HiveCliHook()\n hook.load_file(filepath=filepath, table=table, create=False)\n\n query = (\n \"LOAD DATA LOCAL INPATH '{filepath}' \"\n \"OVERWRITE INTO TABLE {table} ;\\n\"\n .format(filepath=filepath, table=table)\n )\n mock_run_cli.assert_called_with(query)\n\n @mock.patch('airflow.hooks.hive_hooks.HiveCliHook.load_file')\n @mock.patch('pandas.DataFrame.to_csv')\n def test_load_df(self, mock_to_csv, mock_load_file):\n df = pd.DataFrame({\"c\": [\"foo\", \"bar\", \"baz\"]})\n table = \"t\"\n delimiter = \",\"\n encoding = \"utf-8\"\n\n hook = HiveCliHook()\n hook.load_df(df=df,\n table=table,\n delimiter=delimiter,\n encoding=encoding)\n\n assert mock_to_csv.call_count == 1\n kwargs = mock_to_csv.call_args[1]\n self.assertEqual(kwargs[\"header\"], False)\n self.assertEqual(kwargs[\"index\"], False)\n self.assertEqual(kwargs[\"sep\"], delimiter)\n\n assert mock_load_file.call_count == 1\n kwargs = mock_load_file.call_args[1]\n self.assertEqual(kwargs[\"delimiter\"], delimiter)\n self.assertEqual(kwargs[\"field_dict\"], {\"c\": \"STRING\"})\n self.assertTrue(isinstance(kwargs[\"field_dict\"], OrderedDict))\n self.assertEqual(kwargs[\"table\"], table)\n\n @mock.patch('airflow.hooks.hive_hooks.HiveCliHook.load_file')\n @mock.patch('pandas.DataFrame.to_csv')\n def test_load_df_with_optional_parameters(self, mock_to_csv, mock_load_file):\n hook = HiveCliHook()\n b = (True, False)\n for create, recreate in itertools.product(b, b):\n mock_load_file.reset_mock()\n hook.load_df(df=pd.DataFrame({\"c\": range(0, 10)}),\n table=\"t\",\n create=create,\n recreate=recreate)\n\n assert mock_load_file.call_count == 1\n kwargs = mock_load_file.call_args[1]\n self.assertEqual(kwargs[\"create\"], create)\n self.assertEqual(kwargs[\"recreate\"], recreate)\n\n @mock.patch('airflow.hooks.hive_hooks.HiveCliHook.run_cli')\n def test_load_df_with_data_types(self, mock_run_cli):\n d = OrderedDict()\n d['b'] = [True]\n d['i'] = [-1]\n d['t'] = [1]\n d['f'] = [0.0]\n d['c'] = ['c']\n d['M'] = [datetime.datetime(2018, 1, 1)]\n d['O'] = [object()]\n d['S'] = ['STRING'.encode('utf-8')]\n d['U'] = ['STRING']\n d['V'] = [None]\n df = pd.DataFrame(d)\n\n hook = HiveCliHook()\n hook.load_df(df, 't')\n\n query = \"\"\"\n CREATE TABLE IF NOT EXISTS t (\n b BOOLEAN,\n i BIGINT,\n t BIGINT,\n f DOUBLE,\n c STRING,\n M TIMESTAMP,\n O STRING,\n S STRING,\n U STRING,\n V STRING)\n ROW FORMAT DELIMITED\n FIELDS TERMINATED BY ','\n STORED AS textfile\n ;\n \"\"\"\n assertEqualIgnoreMultipleSpaces(self, mock_run_cli.call_args_list[0][0][0], query)\n\n\nclass TestHiveMetastoreHook(HiveEnvironmentTest):\n VALID_FILTER_MAP = {'key2': 'value2'}\n\n def test_get_max_partition_from_empty_part_specs(self):\n max_partition = \\\n HiveMetastoreHook._get_max_partition_from_part_specs([],\n 'key1',\n self.VALID_FILTER_MAP)\n self.assertIsNone(max_partition)\n\n def test_get_max_partition_from_valid_part_specs_and_invalid_filter_map(self):\n with self.assertRaises(AirflowException):\n HiveMetastoreHook._get_max_partition_from_part_specs(\n [{'key1': 'value1', 'key2': 'value2'},\n {'key1': 'value3', 'key2': 'value4'}],\n 'key1',\n {'key3': 'value5'})\n\n def test_get_max_partition_from_valid_part_specs_and_invalid_partition_key(self):\n with self.assertRaises(AirflowException):\n HiveMetastoreHook._get_max_partition_from_part_specs(\n [{'key1': 'value1', 'key2': 'value2'},\n {'key1': 'value3', 'key2': 'value4'}],\n 'key3',\n self.VALID_FILTER_MAP)\n\n def test_get_max_partition_from_valid_part_specs_and_none_partition_key(self):\n with self.assertRaises(AirflowException):\n HiveMetastoreHook._get_max_partition_from_part_specs(\n [{'key1': 'value1', 'key2': 'value2'},\n {'key1': 'value3', 'key2': 'value4'}],\n None,\n self.VALID_FILTER_MAP)\n\n def test_get_max_partition_from_valid_part_specs_and_none_filter_map(self):\n max_partition = \\\n HiveMetastoreHook._get_max_partition_from_part_specs(\n [{'key1': 'value1', 'key2': 'value2'},\n {'key1': 'value3', 'key2': 'value4'}],\n 'key1',\n None)\n\n # No partition will be filtered out.\n self.assertEqual(max_partition, b'value3')\n\n def test_get_max_partition_from_valid_part_specs(self):\n max_partition = \\\n HiveMetastoreHook._get_max_partition_from_part_specs(\n [{'key1': 'value1', 'key2': 'value2'},\n {'key1': 'value3', 'key2': 'value4'}],\n 'key1',\n self.VALID_FILTER_MAP)\n self.assertEqual(max_partition, b'value1')\n\n def test_get_metastore_client(self):\n self.assertIsInstance(self.hook.get_metastore_client(), HMSClient)\n\n @mock.patch(\"airflow.hooks.hive_hooks.HiveMetastoreHook.get_connection\",\n return_value=[Connection(host=\"localhost\", port=\"9802\")])\n @mock.patch(\"airflow.hooks.hive_hooks.socket\")\n def test_error_metastore_client(self, socket_mock, _find_vaild_server_mock):\n socket_mock.socket.return_value.connect_ex.return_value = 0\n self.hook.get_metastore_client()\n\n def test_get_conn(self):\n self.assertIsInstance(self.hook.get_conn(), HMSClient)\n\n def test_check_for_partition(self):\n partition = \"{p_by}='{date}'\".format(date=DEFAULT_DATE_DS,\n p_by=self.partition_by)\n missing_partition = \"{p_by}='{date}'\".format(date=self.next_day,\n p_by=self.partition_by)\n self.assertTrue(\n self.hook.check_for_partition(self.database, self.table,\n partition)\n )\n self.assertFalse(\n self.hook.check_for_partition(self.database, self.table,\n missing_partition)\n )\n\n def test_check_for_named_partition(self):\n partition = \"{p_by}={date}\".format(date=DEFAULT_DATE_DS,\n p_by=self.partition_by)\n missing_partition = \"{p_by}={date}\".format(date=self.next_day,\n p_by=self.partition_by)\n self.assertTrue(\n self.hook.check_for_named_partition(self.database,\n self.table,\n partition)\n )\n self.assertFalse(\n self.hook.check_for_named_partition(self.database,\n self.table,\n missing_partition)\n )\n\n def test_get_table(self):\n table_info = self.hook.get_table(db=self.database,\n table_name=self.table)\n self.assertEqual(table_info.tableName, self.table)\n columns = ['state', 'year', 'name', 'gender', 'num']\n self.assertEqual([col.name for col in table_info.sd.cols], columns)\n\n def test_get_tables(self):\n tables = self.hook.get_tables(db=self.database,\n pattern=self.table + \"*\")\n self.assertIn(self.table, {table.tableName for table in tables})\n\n def test_get_databases(self):\n databases = self.hook.get_databases(pattern='*')\n self.assertIn(self.database, databases)\n\n def test_get_partitions(self):\n partitions = self.hook.get_partitions(schema=self.database,\n table_name=self.table)\n self.assertEqual(len(partitions), 1)\n self.assertEqual(partitions, [{self.partition_by: DEFAULT_DATE_DS}])\n\n def test_max_partition(self):\n filter_map = {self.partition_by: DEFAULT_DATE_DS}\n partition = self.hook.max_partition(schema=self.database,\n table_name=self.table,\n field=self.partition_by,\n filter_map=filter_map)\n self.assertEqual(partition, DEFAULT_DATE_DS.encode('utf-8'))\n\n def test_table_exists(self):\n self.assertTrue(self.hook.table_exists(self.table, db=self.database))\n self.assertFalse(\n self.hook.table_exists(str(random.randint(1, 10000)))\n )\n\n\nclass TestHiveServer2Hook(unittest.TestCase):\n\n def _upload_dataframe(self):\n df = pd.DataFrame({'a': [1, 2], 'b': [1, 2]})\n self.local_path = '/tmp/TestHiveServer2Hook.csv'\n df.to_csv(self.local_path, header=False, index=False)\n\n def setUp(self):\n configuration.load_test_config()\n self._upload_dataframe()\n args = {'owner': 'airflow', 'start_date': DEFAULT_DATE}\n self.dag = DAG('test_dag_id', default_args=args)\n self.database = 'airflow'\n self.table = 'hive_server_hook'\n self.hql = \"\"\"\n CREATE DATABASE IF NOT EXISTS {{ params.database }};\n USE {{ params.database }};\n DROP TABLE IF EXISTS {{ params.table }};\n CREATE TABLE IF NOT EXISTS {{ params.table }} (\n a int,\n b int)\n ROW FORMAT DELIMITED\n FIELDS TERMINATED BY ',';\n LOAD DATA LOCAL INPATH '{{ params.csv_path }}'\n OVERWRITE INTO TABLE {{ params.table }};\n \"\"\"\n self.columns = ['{}.a'.format(self.table),\n '{}.b'.format(self.table)]\n self.hook = HiveMetastoreHook()\n t = HiveOperator(\n task_id='HiveHook_' + str(random.randint(1, 10000)),\n params={\n 'database': self.database,\n 'table': self.table,\n 'csv_path': self.local_path\n },\n hive_cli_conn_id='hive_cli_default',\n hql=self.hql, dag=self.dag)\n t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,\n ignore_ti_state=True)\n\n def tearDown(self):\n hook = HiveMetastoreHook()\n with hook.get_conn() as metastore:\n metastore.drop_table(self.database, self.table, deleteData=True)\n os.remove(self.local_path)\n\n def test_get_conn(self):\n hook = HiveServer2Hook()\n hook.get_conn()\n\n @mock.patch('pyhive.hive.connect')\n def test_get_conn_with_password(self, mock_connect):\n from airflow.hooks.base_hook import CONN_ENV_PREFIX\n conn_id = \"conn_with_password\"\n conn_env = CONN_ENV_PREFIX + conn_id.upper()\n conn_value = os.environ.get(conn_env)\n os.environ[conn_env] = \"jdbc+hive2://conn_id:conn_pass@localhost:10000/default?authMechanism=LDAP\"\n\n HiveServer2Hook(hiveserver2_conn_id=conn_id).get_conn()\n mock_connect.assert_called_with(\n host='localhost',\n port=10000,\n auth='LDAP',\n kerberos_service_name=None,\n username='conn_id',\n password='conn_pass',\n database='default')\n\n if conn_value:\n os.environ[conn_env] = conn_value\n\n def test_get_records(self):\n hook = HiveServer2Hook()\n query = \"SELECT * FROM {}\".format(self.table)\n results = hook.get_records(query, schema=self.database)\n self.assertListEqual(results, [(1, 1), (2, 2)])\n\n def test_get_pandas_df(self):\n hook = HiveServer2Hook()\n query = \"SELECT * FROM {}\".format(self.table)\n df = hook.get_pandas_df(query, schema=self.database)\n self.assertEqual(len(df), 2)\n self.assertListEqual(df.columns.tolist(), self.columns)\n self.assertListEqual(df[self.columns[0]].values.tolist(), [1, 2])\n\n def test_get_results_header(self):\n hook = HiveServer2Hook()\n query = \"SELECT * FROM {}\".format(self.table)\n results = hook.get_results(query, schema=self.database)\n self.assertListEqual([col[0] for col in results['header']],\n self.columns)\n\n def test_get_results_data(self):\n hook = HiveServer2Hook()\n query = \"SELECT * FROM {}\".format(self.table)\n results = hook.get_results(query, schema=self.database)\n self.assertListEqual(results['data'], [(1, 1), (2, 2)])\n\n def test_to_csv(self):\n hook = HiveServer2Hook()\n query = \"SELECT * FROM {}\".format(self.table)\n csv_filepath = 'query_results.csv'\n with self.assertLogs() as cm:\n hook.to_csv(query, csv_filepath, schema=self.database,\n delimiter=',', lineterminator='\\n', output_header=True, fetch_size=2)\n df = pd.read_csv(csv_filepath, sep=',')\n self.assertListEqual(df.columns.tolist(), self.columns)\n self.assertListEqual(df[self.columns[0]].values.tolist(), [1, 2])\n self.assertEqual(len(df), 2)\n self.assertIn('INFO:airflow.hooks.hive_hooks.HiveServer2Hook:'\n 'Written 2 rows so far.', cm.output)\n\n def test_multi_statements(self):\n sqls = [\n \"CREATE TABLE IF NOT EXISTS test_multi_statements (i INT)\",\n \"SELECT * FROM {}\".format(self.table),\n \"DROP TABLE test_multi_statements\",\n ]\n hook = HiveServer2Hook()\n results = hook.get_records(sqls, schema=self.database)\n self.assertListEqual(results, [(1, 1), (2, 2)])\n\n def test_get_results_with_hive_conf(self):\n hql = [\"set key\",\n \"set airflow.ctx.dag_id\",\n \"set airflow.ctx.dag_run_id\",\n \"set airflow.ctx.task_id\",\n \"set airflow.ctx.execution_date\"]\n\n dag_id_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_DAG_ID']['env_var_format']\n task_id_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_TASK_ID']['env_var_format']\n execution_date_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_EXECUTION_DATE'][\n 'env_var_format']\n dag_run_id_ctx_var_name = \\\n AIRFLOW_VAR_NAME_FORMAT_MAPPING['AIRFLOW_CONTEXT_DAG_RUN_ID'][\n 'env_var_format']\n os.environ[dag_id_ctx_var_name] = 'test_dag_id'\n os.environ[task_id_ctx_var_name] = 'test_task_id'\n os.environ[execution_date_ctx_var_name] = 'test_execution_date'\n os.environ[dag_run_id_ctx_var_name] = 'test_dag_run_id'\n\n hook = HiveServer2Hook()\n output = '\\n'.join(res_tuple[0]\n for res_tuple\n in hook.get_results(hql=hql,\n hive_conf={'key': 'value'})['data'])\n self.assertIn('value', output)\n self.assertIn('test_dag_id', output)\n self.assertIn('test_task_id', output)\n self.assertIn('test_execution_date', output)\n self.assertIn('test_dag_run_id', output)\n\n del os.environ[dag_id_ctx_var_name]\n del os.environ[task_id_ctx_var_name]\n del os.environ[execution_date_ctx_var_name]\n del os.environ[dag_run_id_ctx_var_name]\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
netaz/dirty-rl
|
[
"189b377b09db9c183fac78274ecfc7857bec695b"
] |
[
"utils/utils.py"
] |
[
"import torch\nimport os\nfrom colorama import Fore, Back, Style\n\n\ndtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\n\n\n\"\"\"Various decorators\"\"\"\n\ndef cached_function(func):\n \"\"\"Use this wrapper for functions that run often, but always return the same result.\n\n After executing the decorated function once, we cache the result and henceforth\n only return this cached value. You can take advantage of the one-time\n initialization, to run specific code once.\n \"\"\"\n def fn_wrapper(*args, **kwargs):\n if fn_wrapper._cache is None:\n ret = func(*args, **kwargs)\n fn_wrapper._cache = ret\n return fn_wrapper._cache\n fn_wrapper._cache = None\n return fn_wrapper\n\n\ndef func_footer(freq, footer_task):\n \"\"\"Run some code after the decorated function ends.\n\n Args:\n freq: (int) number of invocations of the decorated function between\n invocations of the `footer_task`\n footer_task: (callable) the footer function to invoke. This\n function takes the return value of the decorated-function as its\n only input. I.e.\n footer_task(decorated(*args, **kwargs))\n \"\"\"\n def wrap(func):\n def fn_wrapper(*args, **kwargs):\n func_footer._counter += 1\n ret = wrap.func(*args, **kwargs)\n if func_footer._counter % func_footer._freq == 0:\n footer_task(ret)\n return ret\n wrap.func = func\n return fn_wrapper\n func_footer._freq = freq\n func_footer._counter = 0\n return wrap\n\n\ndef optimize_cuda():\n \"\"\"Enable CUDNN benchmark mode for best performance.\n\n This is usually \"safe\" for image classification, regression and RL models\n as the input sizes don't change during the run. See here:\n https://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936/3\n \"\"\"\n torch.backends.cudnn.benchmark = True\n\n\n@cached_function\ndef get_device(device=None):\n \"\"\"Return the device used for model and backprop execution\"\"\"\n if device is None:\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n if device == 'cuda':\n optimize_cuda()\n return device\n\n\nclass GameProgressBar(object):\n \"\"\"A simple progress bar for Atari games with a binary outcome.\n\n This class is written to be used with a controlled-execution block.\n \"\"\"\n def __init__(self, episode_number, is_win_func=None):\n \"\"\"Args:\n episode_number: (int) episode number\n is_win_func: (callable) callable which takes as input the reward\n and determines if the game was won. The default `is_win_func`\n assumes a win produces a positive reward.\n \"\"\"\n if is_win_func is None:\n is_win_func = self.default_win_fn\n self.episode_number = episode_number\n self.is_win = is_win_func\n\n @staticmethod\n def default_win_fn(reward):\n return reward > 0\n\n def __enter__(self):\n print(f\"{self.episode_number}: \", end='', flush=True)\n return self.update\n\n def __exit__(self, type, value, traceback):\n print() # new-line at game end\n\n def update(self, reward):\n \"\"\"Print the updated status of a game in episode.\n \"\"\"\n print((Fore.GREEN + \"-\" if self.is_win(reward) else Fore.RED + \".\") +\n Style.RESET_ALL, end='', flush=True)\n\n\ndef save_checkpoint(model, optimizer, episode, dir):\n fname = f\"{dir}/checkpoint.pt\"\n checkpoint = {'epoch': episode,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict()}\n torch.save(checkpoint, fname)\n\n\ndef load_checkpoint(model, optimizer, chkpt_file, device):\n chkpt_file = os.path.expanduser(chkpt_file)\n checkpoint = torch.load(chkpt_file, map_location=device)\n model.load_state_dict(checkpoint['model'])\n model.to(device)\n optimizer.load_state_dict(checkpoint['optimizer'])\n\n\nclass ExponentialMovingAvg(object):\n \"\"\"EMA helper.\n\n See: https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n The exponential moving average for a series Y may be calculated recursively:\n ema (@ time=t) = new_sample if t = 1\n (1-alpha) * ema + alpha * new_sample if t>1\n \"\"\"\n def __init__(self, alpha):\n \"\"\"\n Args:\n alpha: (float) a constant smoothing factor between 0 and 1. A higher\n alpha value discounts older observations faster.\n \"\"\"\n self.alpha = alpha\n assert 1.0 >= alpha > 0.\n self.ema = None\n\n def update(self, new_sample):\n self.ema = new_sample if self.ema is None else \\\n (1-self.alpha) * self.ema + self.alpha * new_sample\n return self.ema\n\n @property\n def value(self):\n return self.ema\n\n def value_mt(self):\n return self.ema"
] |
[
[
"torch.load",
"torch.cuda.is_available",
"torch.save"
]
] |
wty9391/maximal-revenue-rtb
|
[
"a0c8cc5e03e2306023e77323c8f0bfc5b4988823"
] |
[
"winner.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import quad\n\nepsilon = sys.float_info.epsilon\n\nclass wining_pridictor():\n def __init__(self,d=0.1,max_iter=5000,eta=0.001,step=1,eta_decay=0.99):\n self.d = d\n self.max_iter = max_iter\n self.eta = eta\n self.step = step\n self.eta_decay = eta_decay\n \n # winning function type:tanh\n def w(self, b):\n # b is bid price\n # d is hyperparameter need to be fit\n return np.tanh(b*self.d)\n\n def w_der(self, b):\n # b is bid price\n # d is hyperparameter need to be fit\n return self.d*(1-np.tanh(b*self.d)**2)\n \n def w_der_d(self, b):\n return b*(1-np.tanh(b*self.d)**2)\n \n# def w_der_d_kl(self,b,y):\n# return (self.w_der_d(b)).transpose().dot(\n# np.log(self.w(b)/y) + 1)\n \n def fit(self, x, y):\n print(\"Now start to fit winning function\")\n record_num = np.shape(x)[0]\n \n for i in range(self.max_iter):\n # least squares loss\n error = self.w(x)-y\n self.d = self.d - self.eta * (1/record_num) * (error.transpose().dot(self.w_der_d(x)))\n loss = 1/2 * (1/record_num) * (error**2).sum()\n \n # kl divergence loss\n# self.d = self.d - self.eta * (1/record_num)*self.w_der_d_kl(x,y)\n# loss = entropy(self.w(x), y)\n\n if i % 50 == 0:\n print(\"epoch {}, d {}, loss {}\".format(i, self.d, loss))\n \n self.eta = self.eta * self.eta_decay\n \n print(\"Fitting winning function finished\")\n \n # do integrate to speed up predicting winning price\n bins = 2000\n step = self.step\n self.integrate_b = np.arange(0, bins+1, step)\n self.integrate_b_y = self.w_der(self.integrate_b)\n temp = self.integrate_b * self.integrate_b_y\n self.integrate = np.zeros_like(self.integrate_b, dtype=np.float)\n self.integrate[0] = temp[0]*step\n for i in range(bins):\n self.integrate[i+1] = self.integrate[i]*1.0 + temp[i+1]*step\n self.integrate[0] = self.integrate[1] # incase of zero\n \n def plot(self, x, y):\n y_prediction = self.w(x)\n \n plt.plot(y, label='truth')\n plt.plot(y_prediction, label='w=tanh({0:.5f}x)'.format(self.d))\n plt.legend() \n\n def predict(self, x):\n return self.w(x)\n \n def predict_win_price(self, x):\n x = np.round(x)\n r = np.zeros_like(x)\n for i in range(np.shape(x)[0]):\n index = int(x[i])\n try:\n r[i] = self.integrate[index]\n except IndexError:\n r[i] = self.integrate[-1]\n \n return r\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.plot",
"numpy.round",
"numpy.zeros_like",
"numpy.shape",
"numpy.tanh"
]
] |
LucSkyvvalker/TAUS
|
[
"a804de4386fa31de3fb9a7aebbd686ba2c12a243"
] |
[
"scripts/scoreModel.py"
] |
[
"import extractSents as es\nimport pandas as pd\nimport numpy as np\nimport cleandatas as cd\nimport learnclassify as lc\nimport score as sc\nimport corpusFuncs as corpf\n\n\n\"\"\"\nscoreModel() is used to get a print of:\n'Precision, Recall\nF1-score\nAccuracy\nCross Entropy'\nThe function will ask for input on what\n\"\"\"\ndef scoreModel():\n try:\n testX = np.array(pd.read_csv('../data/testX.csv'))\n testY = np.array(pd.read_csv('../data/testY.csv'),dtype=int)\n except:\n print(\"No valid datasets were found\")\n try:\n (unigramSrc,bigramSrc, trigramSrc, unigramTgt,bigramTgt,trigramTgt,\n unigramSrcPos,bigramSrcPos,trigramSrcPos,unigramTgtPos,bigramTgtPos,\n trigramTgtPos) = corpf.loadNLP()\n except:\n print('No ngram models were found, making new ones...')\n (unigramSrc,bigramSrc, trigramSrc, unigramTgt,bigramTgt,trigramTgt,\n unigramSrcPos,bigramSrcPos,trigramSrcPos,unigramTgtPos,bigramTgtPos,\n trigramTgtPos) = corpf.getNgramModels()\n method = input('What model would you like to use \\nSee README for available options: ' )\n if method == 'SVM':\n svm = lc.loadmodel('../data/svm.joblib')\n scores = lc.classCLF(svm, testX)\n elif method == 'LR':\n lr = lc.loadmodel('../data/lr.joblib')\n scores = lc.classCLF(lr, testX)\n elif method == 'MLP':\n mlp = lc.loadmodel('../data/mlp.joblib')\n scores = lc.classCLF(mlp, testX)\n elif method == 'NBC':\n NBC = lc.loadmodel('../data/NBC.joblib')\n scores = lc.NBC.classnb(NBC,testX)\n else:\n print('No valid method was given, please see the README for instrucions')\n fscore = sc.fscore(scores[0], testY)\n print('F1score:',fscore)\n accuracy = sc.accuracy(scores[0], testY)\n print('Accuracy:', accuracy)\n crossent = []\n for i in range(len(testY)):\n correctEst = 0\n if scores[0][i] == testY[i]:\n correctEst = 1\n crossent.append(sc.crossEntropy(scores[1][i], correctEst))\n print('CrossEnt:', np.mean(crossent))\n return fscore, method, scores, crossent\n\n\n\n\nif __name__ == \"__main__\":\n scoreModel()\n"
] |
[
[
"pandas.read_csv",
"numpy.mean"
]
] |
dreamflyer/musket_core
|
[
"1bdf1b4715a3b5c63bf687799d7b977fdf49053f"
] |
[
"musket_core/crf.py"
] |
[
"from __future__ import absolute_import\r\nfrom __future__ import division\r\n\r\nimport warnings\r\n\r\nfrom keras import backend as K\r\nfrom keras import activations\r\nfrom keras import initializers\r\nfrom keras import regularizers\r\nfrom keras import constraints\r\nfrom keras.layers import Layer\r\nfrom keras.layers import InputSpec\r\nimport keras\r\nfrom musket_core import model\r\nfrom musket_core.losses import crf_loss\r\n \r\ndef _get_accuracy(y_true, y_pred, mask, sparse_target=False):\r\n y_pred = K.argmax(y_pred, -1)\r\n if sparse_target:\r\n y_true = K.cast(y_true[:, :, 0], K.dtype(y_pred))\r\n else:\r\n y_true = K.argmax(y_true, -1)\r\n judge = K.cast(K.equal(y_pred, y_true), K.floatx())\r\n if mask is None:\r\n return K.mean(judge)\r\n else:\r\n mask = K.cast(mask, K.floatx())\r\n return K.sum(judge * mask) / K.sum(mask)\r\n\r\n\r\ndef crf_viterbi_accuracy(y_true, y_pred):\r\n '''Use Viterbi algorithm to get best path, and compute its accuracy.\r\n `y_pred` must be an output from CRF.'''\r\n crf, idx = y_pred._keras_history[:2]\r\n X = crf._inbound_nodes[idx].input_tensors[0]\r\n mask = crf._inbound_nodes[idx].input_masks[0]\r\n y_pred = crf.viterbi_decoding(X, mask)\r\n return _get_accuracy(y_true, y_pred, mask, crf.sparse_target)\r\n\r\n\r\ndef crf_marginal_accuracy(y_true, y_pred):\r\n '''Use time-wise marginal argmax as prediction.\r\n `y_pred` must be an output from CRF with `learn_mode=\"marginal\"`.'''\r\n crf, idx = y_pred._keras_history[:2]\r\n X = crf._inbound_nodes[idx].input_tensors[0]\r\n mask = crf._inbound_nodes[idx].input_masks[0]\r\n y_pred = crf.get_marginal_prob(X, mask)\r\n return _get_accuracy(y_true, y_pred, mask, crf.sparse_target)\r\n\r\n\r\ndef crf_accuracy(y_true, y_pred):\r\n '''Ge default accuracy based on CRF `test_mode`.'''\r\n crf, idx = y_pred._keras_history[:2]\r\n if crf.test_mode == 'viterbi':\r\n return crf_viterbi_accuracy(y_true, y_pred)\r\n else:\r\n return crf_marginal_accuracy(y_true, y_pred) \r\n\r\nkeras.utils.get_custom_objects()[\"crf_viterbi_accuracy\"]=crf_viterbi_accuracy\r\n\r\n@model.block\r\nclass CRF(Layer):\r\n \"\"\"An implementation of linear chain conditional random field (CRF).\r\n\r\n An linear chain CRF is defined to maximize the following likelihood function:\r\n\r\n $$ L(W, U, b; y_1, ..., y_n) := \\frac{1}{Z}\r\n \\sum_{y_1, ..., y_n} \\exp(-a_1' y_1 - a_n' y_n\r\n - \\sum_{k=1^n}((f(x_k' W + b) y_k) + y_1' U y_2)), $$\r\n\r\n where:\r\n $Z$: normalization constant\r\n $x_k, y_k$: inputs and outputs\r\n\r\n This implementation has two modes for optimization:\r\n 1. (`join mode`) optimized by maximizing join likelihood,\r\n which is optimal in theory of statistics.\r\n Note that in this case, CRF must be the output/last layer.\r\n 2. (`marginal mode`) return marginal probabilities on each time\r\n step and optimized via composition\r\n likelihood (product of marginal likelihood), i.e.,\r\n using `categorical_crossentropy` loss.\r\n Note that in this case, CRF can be either the last layer or an\r\n intermediate layer (though not explored).\r\n\r\n For prediction (test phrase), one can choose either Viterbi\r\n best path (class indices) or marginal\r\n probabilities if probabilities are needed.\r\n However, if one chooses *join mode* for training,\r\n Viterbi output is typically better than marginal output,\r\n but the marginal output will still perform\r\n reasonably close, while if *marginal mode* is used for training,\r\n marginal output usually performs\r\n much better. The default behavior and `metrics.crf_accuracy`\r\n is set according to this observation.\r\n\r\n In addition, this implementation supports masking and accepts either\r\n onehot or sparse target.\r\n\r\n If you open a issue or a pull request about CRF, please\r\n add 'cc @lzfelix' to notify Luiz Felix.\r\n\r\n\r\n # Examples\r\n\r\n ```python\r\n from keras_contrib.layers import CRF\r\n from keras_contrib.losses import crf_loss\r\n from keras_contrib.metrics import crf_viterbi_accuracy\r\n\r\n model = Sequential()\r\n model.add(Embedding(3001, 300, mask_zero=True)(X)\r\n\r\n # use learn_mode = 'join', test_mode = 'viterbi',\r\n # sparse_target = True (label indice output)\r\n crf = CRF(10, sparse_target=True)\r\n model.add(crf)\r\n\r\n # crf_accuracy is default to Viterbi acc if using join-mode (default).\r\n # One can add crf.marginal_acc if interested, but may slow down learning\r\n model.compile('adam', loss=crf_loss, metrics=[crf_viterbi_accuracy])\r\n\r\n # y must be label indices (with shape 1 at dim 3) here,\r\n # since `sparse_target=True`\r\n model.fit(x, y)\r\n\r\n # prediction give onehot representation of Viterbi best path\r\n y_hat = model.predict(x_test)\r\n ```\r\n\r\n The following snippet shows how to load a persisted\r\n model that uses the CRF layer:\r\n\r\n ```python\r\n from keras.models import load_model\r\n from keras_contrib.losses import import crf_loss\r\n from keras_contrib.metrics import crf_viterbi_accuracy\r\n\r\n custom_objects={'CRF': CRF,\r\n 'crf_loss': crf_loss,\r\n 'crf_viterbi_accuracy': crf_viterbi_accuracy}\r\n\r\n loaded_model = load_model('<path_to_model>',\r\n custom_objects=custom_objects)\r\n ```\r\n\r\n # Arguments\r\n units: Positive integer, dimensionality of the output space.\r\n learn_mode: Either 'join' or 'marginal'.\r\n The former train the model by maximizing join likelihood while the latter\r\n maximize the product of marginal likelihood over all time steps.\r\n One should use `losses.crf_nll` for 'join' mode\r\n and `losses.categorical_crossentropy` or\r\n `losses.sparse_categorical_crossentropy` for\r\n `marginal` mode. For convenience, simply\r\n use `losses.crf_loss`, which will decide the proper loss as described.\r\n test_mode: Either 'viterbi' or 'marginal'.\r\n The former is recommended and as default when `learn_mode = 'join'` and\r\n gives one-hot representation of the best path at test (prediction) time,\r\n while the latter is recommended and chosen as default\r\n when `learn_mode = 'marginal'`,\r\n which produces marginal probabilities for each time step.\r\n For evaluating metrics, one should\r\n use `metrics.crf_viterbi_accuracy` for 'viterbi' mode and\r\n 'metrics.crf_marginal_accuracy' for 'marginal' mode, or\r\n simply use `metrics.crf_accuracy` for\r\n both which automatically decides it as described.\r\n One can also use both for evaluation at training.\r\n sparse_target: Boolean (default False) indicating\r\n if provided labels are one-hot or\r\n indices (with shape 1 at dim 3).\r\n use_boundary: Boolean (default True) indicating if trainable\r\n start-end chain energies\r\n should be added to model.\r\n use_bias: Boolean, whether the layer uses a bias vector.\r\n kernel_initializer: Initializer for the `kernel` weights matrix,\r\n used for the linear transformation of the inputs.\r\n (see [initializers](../initializers.md)).\r\n chain_initializer: Initializer for the `chain_kernel` weights matrix,\r\n used for the CRF chain energy.\r\n (see [initializers](../initializers.md)).\r\n boundary_initializer: Initializer for the `left_boundary`,\r\n 'right_boundary' weights vectors,\r\n used for the start/left and end/right boundary energy.\r\n (see [initializers](../initializers.md)).\r\n bias_initializer: Initializer for the bias vector\r\n (see [initializers](../initializers.md)).\r\n activation: Activation function to use\r\n (see [activations](../activations.md)).\r\n If you pass None, no activation is applied\r\n (ie. \"linear\" activation: `a(x) = x`).\r\n kernel_regularizer: Regularizer function applied to\r\n the `kernel` weights matrix\r\n (see [regularizer](../regularizers.md)).\r\n chain_regularizer: Regularizer function applied to\r\n the `chain_kernel` weights matrix\r\n (see [regularizer](../regularizers.md)).\r\n boundary_regularizer: Regularizer function applied to\r\n the 'left_boundary', 'right_boundary' weight vectors\r\n (see [regularizer](../regularizers.md)).\r\n bias_regularizer: Regularizer function applied to the bias vector\r\n (see [regularizer](../regularizers.md)).\r\n kernel_constraint: Constraint function applied to\r\n the `kernel` weights matrix\r\n (see [constraints](../constraints.md)).\r\n chain_constraint: Constraint function applied to\r\n the `chain_kernel` weights matrix\r\n (see [constraints](../constraints.md)).\r\n boundary_constraint: Constraint function applied to\r\n the `left_boundary`, `right_boundary` weights vectors\r\n (see [constraints](../constraints.md)).\r\n bias_constraint: Constraint function applied to the bias vector\r\n (see [constraints](../constraints.md)).\r\n input_dim: dimensionality of the input (integer).\r\n This argument (or alternatively, the keyword argument `input_shape`)\r\n is required when using this layer as the first layer in a model.\r\n unroll: Boolean (default False). If True, the network will be\r\n unrolled, else a symbolic loop will be used.\r\n Unrolling can speed-up a RNN, although it tends\r\n to be more memory-intensive.\r\n Unrolling is only suitable for short sequences.\r\n\r\n # Input shape\r\n 3D tensor with shape `(nb_samples, timesteps, input_dim)`.\r\n\r\n # Output shape\r\n 3D tensor with shape `(nb_samples, timesteps, units)`.\r\n\r\n # Masking\r\n This layer supports masking for input data with a variable number\r\n of timesteps. To introduce masks to your data,\r\n use an [Embedding](embeddings.md) layer with the `mask_zero` parameter\r\n set to `True`.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, units,\r\n learn_mode='join',\r\n test_mode=None,\r\n sparse_target=False,\r\n use_boundary=True,\r\n use_bias=True,\r\n activation='linear',\r\n kernel_initializer='glorot_uniform',\r\n chain_initializer='orthogonal',\r\n bias_initializer='zeros',\r\n boundary_initializer='zeros',\r\n kernel_regularizer=None,\r\n chain_regularizer=None,\r\n boundary_regularizer=None,\r\n bias_regularizer=None,\r\n kernel_constraint=None,\r\n chain_constraint=None,\r\n boundary_constraint=None,\r\n bias_constraint=None,\r\n input_dim=None,\r\n unroll=False,\r\n **kwargs):\r\n super(CRF, self).__init__(**kwargs)\r\n self.supports_masking = True\r\n self.units = units\r\n self.learn_mode = learn_mode\r\n assert self.learn_mode in ['join', 'marginal']\r\n self.test_mode = test_mode\r\n if self.test_mode is None:\r\n self.test_mode = 'viterbi' if self.learn_mode == 'join' else 'marginal'\r\n else:\r\n assert self.test_mode in ['viterbi', 'marginal']\r\n self.sparse_target = sparse_target\r\n self.use_boundary = use_boundary\r\n self.use_bias = use_bias\r\n\r\n self.activation = activations.get(activation)\r\n\r\n self.kernel_initializer = initializers.get(kernel_initializer)\r\n self.chain_initializer = initializers.get(chain_initializer)\r\n self.boundary_initializer = initializers.get(boundary_initializer)\r\n self.bias_initializer = initializers.get(bias_initializer)\r\n\r\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\r\n self.chain_regularizer = regularizers.get(chain_regularizer)\r\n self.boundary_regularizer = regularizers.get(boundary_regularizer)\r\n self.bias_regularizer = regularizers.get(bias_regularizer)\r\n\r\n self.kernel_constraint = constraints.get(kernel_constraint)\r\n self.chain_constraint = constraints.get(chain_constraint)\r\n self.boundary_constraint = constraints.get(boundary_constraint)\r\n self.bias_constraint = constraints.get(bias_constraint)\r\n\r\n self.unroll = unroll\r\n\r\n def build(self, input_shape):\r\n input_shape = tuple(input_shape)\r\n self.input_spec = [InputSpec(shape=input_shape)]\r\n self.input_dim = input_shape[-1]\r\n\r\n self.kernel = self.add_weight(shape=(self.input_dim, self.units),\r\n name='kernel',\r\n initializer=self.kernel_initializer,\r\n regularizer=self.kernel_regularizer,\r\n constraint=self.kernel_constraint)\r\n self.chain_kernel = self.add_weight(shape=(self.units, self.units),\r\n name='chain_kernel',\r\n initializer=self.chain_initializer,\r\n regularizer=self.chain_regularizer,\r\n constraint=self.chain_constraint)\r\n if self.use_bias:\r\n self.bias = self.add_weight(shape=(self.units,),\r\n name='bias',\r\n initializer=self.bias_initializer,\r\n regularizer=self.bias_regularizer,\r\n constraint=self.bias_constraint)\r\n else:\r\n self.bias = 0\r\n\r\n if self.use_boundary:\r\n self.left_boundary = self.add_weight(shape=(self.units,),\r\n name='left_boundary',\r\n initializer=self.boundary_initializer,\r\n regularizer=self.boundary_regularizer,\r\n constraint=self.boundary_constraint)\r\n self.right_boundary = self.add_weight(shape=(self.units,),\r\n name='right_boundary',\r\n initializer=self.boundary_initializer,\r\n regularizer=self.boundary_regularizer,\r\n constraint=self.boundary_constraint)\r\n self.built = True\r\n\r\n def call(self, X, mask=None):\r\n if mask is not None:\r\n assert K.ndim(mask) == 2, 'Input mask to CRF must have dim 2 if not None'\r\n\r\n if self.test_mode == 'viterbi':\r\n test_output = self.viterbi_decoding(X, mask)\r\n else:\r\n test_output = self.get_marginal_prob(X, mask)\r\n\r\n self.uses_learning_phase = True\r\n if self.learn_mode == 'join':\r\n train_output = K.zeros_like(K.dot(X, self.kernel))\r\n out = K.in_train_phase(train_output, test_output)\r\n else:\r\n if self.test_mode == 'viterbi':\r\n train_output = self.get_marginal_prob(X, mask)\r\n out = K.in_train_phase(train_output, test_output)\r\n else:\r\n out = test_output\r\n return out\r\n\r\n def compute_output_shape(self, input_shape):\r\n return input_shape[:2] + (self.units,)\r\n\r\n def compute_mask(self, input, mask=None):\r\n if mask is not None and self.learn_mode == 'join':\r\n return K.any(mask, axis=1)\r\n return mask\r\n\r\n def get_config(self):\r\n config = {\r\n 'units': self.units,\r\n 'learn_mode': self.learn_mode,\r\n 'test_mode': self.test_mode,\r\n 'use_boundary': self.use_boundary,\r\n 'use_bias': self.use_bias,\r\n 'sparse_target': self.sparse_target,\r\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\r\n 'chain_initializer': initializers.serialize(self.chain_initializer),\r\n 'boundary_initializer': initializers.serialize(\r\n self.boundary_initializer),\r\n 'bias_initializer': initializers.serialize(self.bias_initializer),\r\n 'activation': activations.serialize(self.activation),\r\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\r\n 'chain_regularizer': regularizers.serialize(self.chain_regularizer),\r\n 'boundary_regularizer': regularizers.serialize(\r\n self.boundary_regularizer),\r\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\r\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\r\n 'chain_constraint': constraints.serialize(self.chain_constraint),\r\n 'boundary_constraint': constraints.serialize(self.boundary_constraint),\r\n 'bias_constraint': constraints.serialize(self.bias_constraint),\r\n 'input_dim': self.input_dim,\r\n 'unroll': self.unroll}\r\n base_config = super(CRF, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n @property\r\n def loss_function(self):\r\n warnings.warn('CRF.loss_function is deprecated '\r\n 'and it might be removed in the future. Please '\r\n 'use losses.crf_loss instead.')\r\n return crf_loss\r\n\r\n @property\r\n def accuracy(self):\r\n warnings.warn('CRF.accuracy is deprecated and it '\r\n 'might be removed in the future. Please '\r\n 'use metrics.crf_accuracy')\r\n if self.test_mode == 'viterbi':\r\n return crf_viterbi_accuracy\r\n else:\r\n return crf_marginal_accuracy\r\n\r\n @property\r\n def viterbi_acc(self):\r\n warnings.warn('CRF.viterbi_acc is deprecated and it might '\r\n 'be removed in the future. Please '\r\n 'use metrics.viterbi_acc instead.')\r\n return crf_viterbi_accuracy\r\n\r\n @property\r\n def marginal_acc(self):\r\n warnings.warn('CRF.moarginal_acc is deprecated and it '\r\n 'might be removed in the future. Please '\r\n 'use metrics.marginal_acc instead.')\r\n return crf_marginal_accuracy\r\n\r\n @staticmethod\r\n def softmaxNd(x, axis=-1):\r\n m = K.max(x, axis=axis, keepdims=True)\r\n exp_x = K.exp(x - m)\r\n prob_x = exp_x / K.sum(exp_x, axis=axis, keepdims=True)\r\n return prob_x\r\n\r\n @staticmethod\r\n def shift_left(x, offset=1):\r\n assert offset > 0\r\n return K.concatenate([x[:, offset:], K.zeros_like(x[:, :offset])], axis=1)\r\n\r\n @staticmethod\r\n def shift_right(x, offset=1):\r\n assert offset > 0\r\n return K.concatenate([K.zeros_like(x[:, :offset]), x[:, :-offset]], axis=1)\r\n\r\n def add_boundary_energy(self, energy, mask, start, end):\r\n start = K.expand_dims(K.expand_dims(start, 0), 0)\r\n end = K.expand_dims(K.expand_dims(end, 0), 0)\r\n if mask is None:\r\n energy = K.concatenate([energy[:, :1, :] + start, energy[:, 1:, :]],\r\n axis=1)\r\n energy = K.concatenate([energy[:, :-1, :], energy[:, -1:, :] + end],\r\n axis=1)\r\n else:\r\n mask = K.expand_dims(K.cast(mask, K.floatx()))\r\n start_mask = K.cast(K.greater(mask, self.shift_right(mask)), K.floatx())\r\n end_mask = K.cast(K.greater(self.shift_left(mask), mask), K.floatx())\r\n energy = energy + start_mask * start\r\n energy = energy + end_mask * end\r\n return energy\r\n\r\n def get_log_normalization_constant(self, input_energy, mask, **kwargs):\r\n \"\"\"Compute logarithm of the normalization constant Z, where\r\n Z = sum exp(-E) -> logZ = log sum exp(-E) =: -nlogZ\r\n \"\"\"\r\n # should have logZ[:, i] == logZ[:, j] for any i, j\r\n logZ = self.recursion(input_energy, mask, return_sequences=False, **kwargs)\r\n return logZ[:, 0]\r\n\r\n def get_energy(self, y_true, input_energy, mask):\r\n \"\"\"Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3\r\n \"\"\"\r\n input_energy = K.sum(input_energy * y_true, 2) # (B, T)\r\n # (B, T-1)\r\n chain_energy = K.sum(K.dot(y_true[:, :-1, :],\r\n self.chain_kernel) * y_true[:, 1:, :], 2)\r\n\r\n if mask is not None:\r\n mask = K.cast(mask, K.floatx())\r\n # (B, T-1), mask[:,:-1]*mask[:,1:] makes it work with any padding\r\n chain_mask = mask[:, :-1] * mask[:, 1:]\r\n input_energy = input_energy * mask\r\n chain_energy = chain_energy * chain_mask\r\n total_energy = K.sum(input_energy, -1) + K.sum(chain_energy, -1) # (B, )\r\n\r\n return total_energy\r\n\r\n def get_negative_log_likelihood(self, y_true, X, mask):\r\n \"\"\"Compute the loss, i.e., negative log likelihood (normalize by number of time steps)\r\n likelihood = 1/Z * exp(-E) -> neg_log_like = - log(1/Z * exp(-E)) = logZ + E\r\n \"\"\"\r\n input_energy = self.activation(K.dot(X, self.kernel) + self.bias)\r\n if self.use_boundary:\r\n input_energy = self.add_boundary_energy(input_energy, mask,\r\n self.left_boundary,\r\n self.right_boundary)\r\n energy = self.get_energy(y_true, input_energy, mask)\r\n logZ = self.get_log_normalization_constant(input_energy, mask,\r\n input_length=K.int_shape(X)[1])\r\n nloglik = logZ + energy\r\n if mask is not None:\r\n nloglik = nloglik / K.sum(K.cast(mask, K.floatx()), 1)\r\n else:\r\n nloglik = nloglik / K.cast(K.shape(X)[1], K.floatx())\r\n return nloglik\r\n\r\n def step(self, input_energy_t, states, return_logZ=True):\r\n # not in the following `prev_target_val` has shape = (B, F)\r\n # where B = batch_size, F = output feature dim\r\n # Note: `i` is of float32, due to the behavior of `K.rnn`\r\n prev_target_val, i, chain_energy = states[:3]\r\n t = K.cast(i[0, 0], dtype='int32')\r\n if len(states) > 3:\r\n if K.backend() == 'theano':\r\n m = states[3][:, t:(t + 2)]\r\n else:\r\n m = K.slice(states[3], [0, t], [-1, 2])\r\n input_energy_t = input_energy_t * K.expand_dims(m[:, 0])\r\n # (1, F, F)*(B, 1, 1) -> (B, F, F)\r\n chain_energy = chain_energy * K.expand_dims(\r\n K.expand_dims(m[:, 0] * m[:, 1]))\r\n if return_logZ:\r\n # shapes: (1, B, F) + (B, F, 1) -> (B, F, F)\r\n energy = chain_energy + K.expand_dims(input_energy_t - prev_target_val, 2)\r\n new_target_val = K.logsumexp(-energy, 1) # shapes: (B, F)\r\n return new_target_val, [new_target_val, i + 1]\r\n else:\r\n energy = chain_energy + K.expand_dims(input_energy_t + prev_target_val, 2)\r\n min_energy = K.min(energy, 1)\r\n # cast for tf-version `K.rnn\r\n argmin_table = K.cast(K.argmin(energy, 1), K.floatx())\r\n return argmin_table, [min_energy, i + 1]\r\n\r\n def recursion(self, input_energy, mask=None, go_backwards=False,\r\n return_sequences=True, return_logZ=True, input_length=None):\r\n \"\"\"Forward (alpha) or backward (beta) recursion\r\n\r\n If `return_logZ = True`, compute the logZ, the normalization constant:\r\n\r\n \\[ Z = \\sum_{y1, y2, y3} exp(-E) # energy\r\n = \\sum_{y1, y2, y3} exp(-(u1' y1 + y1' W y2 + u2' y2 + y2' W y3 + u3' y3))\r\n = sum_{y2, y3} (exp(-(u2' y2 + y2' W y3 + u3' y3))\r\n sum_{y1} exp(-(u1' y1' + y1' W y2))) \\]\r\n\r\n Denote:\r\n \\[ S(y2) := sum_{y1} exp(-(u1' y1 + y1' W y2)), \\]\r\n \\[ Z = sum_{y2, y3} exp(log S(y2) - (u2' y2 + y2' W y3 + u3' y3)) \\]\r\n \\[ logS(y2) = log S(y2) = log_sum_exp(-(u1' y1' + y1' W y2)) \\]\r\n Note that:\r\n yi's are one-hot vectors\r\n u1, u3: boundary energies have been merged\r\n\r\n If `return_logZ = False`, compute the Viterbi's best path lookup table.\r\n \"\"\"\r\n chain_energy = self.chain_kernel\r\n # shape=(1, F, F): F=num of output features. 1st F is for t-1, 2nd F for t\r\n chain_energy = K.expand_dims(chain_energy, 0)\r\n # shape=(B, F), dtype=float32\r\n prev_target_val = K.zeros_like(input_energy[:, 0, :])\r\n\r\n if go_backwards:\r\n input_energy = K.reverse(input_energy, 1)\r\n if mask is not None:\r\n mask = K.reverse(mask, 1)\r\n\r\n initial_states = [prev_target_val, K.zeros_like(prev_target_val[:, :1])]\r\n constants = [chain_energy]\r\n\r\n if mask is not None:\r\n mask2 = K.cast(K.concatenate([mask, K.zeros_like(mask[:, :1])], axis=1),\r\n K.floatx())\r\n constants.append(mask2)\r\n\r\n def _step(input_energy_i, states):\r\n return self.step(input_energy_i, states, return_logZ)\r\n\r\n target_val_last, target_val_seq, _ = K.rnn(_step, input_energy,\r\n initial_states,\r\n constants=constants,\r\n input_length=input_length,\r\n unroll=self.unroll)\r\n\r\n if return_sequences:\r\n if go_backwards:\r\n target_val_seq = K.reverse(target_val_seq, 1)\r\n return target_val_seq\r\n else:\r\n return target_val_last\r\n\r\n def forward_recursion(self, input_energy, **kwargs):\r\n return self.recursion(input_energy, **kwargs)\r\n\r\n def backward_recursion(self, input_energy, **kwargs):\r\n return self.recursion(input_energy, go_backwards=True, **kwargs)\r\n\r\n def get_marginal_prob(self, X, mask=None):\r\n input_energy = self.activation(K.dot(X, self.kernel) + self.bias)\r\n if self.use_boundary:\r\n input_energy = self.add_boundary_energy(input_energy, mask,\r\n self.left_boundary,\r\n self.right_boundary)\r\n input_length = K.int_shape(X)[1]\r\n alpha = self.forward_recursion(input_energy, mask=mask,\r\n input_length=input_length)\r\n beta = self.backward_recursion(input_energy, mask=mask,\r\n input_length=input_length)\r\n if mask is not None:\r\n input_energy = input_energy * K.expand_dims(K.cast(mask, K.floatx()))\r\n margin = -(self.shift_right(alpha) + input_energy + self.shift_left(beta))\r\n return self.softmaxNd(margin)\r\n\r\n def viterbi_decoding(self, X, mask=None):\r\n input_energy = self.activation(K.dot(X, self.kernel) + self.bias)\r\n if self.use_boundary:\r\n input_energy = self.add_boundary_energy(\r\n input_energy, mask, self.left_boundary, self.right_boundary)\r\n\r\n argmin_tables = self.recursion(input_energy, mask, return_logZ=False)\r\n argmin_tables = K.cast(argmin_tables, 'int32')\r\n\r\n # backward to find best path, `initial_best_idx` can be any,\r\n # as all elements in the last argmin_table are the same\r\n argmin_tables = K.reverse(argmin_tables, 1)\r\n # matrix instead of vector is required by tf `K.rnn`\r\n initial_best_idx = [K.expand_dims(argmin_tables[:, 0, 0])]\r\n \r\n\r\n def gather_each_row(params, indices):\r\n n = K.shape(indices)[0]\r\n \r\n if K.backend() == 'tensorflow':\r\n import tensorflow as tf\r\n indices = K.transpose(K.stack([tf.range(n), indices]))\r\n return tf.gather_nd(params, indices)\r\n else:\r\n raise NotImplementedError\r\n\r\n def find_path(argmin_table, best_idx):\r\n next_best_idx = gather_each_row(argmin_table, best_idx[0][:, 0])\r\n next_best_idx = K.expand_dims(next_best_idx)\r\n \r\n return next_best_idx, [next_best_idx]\r\n\r\n _, best_paths, _ = K.rnn(find_path, argmin_tables, initial_best_idx,\r\n input_length=K.int_shape(X)[1], unroll=self.unroll)\r\n best_paths = K.reverse(best_paths, 1)\r\n best_paths = K.squeeze(best_paths, 2)\r\n\r\n return K.one_hot(best_paths, self.units)"
] |
[
[
"tensorflow.gather_nd",
"tensorflow.range"
]
] |
seanpquinn/augerta
|
[
"43862fd6b5360c9b7c5a7b3502fb7738ea2e8d75"
] |
[
"web_monitor/north_daily_events_final_2016_catchup.py"
] |
[
"import time\nimport math\nimport datetime\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter, date2num\nimport numpy as np\nimport subprocess as sp\nimport time\nimport sys\nimport os\nfrom itertools import groupby\nfrom sklearn.neighbors import KernelDensity\nfrom sklearn.grid_search import GridSearchCV\nimport peakutils\n\n#dirlist=['/home/augta/data/north/Events/20161104',\n# '/home/augta/data/north/Events/20161107',\n# '/home/augta/data/north/Events/20161108',\n# '/home/augta/data/north/Events/20161109',\n# '/home/augta/data/north/Events/20161110',\ndirlist=['/home/augta/data/north/Events/20161111',\n '/home/augta/data/north/Events/20161112',\n '/home/augta/data/north/Events/20161113',\n '/home/augta/data/north/Events/20161114',\n '/home/augta/data/north/Events/20161115',\n '/home/augta/data/north/Events/20161116',\n '/home/augta/data/north/Events/20161117',\n '/home/augta/data/north/Events/20161119',\n '/home/augta/data/north/Events/20161120',\n '/home/augta/data/north/Events/20161121',\n '/home/augta/data/north/Events/20161122',\n '/home/augta/data/north/Events/20161123',\n '/home/augta/data/north/Events/20161124',\n '/home/augta/data/north/Events/20161125',\n '/home/augta/data/north/Events/20161126',\n '/home/augta/data/north/Events/20161127',\n '/home/augta/data/north/Events/20161128',\n '/home/augta/data/north/Events/20161129',\n '/home/augta/data/north/Events/20161130',\n '/home/augta/data/north/Events/20161201',\n '/home/augta/data/north/Events/20161202',\n '/home/augta/data/north/Events/20161203',\n '/home/augta/data/north/Events/20161204',\n '/home/augta/data/north/Events/20161205',\n '/home/augta/data/north/Events/20161206',\n '/home/augta/data/north/Events/20161207',\n '/home/augta/data/north/Events/20161208',\n '/home/augta/data/north/Events/20161209',\n '/home/augta/data/north/Events/20161210',\n '/home/augta/data/north/Events/20161211',\n '/home/augta/data/north/Events/20161212',\n '/home/augta/data/north/Events/20161213',\n '/home/augta/data/north/Events/20161214',\n '/home/augta/data/north/Events/20161215',\n '/home/augta/data/north/Events/20161216']\n\nfor folder in dirlist:\n\tfdate = folder.split('/')[-1]\n\tos.chdir('/home/augta/data/north/Muons/%s' %fdate)\n\tdl=os.listdir('.')\n\tdl.sort()\n\tfor i in dl:\n\t\tif '.2016' in i:\n\t\t\tdl.remove(i)\n\twith open('/home/augta/data/north/Events/%s/muon_list.txt' %fdate,'w') as F:\n\t\tfor j in dl:\n\t\t\tF.write(j+'\\n')\n\tyr = int(fdate[:4])\n\tmo = int(fdate[4:6])\n\tdy = int(fdate[6:])\n\n\tsecsInWeek = 604800 \n\tsecsInDay = 86400 \n\tgpsEpoch = (1980, 1, 6, 0, 0, 0) # (year, month, day, hh, mm, ss)\n\n\t#*****NOTICE*****: LEAPSEC MUST BE CHANGED TO 18 ON JAN 1 2017\n\tdef gpsFromUTC(year, month, day, hour, minute, sec, leapSecs=18): \n\t\t\"\"\"converts UTC to GPS second\n\n\t\tOriginal function can be found at: http://software.ligo.org/docs/glue/frames.html\n\n\t\tGPS time is basically measured in (atomic) seconds since \n\t\tJanuary 6, 1980, 00:00:00.0 (the GPS Epoch) \n\n\t\tThe GPS week starts on Saturday midnight (Sunday morning), and runs \n\t\tfor 604800 seconds. \n\n\t\tCurrently, GPS time is 17 seconds ahead of UTC\n\t\tWhile GPS SVs transmit this difference and the date when another leap \n\t\tsecond takes effect, the use of leap seconds cannot be predicted. This \n\t\troutine is precise until the next leap second is introduced and has to be \n\t\tupdated after that.\n\n\t\tSOW = Seconds of Week \n\t\tSOD = Seconds of Day \n\n\t\tNote: Python represents time in integer seconds, fractions are lost!!! \n\t\t\"\"\" \n\t\tsecFract = sec % 1 \n\t\tepochTuple = gpsEpoch + (-1, -1, 0) \n\t\tt0 = time.mktime(epochTuple) \n\t\tt = time.mktime((year, month, day, hour, minute, sec, -1, -1, 0)) \n\t\t# Note: time.mktime strictly works in localtime and to yield UTC, it should be \n\t\t# corrected with time.timezone \n\t\t# However, since we use the difference, this correction is unnecessary. \n\t\t# Warning: trouble if daylight savings flag is set to -1 or 1 !!! \n\t\tt = t + leapSecs\n\t\ttdiff = t - t0\n\t\tgpsSOW = (tdiff % secsInWeek) + secFract\n\t\tgpsWeek = int(math.floor(tdiff/secsInWeek))\n\t\tgpsDay = int(math.floor(gpsSOW/secsInDay))\n\t\tgpsSOD = (gpsSOW % secsInDay)\n\t\tgps_tuple = (gpsWeek, gpsSOW, gpsDay, gpsSOD)\n\t\treturn int(gps_tuple[0] * secsInWeek + gps_tuple[1])\n\n\tdef get_calib(evt_utc_time,mu_list):\n\t\t#Convert event utc time stamp to datetime\n\t\tevt_ds = datetime.datetime.strptime(evt_utc_time,'%Y/%m/%d_%H:%M:%S')\n\t\tevt_gps = gpsFromUTC(evt_ds.year,evt_ds.month,evt_ds.day,evt_ds.hour,\n\t\t\tevt_ds.minute,evt_ds.second)\n\t\t#A30 base line\n\t\ta30_bl = 512\n\t\tmu_file = ''\n\t\tfor i in range(len(mu_list)-1):\n\t\t\tmu_ds_t1 = datetime.datetime.strptime(mu_list[i].split('.')[0],'%Y%m%d_%H%M%S')\n\t\t\tmu_ds_t2 = datetime.datetime.strptime(mu_list[i+1].split('.')[0],'%Y%m%d_%H%M%S')\n\t\t\tif evt_ds > mu_ds_t1 and evt_ds < mu_ds_t2:\n\t\t\t\tmu_file = mu_list[i]\n\t\t\t\tmu_gps_start = mu_ds_t1\n\t\t\telif i == len(mu_list)-2 and evt_ds > mu_ds_t2:\n\t\t\t\tmu_file = mu_list[i+1]\n\t\t\t\tmu_gps_start = mu_ds_t2\n\t\t\telse:\n\t\t\t\tcontinue\n\t\tif len(mu_file) > 0:\t\n\t\t\tmu_ds_t1 = mu_gps_start\n\t\t\tmu_gps = gpsFromUTC(mu_ds_t1.year,mu_ds_t1.month,mu_ds_t1.day,mu_ds_t1.hour,\n\t\t\t\tmu_ds_t1.minute,mu_ds_t1.second)\n\t\t\tstart_index = (evt_gps - mu_gps) - 60\n\t\t\tmu_full_path = '/home/augta/data/north/Muons/%s/'%fdate+mu_file\n\t\t\tout_file = '/home/augta/web_monitor/tmp/muon_tmp.txt'\n\t\t\tsp.call(['./anamu','-i','%s' %mu_full_path,'-o','%s' %out_file,\n\t\t\t\t'--first','%i' %start_index,'--last','%i' %(start_index + 60)])\n\t\t\tmu_data = np.loadtxt(out_file,usecols=(1,))\n\t\t\t#Construct pulse height and charge histograms\n\t\t\tpeaks = np.zeros(3840)\n\t\t\tcharge = np.zeros(3840)\n\t\t\tfor i in range(3840):\n\t\t\t\ttmp_trace = mu_data[i*63:(i+1)*63] - 511.5\n\t\t\t\ttry:\n\t\t\t\t\tpeak_loc = tmp_trace.argmax()\n\t\t\t\t\tpeaks[i] = peak_loc + 1\n\t\t\t\t\tcharge[i] = tmp_trace.sum()\n\t\t\t\texcept:\n\t\t\t\t\tpeaks = peaks[:i]\n\t\t\t\t\tcharge = charge[:i]\n\t\t\t\t\tbreak\n\t\treturn charge,peaks\n\n\tfname = \"%i%02d%02d\" %(yr,mo,dy)\n\tos.chdir('/home/augta/web_monitor')\n\tmuon_list = dl\n\n\tevt_list = os.listdir('/home/augta/data/north/Events/%s/' %fname)\n\tevt_list = [k for k in evt_list if '.evt' in k]\n\tglob_evt_list = [k for k in evt_list if 'global' in k]\n\tglob_evt_list.sort()\n\tlocal_evt_list = [k for k in evt_list if 'local' in k]\n\tlocal_evt_list.sort()\n\n\tnloc_dir = '/var/www/html/monitor/data/local_north/%s/' %fname\n\tnglob_dir = '/var/www/html/monitor/data/global_north/%s/' %fname\n\tsp.call(['mkdir',nloc_dir])\n\tsp.call(['mkdir',nglob_dir])\n\n\tsp.call(['rm',nloc_dir+'signal.txt'])\n\tsp.call(['rm',nglob_dir+'signal.txt'])\n\t\n\tbl_evt = 514\n\tif len(local_evt_list) > 0:\n\t\tfor m in local_evt_list:\n\t\t\tcurr_file = '/home/augta/data/north/Events/%s/%s' %(fname,m)\n\t\t\tfout = nloc_dir + m[:-4] + '.txt'\n\t\t\twith open(fout,'w') as f:\n\t\t\t\tsp.call(['./testevt',curr_file],stdout=f)\n\t\t\twith open(fout,'r') as f:\n\t\t\t\tgps_line = f.readline() # Get GPS information\n\t\t\t\tgps_ts = gps_line.split(' ')[-2].replace(',','') # Select time stamp\n\t\t\t\tutc_line = f.readline()\n\t\t\t\tutc_date = utc_line.split(' ')[-2]\n\t\t\t\tutc_time = utc_line.split(' ')[-1].split('.')[0]\n\t\t\tutc = utc_date+'_'+utc_time\n\t\t\tvem_charge,vem_peak = get_calib(utc,muon_list)\n\t\t\tvem_charge = vem_charge[vem_charge>0.]\n\t\t\tplt.subplot(121)\n\t\t\tplt.hist(vem_peak,bins=np.arange(0,50),histtype='step')\n\t\t\txx,yy = np.histogram(vem_peak,np.arange(0,50))\n\t\t\tvem_pulse_peak = xx.argmax() + 1\n\t\t\tplt.xlabel('ADC counts')\n\t\t\tplt.title('A30 Pulse height')\n\t\t\tplt.subplot(122)\n\t\t\tgrid=GridSearchCV(KernelDensity(),{'bandwidth': np.linspace(5,80,30)},cv=10,n_jobs=2)\n\t\t\tgrid.fit(vem_charge[:,None])\n\t\t\tkde=grid.best_estimator_\n\t\t\tbest_bw=grid.best_params_['bandwidth']\n\t\t\txgrid=np.linspace(0,2000,4000)\n\t\t\tpdf=np.exp(kde.score_samples(xgrid[:,None]))\n\t\t\tplt.hist(vem_charge,bins=50,histtype='stepfilled',fc='gray',alpha=0.2,normed=True)\n\t\t\tplt.xlabel('Integrated ADC')\n\t\t\tall_local_max = peakutils.indexes(pdf,thres = 0.4,min_dist=125)\n\t\t\tif len(all_local_max)>1:\n\t\t\t\tmuon_hump = all_local_max[1]\n\t\t\telse:\n\t\t\t\tmuon_hump = 0\n\t\t\tpeak_pdf = muon_hump\n\t\t\tvem_charge_peak = xgrid[peak_pdf]\n\t\t\t#If vem_charge_peak > 800, probably something wrong, just use old one\n\t\t\tif vem_charge_peak > 800 or len(all_local_max) == 1:\n\t\t\t\tvem_charge_peak = vem_charge_peak_old\n\t\t\tplt.vlines(vem_charge_peak,plt.ylim()[0],plt.ylim()[1])\n\t\t\tplt.plot(xgrid,pdf)\n\t\t\tplt.xlim(xmin=0.,xmax=1300) #No need to go beyond 500 for current HV\n\t\t\tplt.title('A30 Charge')\n\t\t\tplt.tight_layout()\n\t\t\tplt.savefig(nloc_dir+'calib_histogram_%s.png' %m[:-4])\n\t\t\tplt.close('all')\n\t\t\tdata = np.loadtxt(fout,usecols=(4,),skiprows=3)\n\t\t\tadc = data - bl_evt\n\t\t\tymax = adc.argmax()\n\t\t\tsignal = np.sum(adc[ymax-40:ymax+50]) / (vem_charge_peak / 30)\n\t\t\tadc = adc / vem_charge_peak * (vem_pulse_peak+1)\n\t\t\tx = np.arange(1024)\n\t\t\tplt.step(x,adc)\n\t\t\tplt.xlim(ymax-40,ymax+50)\n\t\t\tplt.xlabel('Time [10 ns]')\n\t\t\tplt.ylabel('Signal [VEM Peak]')\n\t\t\tplt.title('Signal: %.3f VEM' %signal)\n\t\t\tplt.savefig(nloc_dir + '%s_trace.png' %m[:-4])\n\t\t\tplt.close('all')\n\t\t\tlocindex = m.split('_')[0]\n\t\t\tnp.savetxt(nloc_dir+'%s_pulse_height_hist.txt' %m[:-4],vem_peak)\n\t\t\tnp.savetxt(nloc_dir+'%s_charge_hist.txt' %m[:-4],vem_charge)\n\t\t\twith open(nloc_dir + 'signal.txt','a') as f:\n\t\t\t\tf.write('%s %s %.3f %.3f %.3f\\n' %(locindex,gps_ts,signal,vem_charge_peak,vem_pulse_peak))\n\t\t\twith open('north_local_signal.txt','a') as f:\n\t\t\t\tf.write('%s %.3f\\n' %(gps_ts,signal))\n\t\t\tvem_charge_peak_old = vem_charge_peak\n\t\t\tvem_pulse_peak_old = vem_pulse_peak\n\n\tif len(glob_evt_list) > 0:\n\t\tfor m in glob_evt_list:\n\t\t\tcurr_file = '/home/augta/data/north/Events/%s/%s' %(fname,m)\n\t\t\tfout = nglob_dir + m[:-4] + '.txt'\n\t\t\twith open(fout,'w') as f:\n\t\t\t\tsp.call(['./testevt',curr_file],stdout=f)\n\t\t\twith open(fout,'r') as f:\n\t\t\t\tgps_line = f.readline() # Get GPS information\n\t\t\t\tgps_ts = gps_line.split(' ')[-2].replace(',','') # Select time stamp\n\t\t\t\tutc_line = f.readline()\n\t\t\t\tutc_date = utc_line.split(' ')[-2]\n\t\t\t\tutc_time = utc_line.split(' ')[-1].split('.')[0]\n\t\t\tutc = utc_date+'_'+utc_time\n\t\t\tvem_charge,vem_peak = get_calib(utc,muon_list)\n\t\t\tvem_charge = vem_charge[vem_charge>0.]\n\t\t\tplt.subplot(121)\n\t\t\tplt.hist(vem_peak,bins=np.arange(0,50),histtype='step')\n\t\t\txx,yy = np.histogram(vem_peak,np.arange(0,50))\n\t\t\tvem_pulse_peak = xx.argmax() + 1\n\t\t\tplt.xlabel('ADC counts')\n\t\t\tplt.title('A30 Pulse height')\n\t\t\tplt.subplot(122)\n\t\t\tgrid=GridSearchCV(KernelDensity(),{'bandwidth': np.linspace(5,80,30)},cv=10,n_jobs=2)\n\t\t\tgrid.fit(vem_charge[:,None])\n\t\t\tkde=grid.best_estimator_\n\t\t\tbest_bw=grid.best_params_['bandwidth']\n\t\t\txgrid=np.linspace(0,2000,4000)\n\t\t\tpdf=np.exp(kde.score_samples(xgrid[:,None]))\n\t\t\tplt.hist(vem_charge,bins=50,histtype='stepfilled',fc='gray',alpha=0.2,normed=True)\n\t\t\tplt.xlabel('Integrated ADC')\n\t\t\tall_local_max = peakutils.indexes(pdf,thres = 0.4,min_dist=125)\n\t\t\tif len(all_local_max)>1:\n\t\t\t\tmuon_hump = all_local_max[1]\n\t\t\telse:\n\t\t\t\tmuon_hump = 0\n\t\t\tpeak_pdf = muon_hump\n\t\t\tvem_charge_peak = xgrid[peak_pdf]\n\t\t\t#If vem_charge_peak > 800, probably something wrong, just use old one\n\t\t\tif vem_charge_peak > 800 or len(all_local_max) == 1:\n\t\t\t\tvem_charge_peak = vem_charge_peak_old\n\t\t\tplt.vlines(vem_charge_peak,plt.ylim()[0],plt.ylim()[1])\n\t\t\tplt.plot(xgrid,pdf)\n\t\t\tplt.xlim(xmin=0.,xmax=1300) #No need to go beyond 500 for current HV\n\t\t\tplt.title('A30 Charge')\n\t\t\tplt.tight_layout()\n\t\t\tplt.savefig(nglob_dir+'calib_histogram_%s.png' %m[:-4])\n\t\t\tplt.close('all')\n\t\t\tdata = np.loadtxt(fout,usecols=(4,),skiprows=3)\n\t\t\tadc = data - bl_evt\n\t\t\tymax = adc.argmax()\n\t\t\tsignal = np.sum(adc[ymax-40:ymax+50]) / (vem_charge_peak / 30)\n\t\t\tadc = adc / vem_charge_peak * (vem_pulse_peak+1)\n\t\t\tx = np.arange(1024)\n\t\t\tplt.step(x,adc)\n\t\t\tplt.xlim(ymax-40,ymax+50)\n\t\t\tplt.xlabel('Time [10 ns]')\n\t\t\tplt.ylabel('Signal [VEM Peak]')\n\t\t\tplt.title('Signal: %.3f VEM' %signal)\n\t\t\tplt.savefig(nglob_dir + '%s_trace.png' %m[:-4])\n\t\t\tplt.close('all')\n\t\t\tlocindex = m.split('_')[0]\n\t\t\tnp.savetxt(nglob_dir+'%s_pulse_height_hist.txt' %m[:-4],vem_peak)\n\t\t\tnp.savetxt(nglob_dir+'%s_charge_hist.txt' %m[:-4],vem_charge)\n\t\t\twith open(nglob_dir + 'signal.txt','a') as f:\n\t\t\t\tf.write('%s %s %.3f %.3f %.3f\\n' %(locindex,gps_ts,signal,vem_charge_peak,vem_pulse_peak))\n\t\t\twith open('north_global_signal.txt','a') as f:\n\t\t\t\tf.write('%s %.3f\\n' %(gps_ts,signal))\n\t\t\tvem_charge_peak_old = vem_charge_peak\n\t\t\tvem_pulse_peak_old = vem_pulse_peak"
] |
[
[
"numpy.linspace",
"matplotlib.pyplot.step",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"sklearn.neighbors.KernelDensity",
"numpy.savetxt",
"numpy.sum",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"numpy.loadtxt"
]
] |
brendankeith/PyMFEM
|
[
"5ff7c88cae07ca2a0dfe0b1d4224491c31c8c2ed"
] |
[
"mfem/_par/sparsemat.py"
] |
[
"# This file was automatically generated by SWIG (http://www.swig.org).\n# Version 4.0.2\n#\n# Do not make changes to this file unless you know what you are doing--modify\n# the SWIG interface file instead.\n\nfrom sys import version_info as _swig_python_version_info\nif _swig_python_version_info < (2, 7, 0):\n raise RuntimeError(\"Python 2.7 or later required\")\n\n# Import the low-level C/C++ module\nif __package__ or \".\" in __name__:\n from . import _sparsemat\nelse:\n import _sparsemat\n\ntry:\n import builtins as __builtin__\nexcept ImportError:\n import __builtin__\n\n_swig_new_instance_method = _sparsemat.SWIG_PyInstanceMethod_New\n_swig_new_static_method = _sparsemat.SWIG_PyStaticMethod_New\n\ndef _swig_repr(self):\n try:\n strthis = \"proxy of \" + self.this.__repr__()\n except __builtin__.Exception:\n strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n\ndef _swig_setattr_nondynamic_instance_variable(set):\n def set_instance_attr(self, name, value):\n if name == \"thisown\":\n self.this.own(value)\n elif name == \"this\":\n set(self, name, value)\n elif hasattr(self, name) and isinstance(getattr(type(self), name), property):\n set(self, name, value)\n else:\n raise AttributeError(\"You cannot add instance attributes to %s\" % self)\n return set_instance_attr\n\n\ndef _swig_setattr_nondynamic_class_variable(set):\n def set_class_attr(cls, name, value):\n if hasattr(cls, name) and not isinstance(getattr(cls, name), property):\n set(cls, name, value)\n else:\n raise AttributeError(\"You cannot add class attributes to %s\" % cls)\n return set_class_attr\n\n\ndef _swig_add_metaclass(metaclass):\n \"\"\"Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass\"\"\"\n def wrapper(cls):\n return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())\n return wrapper\n\n\nclass _SwigNonDynamicMeta(type):\n \"\"\"Meta class to enforce nondynamic attributes (no new attributes) for a class\"\"\"\n __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)\n\n\nimport weakref\n\nimport mfem._par.array\nimport mfem._par.mem_manager\nimport mfem._par.vector\nimport mfem._par.operators\nimport mfem._par.matrix\nimport mfem._par.densemat\n\ndef RAP_P(A, R, ORAP):\n r\"\"\"RAP_P(SparseMatrix A, SparseMatrix R, SparseMatrix ORAP) -> SparseMatrix\"\"\"\n return _sparsemat.RAP_P(A, R, ORAP)\nRAP_P = _sparsemat.RAP_P\n\ndef RAP_R(Rt, A, P):\n r\"\"\"RAP_R(SparseMatrix Rt, SparseMatrix A, SparseMatrix P) -> SparseMatrix\"\"\"\n return _sparsemat.RAP_R(Rt, A, P)\nRAP_R = _sparsemat.RAP_R\n\ndef OperatorPtr2SparseMatrix(op):\n r\"\"\"OperatorPtr2SparseMatrix(mfem::OperatorPtr op) -> SparseMatrix\"\"\"\n return _sparsemat.OperatorPtr2SparseMatrix(op)\nOperatorPtr2SparseMatrix = _sparsemat.OperatorPtr2SparseMatrix\n\ndef OperatorHandle2SparseMatrix(op):\n r\"\"\"OperatorHandle2SparseMatrix(mfem::OperatorHandle op) -> SparseMatrix\"\"\"\n return _sparsemat.OperatorHandle2SparseMatrix(op)\nOperatorHandle2SparseMatrix = _sparsemat.OperatorHandle2SparseMatrix\nclass RowNode(object):\n r\"\"\"Proxy of C++ mfem::RowNode class.\"\"\"\n\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc=\"The membership flag\")\n __repr__ = _swig_repr\n Value = property(_sparsemat.RowNode_Value_get, _sparsemat.RowNode_Value_set, doc=r\"\"\"Value : double\"\"\")\n Prev = property(_sparsemat.RowNode_Prev_get, _sparsemat.RowNode_Prev_set, doc=r\"\"\"Prev : p.mfem::RowNode\"\"\")\n Column = property(_sparsemat.RowNode_Column_get, _sparsemat.RowNode_Column_set, doc=r\"\"\"Column : int\"\"\")\n\n def __init__(self):\n r\"\"\"__init__(RowNode self) -> RowNode\"\"\"\n _sparsemat.RowNode_swiginit(self, _sparsemat.new_RowNode())\n __swig_destroy__ = _sparsemat.delete_RowNode\n\n# Register RowNode in _sparsemat:\n_sparsemat.RowNode_swigregister(RowNode)\n\nclass SparseMatrix(mfem._par.matrix.AbstractSparseMatrix):\n r\"\"\"Proxy of C++ mfem::SparseMatrix class.\"\"\"\n\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc=\"The membership flag\")\n __repr__ = _swig_repr\n\n def __init__(self, *args):\n r\"\"\"\n __init__(SparseMatrix self) -> SparseMatrix\n __init__(SparseMatrix self, int nrows, int ncols=-1) -> SparseMatrix\n __init__(SparseMatrix self, int * i) -> SparseMatrix\n __init__(SparseMatrix self, int * i, bool ownij, bool owna, bool issorted) -> SparseMatrix\n __init__(SparseMatrix self, int nrows, int ncols, int rowsize) -> SparseMatrix\n __init__(SparseMatrix self, SparseMatrix mat, bool copy_graph=True) -> SparseMatrix\n __init__(SparseMatrix self, Vector v) -> SparseMatrix\n \"\"\"\n\n import numpy as np \n from scipy.sparse import csr_matrix\n if len(args) == 1 and isinstance(args[0], csr_matrix):\n csr = args[0]\n if np.real(csr).dtype != 'float64':\n csr = csr.astype('float64')\n i = np.ascontiguousarray(csr.indptr)\n j = np.ascontiguousarray(csr.indices)\n data = np.ascontiguousarray(csr.data)\n m, n = csr.shape\n this = _sparsemat.new_SparseMatrix([i, j, data, m, n])\n try:\n self.this.append(this)\n except __builtin__.Exception:\n self.this = this\n _sparsemat.SparseMatrix_SetGraphOwner(self, False)\n _sparsemat.SparseMatrix_SetDataOwner(self, False)\n self._i_data = i\n self._j_data = j\n self._d_data = data\n\n return\n\n\n _sparsemat.SparseMatrix_swiginit(self, _sparsemat.new_SparseMatrix(*args))\n\n def UseCuSparse(self, _useCuSparse=True):\n r\"\"\"UseCuSparse(SparseMatrix self, bool _useCuSparse=True)\"\"\"\n return _sparsemat.SparseMatrix_UseCuSparse(self, _useCuSparse)\n UseCuSparse = _swig_new_instance_method(_sparsemat.SparseMatrix_UseCuSparse)\n\n def MakeRef(self, master):\n r\"\"\"MakeRef(SparseMatrix self, SparseMatrix master)\"\"\"\n return _sparsemat.SparseMatrix_MakeRef(self, master)\n MakeRef = _swig_new_instance_method(_sparsemat.SparseMatrix_MakeRef)\n\n def Size(self):\n r\"\"\"Size(SparseMatrix self) -> int\"\"\"\n return _sparsemat.SparseMatrix_Size(self)\n Size = _swig_new_instance_method(_sparsemat.SparseMatrix_Size)\n\n def Clear(self):\n r\"\"\"Clear(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_Clear(self)\n Clear = _swig_new_instance_method(_sparsemat.SparseMatrix_Clear)\n\n def Empty(self):\n r\"\"\"Empty(SparseMatrix self) -> bool\"\"\"\n return _sparsemat.SparseMatrix_Empty(self)\n Empty = _swig_new_instance_method(_sparsemat.SparseMatrix_Empty)\n\n def GetI(self, *args):\n r\"\"\"\n GetI(SparseMatrix self) -> int\n GetI(SparseMatrix self) -> int const *\n \"\"\"\n return _sparsemat.SparseMatrix_GetI(self, *args)\n GetI = _swig_new_instance_method(_sparsemat.SparseMatrix_GetI)\n\n def GetJ(self, *args):\n r\"\"\"\n GetJ(SparseMatrix self) -> int\n GetJ(SparseMatrix self) -> int const *\n \"\"\"\n return _sparsemat.SparseMatrix_GetJ(self, *args)\n GetJ = _swig_new_instance_method(_sparsemat.SparseMatrix_GetJ)\n\n def GetData(self, *args):\n r\"\"\"\n GetData(SparseMatrix self) -> double\n GetData(SparseMatrix self) -> double const *\n \"\"\"\n return _sparsemat.SparseMatrix_GetData(self, *args)\n GetData = _swig_new_instance_method(_sparsemat.SparseMatrix_GetData)\n\n def GetMemoryI(self, *args):\n r\"\"\"\n GetMemoryI(SparseMatrix self) -> mfem::Memory< int >\n GetMemoryI(SparseMatrix self) -> mfem::Memory< int > const &\n \"\"\"\n return _sparsemat.SparseMatrix_GetMemoryI(self, *args)\n GetMemoryI = _swig_new_instance_method(_sparsemat.SparseMatrix_GetMemoryI)\n\n def ReadI(self, on_dev=True):\n r\"\"\"ReadI(SparseMatrix self, bool on_dev=True) -> int const *\"\"\"\n return _sparsemat.SparseMatrix_ReadI(self, on_dev)\n ReadI = _swig_new_instance_method(_sparsemat.SparseMatrix_ReadI)\n\n def WriteI(self, on_dev=True):\n r\"\"\"WriteI(SparseMatrix self, bool on_dev=True) -> int *\"\"\"\n return _sparsemat.SparseMatrix_WriteI(self, on_dev)\n WriteI = _swig_new_instance_method(_sparsemat.SparseMatrix_WriteI)\n\n def ReadWriteI(self, on_dev=True):\n r\"\"\"ReadWriteI(SparseMatrix self, bool on_dev=True) -> int *\"\"\"\n return _sparsemat.SparseMatrix_ReadWriteI(self, on_dev)\n ReadWriteI = _swig_new_instance_method(_sparsemat.SparseMatrix_ReadWriteI)\n\n def HostReadI(self):\n r\"\"\"HostReadI(SparseMatrix self) -> int const *\"\"\"\n return _sparsemat.SparseMatrix_HostReadI(self)\n HostReadI = _swig_new_instance_method(_sparsemat.SparseMatrix_HostReadI)\n\n def HostWriteI(self):\n r\"\"\"HostWriteI(SparseMatrix self) -> int *\"\"\"\n return _sparsemat.SparseMatrix_HostWriteI(self)\n HostWriteI = _swig_new_instance_method(_sparsemat.SparseMatrix_HostWriteI)\n\n def HostReadWriteI(self):\n r\"\"\"HostReadWriteI(SparseMatrix self) -> int *\"\"\"\n return _sparsemat.SparseMatrix_HostReadWriteI(self)\n HostReadWriteI = _swig_new_instance_method(_sparsemat.SparseMatrix_HostReadWriteI)\n\n def GetMemoryJ(self, *args):\n r\"\"\"\n GetMemoryJ(SparseMatrix self) -> mfem::Memory< int >\n GetMemoryJ(SparseMatrix self) -> mfem::Memory< int > const &\n \"\"\"\n return _sparsemat.SparseMatrix_GetMemoryJ(self, *args)\n GetMemoryJ = _swig_new_instance_method(_sparsemat.SparseMatrix_GetMemoryJ)\n\n def ReadJ(self, on_dev=True):\n r\"\"\"ReadJ(SparseMatrix self, bool on_dev=True) -> int const *\"\"\"\n return _sparsemat.SparseMatrix_ReadJ(self, on_dev)\n ReadJ = _swig_new_instance_method(_sparsemat.SparseMatrix_ReadJ)\n\n def WriteJ(self, on_dev=True):\n r\"\"\"WriteJ(SparseMatrix self, bool on_dev=True) -> int *\"\"\"\n return _sparsemat.SparseMatrix_WriteJ(self, on_dev)\n WriteJ = _swig_new_instance_method(_sparsemat.SparseMatrix_WriteJ)\n\n def ReadWriteJ(self, on_dev=True):\n r\"\"\"ReadWriteJ(SparseMatrix self, bool on_dev=True) -> int *\"\"\"\n return _sparsemat.SparseMatrix_ReadWriteJ(self, on_dev)\n ReadWriteJ = _swig_new_instance_method(_sparsemat.SparseMatrix_ReadWriteJ)\n\n def HostReadJ(self):\n r\"\"\"HostReadJ(SparseMatrix self) -> int const *\"\"\"\n return _sparsemat.SparseMatrix_HostReadJ(self)\n HostReadJ = _swig_new_instance_method(_sparsemat.SparseMatrix_HostReadJ)\n\n def HostWriteJ(self):\n r\"\"\"HostWriteJ(SparseMatrix self) -> int *\"\"\"\n return _sparsemat.SparseMatrix_HostWriteJ(self)\n HostWriteJ = _swig_new_instance_method(_sparsemat.SparseMatrix_HostWriteJ)\n\n def HostReadWriteJ(self):\n r\"\"\"HostReadWriteJ(SparseMatrix self) -> int *\"\"\"\n return _sparsemat.SparseMatrix_HostReadWriteJ(self)\n HostReadWriteJ = _swig_new_instance_method(_sparsemat.SparseMatrix_HostReadWriteJ)\n\n def GetMemoryData(self, *args):\n r\"\"\"\n GetMemoryData(SparseMatrix self) -> mfem::Memory< double >\n GetMemoryData(SparseMatrix self) -> mfem::Memory< double > const &\n \"\"\"\n return _sparsemat.SparseMatrix_GetMemoryData(self, *args)\n GetMemoryData = _swig_new_instance_method(_sparsemat.SparseMatrix_GetMemoryData)\n\n def ReadData(self, on_dev=True):\n r\"\"\"ReadData(SparseMatrix self, bool on_dev=True) -> double const *\"\"\"\n return _sparsemat.SparseMatrix_ReadData(self, on_dev)\n ReadData = _swig_new_instance_method(_sparsemat.SparseMatrix_ReadData)\n\n def WriteData(self, on_dev=True):\n r\"\"\"WriteData(SparseMatrix self, bool on_dev=True) -> double *\"\"\"\n return _sparsemat.SparseMatrix_WriteData(self, on_dev)\n WriteData = _swig_new_instance_method(_sparsemat.SparseMatrix_WriteData)\n\n def ReadWriteData(self, on_dev=True):\n r\"\"\"ReadWriteData(SparseMatrix self, bool on_dev=True) -> double *\"\"\"\n return _sparsemat.SparseMatrix_ReadWriteData(self, on_dev)\n ReadWriteData = _swig_new_instance_method(_sparsemat.SparseMatrix_ReadWriteData)\n\n def HostReadData(self):\n r\"\"\"HostReadData(SparseMatrix self) -> double const *\"\"\"\n return _sparsemat.SparseMatrix_HostReadData(self)\n HostReadData = _swig_new_instance_method(_sparsemat.SparseMatrix_HostReadData)\n\n def HostWriteData(self):\n r\"\"\"HostWriteData(SparseMatrix self) -> double *\"\"\"\n return _sparsemat.SparseMatrix_HostWriteData(self)\n HostWriteData = _swig_new_instance_method(_sparsemat.SparseMatrix_HostWriteData)\n\n def HostReadWriteData(self):\n r\"\"\"HostReadWriteData(SparseMatrix self) -> double *\"\"\"\n return _sparsemat.SparseMatrix_HostReadWriteData(self)\n HostReadWriteData = _swig_new_instance_method(_sparsemat.SparseMatrix_HostReadWriteData)\n\n def RowSize(self, i):\n r\"\"\"RowSize(SparseMatrix self, int const i) -> int\"\"\"\n return _sparsemat.SparseMatrix_RowSize(self, i)\n RowSize = _swig_new_instance_method(_sparsemat.SparseMatrix_RowSize)\n\n def MaxRowSize(self):\n r\"\"\"MaxRowSize(SparseMatrix self) -> int\"\"\"\n return _sparsemat.SparseMatrix_MaxRowSize(self)\n MaxRowSize = _swig_new_instance_method(_sparsemat.SparseMatrix_MaxRowSize)\n\n def GetRowColumns(self, *args):\n r\"\"\"\n GetRowColumns(SparseMatrix self, int const row) -> int\n GetRowColumns(SparseMatrix self, int const row) -> int const *\n \"\"\"\n return _sparsemat.SparseMatrix_GetRowColumns(self, *args)\n GetRowColumns = _swig_new_instance_method(_sparsemat.SparseMatrix_GetRowColumns)\n\n def GetRowEntries(self, *args):\n r\"\"\"\n GetRowEntries(SparseMatrix self, int const row) -> double\n GetRowEntries(SparseMatrix self, int const row) -> double const *\n \"\"\"\n return _sparsemat.SparseMatrix_GetRowEntries(self, *args)\n GetRowEntries = _swig_new_instance_method(_sparsemat.SparseMatrix_GetRowEntries)\n\n def SetWidth(self, width_=-1):\n r\"\"\"SetWidth(SparseMatrix self, int width_=-1)\"\"\"\n return _sparsemat.SparseMatrix_SetWidth(self, width_)\n SetWidth = _swig_new_instance_method(_sparsemat.SparseMatrix_SetWidth)\n\n def ActualWidth(self):\n r\"\"\"ActualWidth(SparseMatrix self) -> int\"\"\"\n return _sparsemat.SparseMatrix_ActualWidth(self)\n ActualWidth = _swig_new_instance_method(_sparsemat.SparseMatrix_ActualWidth)\n\n def SortColumnIndices(self):\n r\"\"\"SortColumnIndices(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_SortColumnIndices(self)\n SortColumnIndices = _swig_new_instance_method(_sparsemat.SparseMatrix_SortColumnIndices)\n\n def MoveDiagonalFirst(self):\n r\"\"\"MoveDiagonalFirst(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_MoveDiagonalFirst(self)\n MoveDiagonalFirst = _swig_new_instance_method(_sparsemat.SparseMatrix_MoveDiagonalFirst)\n\n def Elem(self, *args):\n r\"\"\"\n Elem(SparseMatrix self, int i, int j) -> double\n Elem(SparseMatrix self, int i, int j) -> double const &\n \"\"\"\n return _sparsemat.SparseMatrix_Elem(self, *args)\n Elem = _swig_new_instance_method(_sparsemat.SparseMatrix_Elem)\n\n def __call__(self, *args):\n r\"\"\"\n __call__(SparseMatrix self, int i, int j) -> double\n __call__(SparseMatrix self, int i, int j) -> double const &\n \"\"\"\n return _sparsemat.SparseMatrix___call__(self, *args)\n __call__ = _swig_new_instance_method(_sparsemat.SparseMatrix___call__)\n\n def GetDiag(self, d):\n r\"\"\"GetDiag(SparseMatrix self, Vector d)\"\"\"\n return _sparsemat.SparseMatrix_GetDiag(self, d)\n GetDiag = _swig_new_instance_method(_sparsemat.SparseMatrix_GetDiag)\n\n def ToDenseMatrix(self, *args):\n r\"\"\"\n ToDenseMatrix(SparseMatrix self) -> DenseMatrix\n ToDenseMatrix(SparseMatrix self, DenseMatrix B)\n \"\"\"\n return _sparsemat.SparseMatrix_ToDenseMatrix(self, *args)\n ToDenseMatrix = _swig_new_instance_method(_sparsemat.SparseMatrix_ToDenseMatrix)\n\n def GetMemoryClass(self):\n r\"\"\"GetMemoryClass(SparseMatrix self) -> mfem::MemoryClass\"\"\"\n return _sparsemat.SparseMatrix_GetMemoryClass(self)\n GetMemoryClass = _swig_new_instance_method(_sparsemat.SparseMatrix_GetMemoryClass)\n\n def Mult(self, x, y):\n r\"\"\"Mult(SparseMatrix self, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_Mult(self, x, y)\n Mult = _swig_new_instance_method(_sparsemat.SparseMatrix_Mult)\n\n def AddMult(self, x, y, a=1.0):\n r\"\"\"AddMult(SparseMatrix self, Vector x, Vector y, double const a=1.0)\"\"\"\n return _sparsemat.SparseMatrix_AddMult(self, x, y, a)\n AddMult = _swig_new_instance_method(_sparsemat.SparseMatrix_AddMult)\n\n def MultTranspose(self, x, y):\n r\"\"\"MultTranspose(SparseMatrix self, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_MultTranspose(self, x, y)\n MultTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_MultTranspose)\n\n def AddMultTranspose(self, x, y, a=1.0):\n r\"\"\"AddMultTranspose(SparseMatrix self, Vector x, Vector y, double const a=1.0)\"\"\"\n return _sparsemat.SparseMatrix_AddMultTranspose(self, x, y, a)\n AddMultTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_AddMultTranspose)\n\n def BuildTranspose(self):\n r\"\"\"BuildTranspose(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_BuildTranspose(self)\n BuildTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_BuildTranspose)\n\n def ResetTranspose(self):\n r\"\"\"ResetTranspose(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_ResetTranspose(self)\n ResetTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_ResetTranspose)\n\n def PartMult(self, rows, x, y):\n r\"\"\"PartMult(SparseMatrix self, intArray rows, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_PartMult(self, rows, x, y)\n PartMult = _swig_new_instance_method(_sparsemat.SparseMatrix_PartMult)\n\n def PartAddMult(self, rows, x, y, a=1.0):\n r\"\"\"PartAddMult(SparseMatrix self, intArray rows, Vector x, Vector y, double const a=1.0)\"\"\"\n return _sparsemat.SparseMatrix_PartAddMult(self, rows, x, y, a)\n PartAddMult = _swig_new_instance_method(_sparsemat.SparseMatrix_PartAddMult)\n\n def BooleanMult(self, x, y):\n r\"\"\"BooleanMult(SparseMatrix self, intArray x, intArray y)\"\"\"\n return _sparsemat.SparseMatrix_BooleanMult(self, x, y)\n BooleanMult = _swig_new_instance_method(_sparsemat.SparseMatrix_BooleanMult)\n\n def BooleanMultTranspose(self, x, y):\n r\"\"\"BooleanMultTranspose(SparseMatrix self, intArray x, intArray y)\"\"\"\n return _sparsemat.SparseMatrix_BooleanMultTranspose(self, x, y)\n BooleanMultTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_BooleanMultTranspose)\n\n def AbsMult(self, x, y):\n r\"\"\"AbsMult(SparseMatrix self, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_AbsMult(self, x, y)\n AbsMult = _swig_new_instance_method(_sparsemat.SparseMatrix_AbsMult)\n\n def AbsMultTranspose(self, x, y):\n r\"\"\"AbsMultTranspose(SparseMatrix self, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_AbsMultTranspose(self, x, y)\n AbsMultTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_AbsMultTranspose)\n\n def InnerProduct(self, x, y):\n r\"\"\"InnerProduct(SparseMatrix self, Vector x, Vector y) -> double\"\"\"\n return _sparsemat.SparseMatrix_InnerProduct(self, x, y)\n InnerProduct = _swig_new_instance_method(_sparsemat.SparseMatrix_InnerProduct)\n\n def GetRowSums(self, x):\n r\"\"\"GetRowSums(SparseMatrix self, Vector x)\"\"\"\n return _sparsemat.SparseMatrix_GetRowSums(self, x)\n GetRowSums = _swig_new_instance_method(_sparsemat.SparseMatrix_GetRowSums)\n\n def GetRowNorml1(self, irow):\n r\"\"\"GetRowNorml1(SparseMatrix self, int irow) -> double\"\"\"\n return _sparsemat.SparseMatrix_GetRowNorml1(self, irow)\n GetRowNorml1 = _swig_new_instance_method(_sparsemat.SparseMatrix_GetRowNorml1)\n\n def Inverse(self):\n r\"\"\"Inverse(SparseMatrix self) -> MatrixInverse\"\"\"\n return _sparsemat.SparseMatrix_Inverse(self)\n Inverse = _swig_new_instance_method(_sparsemat.SparseMatrix_Inverse)\n\n def EliminateRow(self, *args):\n r\"\"\"\n EliminateRow(SparseMatrix self, int row, double const sol, Vector rhs)\n EliminateRow(SparseMatrix self, int row, mfem::Operator::DiagonalPolicy dpolicy=DIAG_ZERO)\n \"\"\"\n return _sparsemat.SparseMatrix_EliminateRow(self, *args)\n EliminateRow = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateRow)\n\n def EliminateCol(self, *args, **kwargs):\n r\"\"\"EliminateCol(SparseMatrix self, int col, mfem::Operator::DiagonalPolicy dpolicy=DIAG_ZERO)\"\"\"\n return _sparsemat.SparseMatrix_EliminateCol(self, *args, **kwargs)\n EliminateCol = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateCol)\n\n def EliminateCols(self, *args):\n r\"\"\"\n EliminateCols(SparseMatrix self, intArray cols, Vector x=None, Vector b=None)\n EliminateCols(SparseMatrix self, intArray col_marker, SparseMatrix Ae)\n \"\"\"\n return _sparsemat.SparseMatrix_EliminateCols(self, *args)\n EliminateCols = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateCols)\n\n def EliminateRowColMultipleRHS(self, *args, **kwargs):\n r\"\"\"EliminateRowColMultipleRHS(SparseMatrix self, int rc, Vector sol, DenseMatrix rhs, mfem::Operator::DiagonalPolicy dpolicy=DIAG_ONE)\"\"\"\n return _sparsemat.SparseMatrix_EliminateRowColMultipleRHS(self, *args, **kwargs)\n EliminateRowColMultipleRHS = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateRowColMultipleRHS)\n\n def EliminateRowColDiag(self, rc, value):\n r\"\"\"EliminateRowColDiag(SparseMatrix self, int rc, double value)\"\"\"\n return _sparsemat.SparseMatrix_EliminateRowColDiag(self, rc, value)\n EliminateRowColDiag = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateRowColDiag)\n\n def EliminateRowCol(self, *args):\n r\"\"\"\n EliminateRowCol(SparseMatrix self, int rc, double const sol, Vector rhs, mfem::Operator::DiagonalPolicy dpolicy=DIAG_ONE)\n EliminateRowCol(SparseMatrix self, int rc, mfem::Operator::DiagonalPolicy dpolicy=DIAG_ONE)\n EliminateRowCol(SparseMatrix self, int rc, SparseMatrix Ae, mfem::Operator::DiagonalPolicy dpolicy=DIAG_ONE)\n \"\"\"\n return _sparsemat.SparseMatrix_EliminateRowCol(self, *args)\n EliminateRowCol = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateRowCol)\n\n def SetDiagIdentity(self):\n r\"\"\"SetDiagIdentity(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_SetDiagIdentity(self)\n SetDiagIdentity = _swig_new_instance_method(_sparsemat.SparseMatrix_SetDiagIdentity)\n\n def EliminateZeroRows(self, threshold=1e-12):\n r\"\"\"EliminateZeroRows(SparseMatrix self, double const threshold=1e-12)\"\"\"\n return _sparsemat.SparseMatrix_EliminateZeroRows(self, threshold)\n EliminateZeroRows = _swig_new_instance_method(_sparsemat.SparseMatrix_EliminateZeroRows)\n\n def Gauss_Seidel_forw(self, x, y):\n r\"\"\"Gauss_Seidel_forw(SparseMatrix self, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_Gauss_Seidel_forw(self, x, y)\n Gauss_Seidel_forw = _swig_new_instance_method(_sparsemat.SparseMatrix_Gauss_Seidel_forw)\n\n def Gauss_Seidel_back(self, x, y):\n r\"\"\"Gauss_Seidel_back(SparseMatrix self, Vector x, Vector y)\"\"\"\n return _sparsemat.SparseMatrix_Gauss_Seidel_back(self, x, y)\n Gauss_Seidel_back = _swig_new_instance_method(_sparsemat.SparseMatrix_Gauss_Seidel_back)\n\n def GetJacobiScaling(self):\n r\"\"\"GetJacobiScaling(SparseMatrix self) -> double\"\"\"\n return _sparsemat.SparseMatrix_GetJacobiScaling(self)\n GetJacobiScaling = _swig_new_instance_method(_sparsemat.SparseMatrix_GetJacobiScaling)\n\n def Jacobi(self, b, x0, x1, sc):\n r\"\"\"Jacobi(SparseMatrix self, Vector b, Vector x0, Vector x1, double sc)\"\"\"\n return _sparsemat.SparseMatrix_Jacobi(self, b, x0, x1, sc)\n Jacobi = _swig_new_instance_method(_sparsemat.SparseMatrix_Jacobi)\n\n def DiagScale(self, b, x, sc=1.0):\n r\"\"\"DiagScale(SparseMatrix self, Vector b, Vector x, double sc=1.0)\"\"\"\n return _sparsemat.SparseMatrix_DiagScale(self, b, x, sc)\n DiagScale = _swig_new_instance_method(_sparsemat.SparseMatrix_DiagScale)\n\n def Jacobi2(self, b, x0, x1, sc=1.0):\n r\"\"\"Jacobi2(SparseMatrix self, Vector b, Vector x0, Vector x1, double sc=1.0)\"\"\"\n return _sparsemat.SparseMatrix_Jacobi2(self, b, x0, x1, sc)\n Jacobi2 = _swig_new_instance_method(_sparsemat.SparseMatrix_Jacobi2)\n\n def Jacobi3(self, b, x0, x1, sc=1.0):\n r\"\"\"Jacobi3(SparseMatrix self, Vector b, Vector x0, Vector x1, double sc=1.0)\"\"\"\n return _sparsemat.SparseMatrix_Jacobi3(self, b, x0, x1, sc)\n Jacobi3 = _swig_new_instance_method(_sparsemat.SparseMatrix_Jacobi3)\n\n def Finalize(self, *args):\n r\"\"\"\n Finalize(SparseMatrix self, int skip_zeros=1)\n Finalize(SparseMatrix self, int skip_zeros, bool fix_empty_rows)\n \"\"\"\n return _sparsemat.SparseMatrix_Finalize(self, *args)\n Finalize = _swig_new_instance_method(_sparsemat.SparseMatrix_Finalize)\n\n def Finalized(self):\n r\"\"\"Finalized(SparseMatrix self) -> bool\"\"\"\n return _sparsemat.SparseMatrix_Finalized(self)\n Finalized = _swig_new_instance_method(_sparsemat.SparseMatrix_Finalized)\n\n def ColumnsAreSorted(self):\n r\"\"\"ColumnsAreSorted(SparseMatrix self) -> bool\"\"\"\n return _sparsemat.SparseMatrix_ColumnsAreSorted(self)\n ColumnsAreSorted = _swig_new_instance_method(_sparsemat.SparseMatrix_ColumnsAreSorted)\n\n def Threshold(self, tol, fix_empty_rows=False):\n r\"\"\"Threshold(SparseMatrix self, double tol, bool fix_empty_rows=False)\"\"\"\n return _sparsemat.SparseMatrix_Threshold(self, tol, fix_empty_rows)\n Threshold = _swig_new_instance_method(_sparsemat.SparseMatrix_Threshold)\n\n def GetBlocks(self, blocks):\n r\"\"\"GetBlocks(SparseMatrix self, mfem::Array2D< mfem::SparseMatrix * > & blocks)\"\"\"\n return _sparsemat.SparseMatrix_GetBlocks(self, blocks)\n GetBlocks = _swig_new_instance_method(_sparsemat.SparseMatrix_GetBlocks)\n\n def GetSubMatrix(self, rows, cols, subm):\n r\"\"\"GetSubMatrix(SparseMatrix self, intArray rows, intArray cols, DenseMatrix subm)\"\"\"\n return _sparsemat.SparseMatrix_GetSubMatrix(self, rows, cols, subm)\n GetSubMatrix = _swig_new_instance_method(_sparsemat.SparseMatrix_GetSubMatrix)\n\n def SetColPtr(self, row):\n r\"\"\"SetColPtr(SparseMatrix self, int const row)\"\"\"\n return _sparsemat.SparseMatrix_SetColPtr(self, row)\n SetColPtr = _swig_new_instance_method(_sparsemat.SparseMatrix_SetColPtr)\n\n def ClearColPtr(self):\n r\"\"\"ClearColPtr(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_ClearColPtr(self)\n ClearColPtr = _swig_new_instance_method(_sparsemat.SparseMatrix_ClearColPtr)\n\n def _Get_(self, col):\n r\"\"\"_Get_(SparseMatrix self, int const col) -> double\"\"\"\n return _sparsemat.SparseMatrix__Get_(self, col)\n _Get_ = _swig_new_instance_method(_sparsemat.SparseMatrix__Get_)\n\n def SearchRow(self, *args):\n r\"\"\"\n SearchRow(SparseMatrix self, int const col) -> double\n SearchRow(SparseMatrix self, int const row, int const col) -> double &\n \"\"\"\n return _sparsemat.SparseMatrix_SearchRow(self, *args)\n SearchRow = _swig_new_instance_method(_sparsemat.SparseMatrix_SearchRow)\n\n def _Add_(self, *args):\n r\"\"\"\n _Add_(SparseMatrix self, int const col, double const a)\n _Add_(SparseMatrix self, int const row, int const col, double const a)\n \"\"\"\n return _sparsemat.SparseMatrix__Add_(self, *args)\n _Add_ = _swig_new_instance_method(_sparsemat.SparseMatrix__Add_)\n\n def _Set_(self, *args):\n r\"\"\"\n _Set_(SparseMatrix self, int const col, double const a)\n _Set_(SparseMatrix self, int const row, int const col, double const a)\n \"\"\"\n return _sparsemat.SparseMatrix__Set_(self, *args)\n _Set_ = _swig_new_instance_method(_sparsemat.SparseMatrix__Set_)\n\n def Set(self, i, j, a):\n r\"\"\"Set(SparseMatrix self, int const i, int const j, double const a)\"\"\"\n return _sparsemat.SparseMatrix_Set(self, i, j, a)\n Set = _swig_new_instance_method(_sparsemat.SparseMatrix_Set)\n\n def SetSubMatrix(self, rows, cols, subm, skip_zeros=1):\n r\"\"\"SetSubMatrix(SparseMatrix self, intArray rows, intArray cols, DenseMatrix subm, int skip_zeros=1)\"\"\"\n return _sparsemat.SparseMatrix_SetSubMatrix(self, rows, cols, subm, skip_zeros)\n SetSubMatrix = _swig_new_instance_method(_sparsemat.SparseMatrix_SetSubMatrix)\n\n def SetSubMatrixTranspose(self, rows, cols, subm, skip_zeros=1):\n r\"\"\"SetSubMatrixTranspose(SparseMatrix self, intArray rows, intArray cols, DenseMatrix subm, int skip_zeros=1)\"\"\"\n return _sparsemat.SparseMatrix_SetSubMatrixTranspose(self, rows, cols, subm, skip_zeros)\n SetSubMatrixTranspose = _swig_new_instance_method(_sparsemat.SparseMatrix_SetSubMatrixTranspose)\n\n def AddSubMatrix(self, rows, cols, subm, skip_zeros=1):\n r\"\"\"AddSubMatrix(SparseMatrix self, intArray rows, intArray cols, DenseMatrix subm, int skip_zeros=1)\"\"\"\n return _sparsemat.SparseMatrix_AddSubMatrix(self, rows, cols, subm, skip_zeros)\n AddSubMatrix = _swig_new_instance_method(_sparsemat.SparseMatrix_AddSubMatrix)\n\n def RowIsEmpty(self, row):\n r\"\"\"RowIsEmpty(SparseMatrix self, int const row) -> bool\"\"\"\n return _sparsemat.SparseMatrix_RowIsEmpty(self, row)\n RowIsEmpty = _swig_new_instance_method(_sparsemat.SparseMatrix_RowIsEmpty)\n\n def GetRow(self, row, cols, srow):\n r\"\"\"GetRow(SparseMatrix self, int const row, intArray cols, Vector srow) -> int\"\"\"\n return _sparsemat.SparseMatrix_GetRow(self, row, cols, srow)\n GetRow = _swig_new_instance_method(_sparsemat.SparseMatrix_GetRow)\n\n def SetRow(self, row, cols, srow):\n r\"\"\"SetRow(SparseMatrix self, int const row, intArray cols, Vector srow)\"\"\"\n return _sparsemat.SparseMatrix_SetRow(self, row, cols, srow)\n SetRow = _swig_new_instance_method(_sparsemat.SparseMatrix_SetRow)\n\n def AddRow(self, row, cols, srow):\n r\"\"\"AddRow(SparseMatrix self, int const row, intArray cols, Vector srow)\"\"\"\n return _sparsemat.SparseMatrix_AddRow(self, row, cols, srow)\n AddRow = _swig_new_instance_method(_sparsemat.SparseMatrix_AddRow)\n\n def ScaleRow(self, row, scale):\n r\"\"\"ScaleRow(SparseMatrix self, int const row, double const scale)\"\"\"\n return _sparsemat.SparseMatrix_ScaleRow(self, row, scale)\n ScaleRow = _swig_new_instance_method(_sparsemat.SparseMatrix_ScaleRow)\n\n def ScaleRows(self, sl):\n r\"\"\"ScaleRows(SparseMatrix self, Vector sl)\"\"\"\n return _sparsemat.SparseMatrix_ScaleRows(self, sl)\n ScaleRows = _swig_new_instance_method(_sparsemat.SparseMatrix_ScaleRows)\n\n def ScaleColumns(self, sr):\n r\"\"\"ScaleColumns(SparseMatrix self, Vector sr)\"\"\"\n return _sparsemat.SparseMatrix_ScaleColumns(self, sr)\n ScaleColumns = _swig_new_instance_method(_sparsemat.SparseMatrix_ScaleColumns)\n\n def __iadd__(self, B):\n r\"\"\"__iadd__(SparseMatrix self, SparseMatrix B) -> SparseMatrix\"\"\"\n val = _sparsemat.SparseMatrix___iadd__(self, B)\n\n val.thisown = 0 \n return self\n\n\n return val\n\n\n def Add(self, *args):\n r\"\"\"\n Add(SparseMatrix self, int const i, int const j, double const a)\n Add(SparseMatrix self, double const a, SparseMatrix B)\n \"\"\"\n return _sparsemat.SparseMatrix_Add(self, *args)\n Add = _swig_new_instance_method(_sparsemat.SparseMatrix_Add)\n\n def __imul__(self, a):\n r\"\"\"__imul__(SparseMatrix self, double a) -> SparseMatrix\"\"\"\n val = _sparsemat.SparseMatrix___imul__(self, a)\n\n val.thisown = 0\n return self\n\n\n return val\n\n\n def IsSymmetric(self):\n r\"\"\"IsSymmetric(SparseMatrix self) -> double\"\"\"\n return _sparsemat.SparseMatrix_IsSymmetric(self)\n IsSymmetric = _swig_new_instance_method(_sparsemat.SparseMatrix_IsSymmetric)\n\n def Symmetrize(self):\n r\"\"\"Symmetrize(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_Symmetrize(self)\n Symmetrize = _swig_new_instance_method(_sparsemat.SparseMatrix_Symmetrize)\n\n def NumNonZeroElems(self):\n r\"\"\"NumNonZeroElems(SparseMatrix self) -> int\"\"\"\n return _sparsemat.SparseMatrix_NumNonZeroElems(self)\n NumNonZeroElems = _swig_new_instance_method(_sparsemat.SparseMatrix_NumNonZeroElems)\n\n def MaxNorm(self):\n r\"\"\"MaxNorm(SparseMatrix self) -> double\"\"\"\n return _sparsemat.SparseMatrix_MaxNorm(self)\n MaxNorm = _swig_new_instance_method(_sparsemat.SparseMatrix_MaxNorm)\n\n def CountSmallElems(self, tol):\n r\"\"\"CountSmallElems(SparseMatrix self, double tol) -> int\"\"\"\n return _sparsemat.SparseMatrix_CountSmallElems(self, tol)\n CountSmallElems = _swig_new_instance_method(_sparsemat.SparseMatrix_CountSmallElems)\n\n def CheckFinite(self):\n r\"\"\"CheckFinite(SparseMatrix self) -> int\"\"\"\n return _sparsemat.SparseMatrix_CheckFinite(self)\n CheckFinite = _swig_new_instance_method(_sparsemat.SparseMatrix_CheckFinite)\n\n def SetGraphOwner(self, ownij):\n r\"\"\"SetGraphOwner(SparseMatrix self, bool ownij)\"\"\"\n return _sparsemat.SparseMatrix_SetGraphOwner(self, ownij)\n SetGraphOwner = _swig_new_instance_method(_sparsemat.SparseMatrix_SetGraphOwner)\n\n def SetDataOwner(self, owna):\n r\"\"\"SetDataOwner(SparseMatrix self, bool owna)\"\"\"\n return _sparsemat.SparseMatrix_SetDataOwner(self, owna)\n SetDataOwner = _swig_new_instance_method(_sparsemat.SparseMatrix_SetDataOwner)\n\n def OwnsGraph(self):\n r\"\"\"OwnsGraph(SparseMatrix self) -> bool\"\"\"\n return _sparsemat.SparseMatrix_OwnsGraph(self)\n OwnsGraph = _swig_new_instance_method(_sparsemat.SparseMatrix_OwnsGraph)\n\n def OwnsData(self):\n r\"\"\"OwnsData(SparseMatrix self) -> bool\"\"\"\n return _sparsemat.SparseMatrix_OwnsData(self)\n OwnsData = _swig_new_instance_method(_sparsemat.SparseMatrix_OwnsData)\n\n def LoseData(self):\n r\"\"\"LoseData(SparseMatrix self)\"\"\"\n return _sparsemat.SparseMatrix_LoseData(self)\n LoseData = _swig_new_instance_method(_sparsemat.SparseMatrix_LoseData)\n\n def Swap(self, other):\n r\"\"\"Swap(SparseMatrix self, SparseMatrix other)\"\"\"\n return _sparsemat.SparseMatrix_Swap(self, other)\n Swap = _swig_new_instance_method(_sparsemat.SparseMatrix_Swap)\n __swig_destroy__ = _sparsemat.delete_SparseMatrix\n\n def GetType(self):\n r\"\"\"GetType(SparseMatrix self) -> mfem::Operator::Type\"\"\"\n return _sparsemat.SparseMatrix_GetType(self)\n GetType = _swig_new_instance_method(_sparsemat.SparseMatrix_GetType)\n\n def GetIArray(self):\n r\"\"\"GetIArray(SparseMatrix self) -> PyObject *\"\"\"\n return _sparsemat.SparseMatrix_GetIArray(self)\n GetIArray = _swig_new_instance_method(_sparsemat.SparseMatrix_GetIArray)\n\n def GetJArray(self):\n r\"\"\"GetJArray(SparseMatrix self) -> PyObject *\"\"\"\n return _sparsemat.SparseMatrix_GetJArray(self)\n GetJArray = _swig_new_instance_method(_sparsemat.SparseMatrix_GetJArray)\n\n def GetDataArray(self):\n r\"\"\"GetDataArray(SparseMatrix self) -> PyObject *\"\"\"\n return _sparsemat.SparseMatrix_GetDataArray(self)\n GetDataArray = _swig_new_instance_method(_sparsemat.SparseMatrix_GetDataArray)\n\n def Print(self, *args):\n r\"\"\"\n Print(SparseMatrix self, std::ostream & out=mfem::out, int width_=4)\n Print(SparseMatrix self, char const * file, int precision=8)\n \"\"\"\n return _sparsemat.SparseMatrix_Print(self, *args)\n Print = _swig_new_instance_method(_sparsemat.SparseMatrix_Print)\n\n def PrintGZ(self, file, precision=8):\n r\"\"\"PrintGZ(SparseMatrix self, char const * file, int precision=8)\"\"\"\n return _sparsemat.SparseMatrix_PrintGZ(self, file, precision)\n PrintGZ = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintGZ)\n\n def PrintMatlab(self, *args):\n r\"\"\"\n PrintMatlab(SparseMatrix self, std::ostream & out=mfem::out)\n PrintMatlab(SparseMatrix self, char const * file, int precision=8)\n \"\"\"\n return _sparsemat.SparseMatrix_PrintMatlab(self, *args)\n PrintMatlab = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintMatlab)\n\n def PrintMatlabGZ(self, file, precision=8):\n r\"\"\"PrintMatlabGZ(SparseMatrix self, char const * file, int precision=8)\"\"\"\n return _sparsemat.SparseMatrix_PrintMatlabGZ(self, file, precision)\n PrintMatlabGZ = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintMatlabGZ)\n\n def PrintMM(self, *args):\n r\"\"\"\n PrintMM(SparseMatrix self, std::ostream & out=mfem::out)\n PrintMM(SparseMatrix self, char const * file, int precision=8)\n \"\"\"\n return _sparsemat.SparseMatrix_PrintMM(self, *args)\n PrintMM = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintMM)\n\n def PrintMMGZ(self, file, precision=8):\n r\"\"\"PrintMMGZ(SparseMatrix self, char const * file, int precision=8)\"\"\"\n return _sparsemat.SparseMatrix_PrintMMGZ(self, file, precision)\n PrintMMGZ = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintMMGZ)\n\n def PrintCSRGZ(self, file, precision=8):\n r\"\"\"PrintCSRGZ(SparseMatrix self, char const * file, int precision=8)\"\"\"\n return _sparsemat.SparseMatrix_PrintCSRGZ(self, file, precision)\n PrintCSRGZ = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintCSRGZ)\n\n def PrintCSR(self, *args):\n r\"\"\"\n PrintCSR(SparseMatrix self, std::ostream & out)\n PrintCSR(SparseMatrix self, char const * file, int precision=8)\n PrintCSR(SparseMatrix self)\n \"\"\"\n return _sparsemat.SparseMatrix_PrintCSR(self, *args)\n PrintCSR = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintCSR)\n\n def PrintCSR2GZ(self, file, precision=8):\n r\"\"\"PrintCSR2GZ(SparseMatrix self, char const * file, int precision=8)\"\"\"\n return _sparsemat.SparseMatrix_PrintCSR2GZ(self, file, precision)\n PrintCSR2GZ = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintCSR2GZ)\n\n def PrintCSR2(self, *args):\n r\"\"\"\n PrintCSR2(SparseMatrix self, std::ostream & out)\n PrintCSR2(SparseMatrix self, char const * file, int precision=8)\n PrintCSR2(SparseMatrix self)\n \"\"\"\n return _sparsemat.SparseMatrix_PrintCSR2(self, *args)\n PrintCSR2 = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintCSR2)\n\n def PrintInfoGZ(self, file, precision=8):\n r\"\"\"PrintInfoGZ(SparseMatrix self, char const * file, int precision=8)\"\"\"\n return _sparsemat.SparseMatrix_PrintInfoGZ(self, file, precision)\n PrintInfoGZ = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintInfoGZ)\n\n def PrintInfo(self, *args):\n r\"\"\"\n PrintInfo(SparseMatrix self, std::ostream & out)\n PrintInfo(SparseMatrix self, char const * file, int precision=8)\n PrintInfo(SparseMatrix self)\n \"\"\"\n return _sparsemat.SparseMatrix_PrintInfo(self, *args)\n PrintInfo = _swig_new_instance_method(_sparsemat.SparseMatrix_PrintInfo)\n\n# Register SparseMatrix in _sparsemat:\n_sparsemat.SparseMatrix_swigregister(SparseMatrix)\n\n\ndef __lshift__(os, mat):\n r\"\"\"__lshift__(std::ostream & os, SparseMatrix mat) -> std::ostream &\"\"\"\n return _sparsemat.__lshift__(os, mat)\n__lshift__ = _sparsemat.__lshift__\n\ndef SparseMatrixFunction(S, f):\n r\"\"\"SparseMatrixFunction(SparseMatrix S, double (*)(double) f)\"\"\"\n return _sparsemat.SparseMatrixFunction(S, f)\nSparseMatrixFunction = _sparsemat.SparseMatrixFunction\n\ndef TransposeAbstractSparseMatrix(A, useActualWidth):\n r\"\"\"TransposeAbstractSparseMatrix(AbstractSparseMatrix A, int useActualWidth) -> SparseMatrix\"\"\"\n return _sparsemat.TransposeAbstractSparseMatrix(A, useActualWidth)\nTransposeAbstractSparseMatrix = _sparsemat.TransposeAbstractSparseMatrix\n\ndef TransposeMult(A, B):\n r\"\"\"TransposeMult(SparseMatrix A, SparseMatrix B) -> SparseMatrix\"\"\"\n return _sparsemat.TransposeMult(A, B)\nTransposeMult = _sparsemat.TransposeMult\n\ndef MultAbstractSparseMatrix(A, B):\n r\"\"\"MultAbstractSparseMatrix(AbstractSparseMatrix A, AbstractSparseMatrix B) -> SparseMatrix\"\"\"\n return _sparsemat.MultAbstractSparseMatrix(A, B)\nMultAbstractSparseMatrix = _sparsemat.MultAbstractSparseMatrix\n\ndef Mult_AtDA(A, D, OAtDA=None):\n r\"\"\"Mult_AtDA(SparseMatrix A, Vector D, SparseMatrix OAtDA=None) -> SparseMatrix\"\"\"\n return _sparsemat.Mult_AtDA(A, D, OAtDA)\nMult_AtDA = _sparsemat.Mult_AtDA\n\ndef OuterProduct(*args):\n r\"\"\"\n OuterProduct(DenseMatrix A, DenseMatrix B) -> DenseMatrix\n OuterProduct(DenseMatrix A, SparseMatrix B) -> SparseMatrix\n OuterProduct(SparseMatrix A, DenseMatrix B) -> SparseMatrix\n OuterProduct(SparseMatrix A, SparseMatrix B) -> SparseMatrix\n \"\"\"\n return _sparsemat.OuterProduct(*args)\nOuterProduct = _sparsemat.OuterProduct\n\n\n"
] |
[
[
"numpy.ascontiguousarray",
"numpy.real"
]
] |
escherba/ivis
|
[
"bbfd8381c0f40f7219585df851ed9a2f4278bee4"
] |
[
"ivis/data/sequence/image.py"
] |
[
"\"\"\"Custom datasets that load images from disk.\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .sequence import IndexableDataset\n\n\nclass ImageDataset(IndexableDataset):\n \"\"\"When indexed, loads images from disk, resizes to consistent size, then returns image.\n Since the returned images will consist of 3 dimensions, the model ivis uses must be capable\n of dealing with this dimensionality of data (for example, a Convolutional Neural Network).\n Such a model can be constructed externally and then passed to ivis as the argument for 'model'.\n\n :param list filepath_list: All image filepaths in dataset.\n :param tuple img_shape: A tuple (height, width) containing desired dimensions to resize the\n images to.\n :param color_mode str: Either \"rgb\", \"rgba\" or \"grayscale\". Determines how many channels present\n in images that are read in - 3, 4, or 1 respectively.\n :param resize_method str: Interpolation method to use when resizing image. Must be one of:\n \"area\", \"bicubic\", \"bilinear\", \"gaussian\", \"lanczos3\", \"lanczos5\", \"mitchellcubic\", \"nearest\".\n :param preserve_aspect_ratio boolean: Whether to preserve the aspect ratio when resizing images.\n If True, will maintain aspect ratio by padding the image.\n :param dtype tf.dtypes.DType: The dtype to read the image into. One of tf.uint8 or tf.uint16.\n :param preprocessing_function Callable: A function to apply to every image. Will be called\n at the end of the pipeline, after image reading and resizing.\n If None (default), no function will be applied.\"\"\"\n\n shape = None\n def __init__(self, filepath_list, img_shape, color_mode=\"rgb\",\n resize_method=\"bilinear\", preserve_aspect_ratio=False,\n dtype=tf.uint8, preprocessing_function=None):\n self.filepath_list = np.array(filepath_list)\n self.img_shape = img_shape\n if color_mode == \"rgb\":\n self.channels = 3\n elif color_mode == \"rgba\":\n self.channels = 4\n elif color_mode == \"grayscale\":\n self.channels = 1\n else:\n raise ValueError(\"color_mode arg '{}' not recognized.\"\n \" Must be one of 'rgb', 'rgba', 'grayscale.\".format(color_mode))\n self.resize_method = resize_method\n self.preserve_aspect_ratio = preserve_aspect_ratio\n self.dtype = dtype\n self.preprocessing_function = preprocessing_function\n self.shape = (len(filepath_list), *img_shape, self.channels)\n\n def __getitem__(self, idx):\n if isinstance(idx, slice):\n start, stop, step = idx.indices(len(self))\n return [self[i] for i in range(start, stop, step)]\n if idx < 0:\n idx += len(self)\n img = self.read_image(self.filepath_list[idx])\n img = self.resize_image(img)\n if self.preprocessing_function:\n img = self.preprocessing_function(img)\n return img\n\n def __len__(self):\n return len(self.filepath_list)\n\n def read_image(self, filepath):\n \"\"\"Reads an image from disk into a numpy array\"\"\"\n img_bytes = tf.io.read_file(filepath)\n return tf.image.decode_png(img_bytes, channels=self.channels, dtype=self.dtype)\n\n def resize_image(self, img):\n \"\"\"Resizes an numpy array image to desired dimensions\"\"\"\n if not self.preserve_aspect_ratio:\n img = tf.image.resize(img, self.img_shape, method=self.resize_method)\n else:\n img = tf.image.resize_with_pad(img, *self.img_shape, method=self.resize_method)\n return tf.cast(img, self.dtype).numpy()\n\n\nclass FlattenedImageDataset(ImageDataset):\n \"\"\"Returns flattened versions of images read in from disk. This dataset can be\n used with the default neighbour retrieval method used by ivis (Annoy KNN index)\n since it is 2D.\"\"\"\n\n def __init__(self, filepath_list, img_shape, color_mode=\"rgb\",\n resize_method=\"bilinear\", preserve_aspect_ratio=False,\n dtype=tf.uint8, preprocessing_function=None):\n super().__init__(filepath_list, img_shape, color_mode, resize_method,\n preserve_aspect_ratio, dtype, preprocessing_function)\n self.shape = (self.shape[0], np.prod(self.shape[1:]))\n\n def __getitem__(self, idx):\n return super().__getitem__(idx).flatten()\n"
] |
[
[
"tensorflow.image.decode_png",
"tensorflow.cast",
"tensorflow.image.resize",
"numpy.prod",
"tensorflow.io.read_file",
"tensorflow.image.resize_with_pad",
"numpy.array"
]
] |
junekihong/beam-span-parser
|
[
"206e032409640556ac4765a5d15dc2f72fbddd74"
] |
[
"src/main.py"
] |
[
"import argparse\nimport itertools\nimport os.path\nimport time, timeit\nimport sys\n\nimport dynet as dy\nimport numpy as np\n\nimport evaluate\nimport parse\nimport trees\nimport vocabulary\nimport gc\nfrom collections import defaultdict\n\ndef format_elapsed(start_time):\n elapsed_time = int(time.time() - start_time)\n minutes, seconds = divmod(elapsed_time, 60)\n hours, minutes = divmod(minutes, 60)\n days, hours = divmod(hours, 24)\n elapsed_string = \"{}h{:02}m{:02}s\".format(hours, minutes, seconds)\n if days > 0:\n elapsed_string = \"{}d{}\".format(days, elapsed_string)\n return elapsed_string\n\ndef run_train(args):\n if args.numpy_seed is not None:\n print(\"Setting numpy random seed to {}...\".format(args.numpy_seed))\n np.random.seed(args.numpy_seed)\n\n sys.setrecursionlimit(10000)\n\n print(\"Loading training trees from {}...\".format(args.train_path))\n train_treebank = trees.load_trees(args.train_path)\n print(\"Loaded {:,} training examples.\".format(len(train_treebank)))\n print(\"Loading development trees from {}...\".format(args.dev_path))\n dev_treebank = trees.load_trees(args.dev_path)\n print(\"Loaded {:,} development examples.\".format(len(dev_treebank)))\n print(\"Processing trees for training...\")\n train_parse = [tree.convert() for tree in train_treebank]\n\n print(\"Constructing vocabularies...\")\n tag_vocab = vocabulary.Vocabulary()\n tag_vocab.index(parse.START)\n tag_vocab.index(parse.STOP)\n\n word_vocab = vocabulary.Vocabulary()\n word_vocab.index(parse.START)\n word_vocab.index(parse.STOP)\n word_vocab.index(parse.UNK)\n\n label_vocab = vocabulary.Vocabulary()\n label_vocab.index(())\n\n for tree in train_parse:\n nodes = [tree]\n while nodes:\n node = nodes.pop()\n if isinstance(node, trees.InternalParseNode):\n label_vocab.index(node.label)\n nodes.extend(reversed(node.children))\n else:\n tag_vocab.index(node.tag)\n word_vocab.index(node.word)\n tag_vocab.freeze()\n word_vocab.freeze()\n label_vocab.freeze()\n\n def print_vocabulary(name, vocab):\n special = {parse.START, parse.STOP, parse.UNK}\n print(\"{} ({:,}): {}\".format(\n name, vocab.size,\n sorted(value for value in vocab.values if value in special) +\n sorted(value for value in vocab.values if value not in special)))\n if args.print_vocabs:\n print_vocabulary(\"Tag\", tag_vocab)\n print_vocabulary(\"Word\", word_vocab)\n print_vocabulary(\"Label\", label_vocab)\n\n print(\"Initializing model...\")\n model = dy.ParameterCollection()\n if os.path.exists(args.model_path_base + \".meta\") and \\\n os.path.exists(args.model_path_base + \".data\"):\n [parser] = dy.load(args.model_path_base, model)\n args.model_path_base = args.model_path_base.split(\"_dev\")[0] + \"-cont\"\n elif args.parser_type == \"beam-parse\":\n parser = parse.BeamParser(\n model,\n tag_vocab,\n word_vocab,\n label_vocab,\n args.tag_embedding_dim,\n args.word_embedding_dim,\n args.lstm_layers,\n args.lstm_dim,\n args.label_hidden_dim,\n args.dropout,\n args.beamsize,\n )\n else:\n parser = parse.ChartParser(\n model,\n tag_vocab,\n word_vocab,\n label_vocab,\n args.tag_embedding_dim,\n args.word_embedding_dim,\n args.lstm_layers,\n args.lstm_dim,\n args.label_hidden_dim,\n args.dropout,\n )\n parser.cross_span = args.cross_span\n parser.cubepruning = False if args.nocubepruning else True\n\n trainer = dy.AdamTrainer(model)\n\n total_processed = 0\n current_processed = 0\n check_every = len(train_parse) / args.checks_per_epoch\n best_dev_fscore = -np.inf\n best_dev_model_path = None\n\n start_time = time.time()\n\n def check_dev():\n nonlocal best_dev_fscore\n nonlocal best_dev_model_path\n\n dev_start_time = time.time()\n\n dev_predicted = []\n for tree in dev_treebank:\n dy.renew_cg()\n sentence = [(leaf.tag, leaf.word) for leaf in tree.leaves()]\n predicted, _ = parser.parse(sentence)\n dev_predicted.append(predicted.convert())\n\n dev_fscore = evaluate.evalb(dev_treebank, dev_predicted)\n\n print(\n \"dev-fscore {} \"\n \"dev-elapsed {} \"\n \"total-elapsed {}\".format(\n dev_fscore,\n format_elapsed(dev_start_time),\n format_elapsed(start_time),\n )\n )\n\n if dev_fscore.fscore() > best_dev_fscore:\n if best_dev_model_path is not None:\n for ext in [\".data\", \".meta\"]:\n path = best_dev_model_path + ext\n if os.path.exists(path):\n print(\"Removing previous model file {}...\".format(path))\n os.remove(path)\n\n best_dev_fscore = dev_fscore.fscore()\n best_dev_model_path = \"{}_dev={:.2f}\".format(\n args.model_path_base, dev_fscore.fscore())\n print(\"Saving new best model to {}...\".format(best_dev_model_path))\n dy.save(best_dev_model_path, [parser])\n\n \n for epoch in itertools.count(start=1):\n if args.epochs is not None and epoch > args.epochs:\n break\n\n np.random.shuffle(train_parse)\n epoch_start_time = time.time()\n\n for start_index in range(0, len(train_parse), args.batch_size):\n dy.renew_cg()\n batch_losses = []\n for tree in train_parse[start_index:start_index + args.batch_size]:\n sentence = [(leaf.tag, leaf.word) for leaf in tree.leaves()]\n _, loss = parser.parse(sentence, tree)\n \n batch_losses.append(loss)\n total_processed += 1\n current_processed += 1\n\n batch_loss = dy.average(batch_losses)\n batch_loss_value = batch_loss.scalar_value()\n batch_loss.backward()\n trainer.update()\n\n print(\n \"epoch {:,} \"\n \"batch {:,}/{:,} \"\n \"processed {:,} \"\n \"batch-loss {:.4f} \"\n \"epoch-elapsed {} \"\n \"total-elapsed {}\".format(\n epoch,\n start_index // args.batch_size + 1,\n int(np.ceil(len(train_parse) / args.batch_size)),\n total_processed,\n batch_loss_value,\n format_elapsed(epoch_start_time),\n format_elapsed(start_time),\n )\n )\n if current_processed >= check_every:\n current_processed -= check_every\n check_dev()\n\n\ndef run_test(args):\n print(\"Loading test trees from {}...\".format(args.test_path))\n test_treebank = trees.load_trees(args.test_path)\n print(\"Loaded {:,} test examples.\".format(len(test_treebank)))\n\n print(\"Loading model from {}...\".format(args.model_path_base))\n model = dy.ParameterCollection()\n [parser] = dy.load(args.model_path_base, model)\n if args.beamsize is not None:\n parser.beamsize = args.beamsize\n if args.log:\n beamsize = \"\"\n if isinstance(parser, parse.BeamParser):\n parsertype = \"beam\"\n beamsize = args.beamsize if args.beamsize is not None else parser.beamsize\n elif isinstance(parser, parse.ChartParser):\n parsertype = \"chart\"\n beamsize = None\n log = open(\"log/{}_b{}.log\".format(parsertype, beamsize), \"w\")\n parser.cubepruning = False if args.nocubepruning else True\n\n test_predicted = []\n score_sum = 0.0\n\n print(\"Parsing test sentences...\")\n start_time = time.time()\n for i, tree in enumerate(test_treebank):\n #sys.stderr.write(\"{}\\r\".format(i))\n\n dy.renew_cg()\n sentence = [(leaf.tag, leaf.word) for leaf in tree.leaves()]\n\n if args.log:\n gc.disable()\n before = time.time()\n\n predicted, score = parser.parse(sentence)\n \n if args.log:\n elapsed = time.time() - before\n log_string = \"len {} model {:10.10} time {}\\n\".format(len(sentence), score.value(), elapsed)\n log.write(log_string)\n log.flush()\n gc.enable()\n\n test_predicted.append(predicted.convert())\n score_sum += score.value()\n\n total_elapsed = float(time.time() - start_time)\n test_fscore = evaluate.evalb(test_treebank, test_predicted)\n\n print(\n \"test-fscore {} \"\n \"test-elapsed {} \"\n \"\\ntotal model score {:10.10} \"\n \"\\nspeed: {}/{:5.5} = {:5.5} => {:5.5}\".format(\n test_fscore,\n format_elapsed(start_time),\n score_sum,\n len(test_treebank), total_elapsed, float(len(test_treebank)) / total_elapsed, float(total_elapsed) / len(test_treebank)\n )\n )\n\n\ndef main():\n dynet_args = [\n \"--dynet-mem\",\n \"--dynet-weight-decay\",\n \"--dynet-autobatch\",\n \"--dynet-gpus\",\n \"--dynet-gpu\",\n \"--dynet-devices\",\n \"--dynet-seed\",\n ]\n\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n\n subparser = subparsers.add_parser(\"train\")\n subparser.set_defaults(callback=run_train)\n\n for arg in dynet_args:\n subparser.add_argument(arg)\n subparser.add_argument(\"--numpy-seed\", type=int)\n subparser.add_argument(\"--parser-type\", choices=[\"chart\", \"beam-parse\"], required=True)\n subparser.add_argument(\"--tag-embedding-dim\", type=int, default=50)\n subparser.add_argument(\"--word-embedding-dim\", type=int, default=100)\n subparser.add_argument(\"--lstm-layers\", type=int, default=2)\n subparser.add_argument(\"--lstm-dim\", type=int, default=250)\n subparser.add_argument(\"--label-hidden-dim\", type=int, default=250)\n subparser.add_argument(\"--dropout\", type=float, default=0.4)\n subparser.add_argument(\"--model-path-base\", required=True)\n subparser.add_argument(\"--train-path\", default=\"data/02-21.10way.clean\")\n subparser.add_argument(\"--dev-path\", default=\"data/22.auto.clean\")\n subparser.add_argument(\"--batch-size\", type=int, default=10)\n subparser.add_argument(\"--epochs\", type=int)\n subparser.add_argument(\"--checks-per-epoch\", type=int, default=4)\n subparser.add_argument(\"--print-vocabs\", action=\"store_true\")\n subparser.add_argument(\"--beamsize\", type=int, default=None)\n subparser.add_argument(\"--cross-span\", default=False, action=\"store_true\")\n subparser.add_argument(\"--nocubepruning\", default=False, action=\"store_true\")\n\n subparser = subparsers.add_parser(\"test\")\n subparser.set_defaults(callback=run_test)\n for arg in dynet_args:\n subparser.add_argument(arg)\n subparser.add_argument(\"--model-path-base\", required=True)\n subparser.add_argument(\"--test-path\", default=\"data/23.auto.clean\")\n subparser.add_argument(\"--beamsize\", type=int, default=None)\n subparser.add_argument(\"--log\", default=False, action=\"store_true\")\n subparser.add_argument(\"--nocubepruning\", default=False, action=\"store_true\")\n\n args = parser.parse_args()\n args.callback(args)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.random.shuffle",
"numpy.random.seed"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.